github.com/etherbanking/go-etherbanking@v1.7.1-0.20181009210156-cf649bca5aba/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  	"fmt"
    22  	"math/big"
    23  	"sort"
    24  	"sync"
    25  
    26  	"github.com/etherbanking/go-etherbanking/common"
    27  	"github.com/etherbanking/go-etherbanking/core/types"
    28  	"github.com/etherbanking/go-etherbanking/crypto"
    29  	"github.com/etherbanking/go-etherbanking/log"
    30  	"github.com/etherbanking/go-etherbanking/rlp"
    31  	"github.com/etherbanking/go-etherbanking/trie"
    32  )
    33  
    34  type revision struct {
    35  	id           int
    36  	journalIndex int
    37  }
    38  
    39  // StateDBs within the ethereum protocol are used to store anything
    40  // within the merkle trie. StateDBs take care of caching and storing
    41  // nested states. It's the general query interface to retrieve:
    42  // * Contracts
    43  // * Accounts
    44  type StateDB struct {
    45  	db   Database
    46  	trie Trie
    47  
    48  	// This map holds 'live' objects, which will get modified while processing a state transition.
    49  	stateObjects      map[common.Address]*stateObject
    50  	stateObjectsDirty map[common.Address]struct{}
    51  
    52  	// DB error.
    53  	// State objects are used by the consensus core and VM which are
    54  	// unable to deal with database-level errors. Any error that occurs
    55  	// during a database read is memoized here and will eventually be returned
    56  	// by StateDB.Commit.
    57  	dbErr error
    58  
    59  	// The refund counter, also used by state transitioning.
    60  	refund *big.Int
    61  
    62  	thash, bhash common.Hash
    63  	txIndex      int
    64  	logs         map[common.Hash][]*types.Log
    65  	logSize      uint
    66  
    67  	preimages map[common.Hash][]byte
    68  
    69  	// Journal of state modifications. This is the backbone of
    70  	// Snapshot and RevertToSnapshot.
    71  	journal        journal
    72  	validRevisions []revision
    73  	nextRevisionId int
    74  
    75  	lock sync.Mutex
    76  }
    77  
    78  // Create a new state from a given trie
    79  func New(root common.Hash, db Database) (*StateDB, error) {
    80  	tr, err := db.OpenTrie(root)
    81  	if err != nil {
    82  		return nil, err
    83  	}
    84  	return &StateDB{
    85  		db:                db,
    86  		trie:              tr,
    87  		stateObjects:      make(map[common.Address]*stateObject),
    88  		stateObjectsDirty: make(map[common.Address]struct{}),
    89  		refund:            new(big.Int),
    90  		logs:              make(map[common.Hash][]*types.Log),
    91  		preimages:         make(map[common.Hash][]byte),
    92  	}, nil
    93  }
    94  
    95  // setError remembers the first non-nil error it is called with.
    96  func (self *StateDB) setError(err error) {
    97  	if self.dbErr == nil {
    98  		self.dbErr = err
    99  	}
   100  }
   101  
   102  func (self *StateDB) Error() error {
   103  	return self.dbErr
   104  }
   105  
   106  // Reset clears out all emphemeral state objects from the state db, but keeps
   107  // the underlying state trie to avoid reloading data for the next operations.
   108  func (self *StateDB) Reset(root common.Hash) error {
   109  	tr, err := self.db.OpenTrie(root)
   110  	if err != nil {
   111  		return err
   112  	}
   113  	self.trie = tr
   114  	self.stateObjects = make(map[common.Address]*stateObject)
   115  	self.stateObjectsDirty = make(map[common.Address]struct{})
   116  	self.thash = common.Hash{}
   117  	self.bhash = common.Hash{}
   118  	self.txIndex = 0
   119  	self.logs = make(map[common.Hash][]*types.Log)
   120  	self.logSize = 0
   121  	self.preimages = make(map[common.Hash][]byte)
   122  	self.clearJournalAndRefund()
   123  	return nil
   124  }
   125  
   126  func (self *StateDB) AddLog(log *types.Log) {
   127  	self.journal = append(self.journal, addLogChange{txhash: self.thash})
   128  
   129  	log.TxHash = self.thash
   130  	log.BlockHash = self.bhash
   131  	log.TxIndex = uint(self.txIndex)
   132  	log.Index = self.logSize
   133  	self.logs[self.thash] = append(self.logs[self.thash], log)
   134  	self.logSize++
   135  }
   136  
   137  func (self *StateDB) GetLogs(hash common.Hash) []*types.Log {
   138  	return self.logs[hash]
   139  }
   140  
   141  func (self *StateDB) Logs() []*types.Log {
   142  	var logs []*types.Log
   143  	for _, lgs := range self.logs {
   144  		logs = append(logs, lgs...)
   145  	}
   146  	return logs
   147  }
   148  
   149  // AddPreimage records a SHA3 preimage seen by the VM.
   150  func (self *StateDB) AddPreimage(hash common.Hash, preimage []byte) {
   151  	if _, ok := self.preimages[hash]; !ok {
   152  		self.journal = append(self.journal, addPreimageChange{hash: hash})
   153  		pi := make([]byte, len(preimage))
   154  		copy(pi, preimage)
   155  		self.preimages[hash] = pi
   156  	}
   157  }
   158  
   159  // Preimages returns a list of SHA3 preimages that have been submitted.
   160  func (self *StateDB) Preimages() map[common.Hash][]byte {
   161  	return self.preimages
   162  }
   163  
   164  func (self *StateDB) AddRefund(gas *big.Int) {
   165  	self.journal = append(self.journal, refundChange{prev: new(big.Int).Set(self.refund)})
   166  	self.refund.Add(self.refund, gas)
   167  }
   168  
   169  // Exist reports whether the given account address exists in the state.
   170  // Notably this also returns true for suicided accounts.
   171  func (self *StateDB) Exist(addr common.Address) bool {
   172  	return self.getStateObject(addr) != nil
   173  }
   174  
   175  // Empty returns whether the state object is either non-existent
   176  // or empty according to the EIP161 specification (balance = nonce = code = 0)
   177  func (self *StateDB) Empty(addr common.Address) bool {
   178  	so := self.getStateObject(addr)
   179  	return so == nil || so.empty()
   180  }
   181  
   182  // Retrieve the balance from the given address or 0 if object not found
   183  func (self *StateDB) GetBalance(addr common.Address) *big.Int {
   184  	stateObject := self.getStateObject(addr)
   185  	if stateObject != nil {
   186  		return stateObject.Balance()
   187  	}
   188  	return common.Big0
   189  }
   190  
   191  func (self *StateDB) GetNonce(addr common.Address) uint64 {
   192  	stateObject := self.getStateObject(addr)
   193  	if stateObject != nil {
   194  		return stateObject.Nonce()
   195  	}
   196  
   197  	return 0
   198  }
   199  
   200  func (self *StateDB) GetCode(addr common.Address) []byte {
   201  	stateObject := self.getStateObject(addr)
   202  	if stateObject != nil {
   203  		return stateObject.Code(self.db)
   204  	}
   205  	return nil
   206  }
   207  
   208  func (self *StateDB) GetCodeSize(addr common.Address) int {
   209  	stateObject := self.getStateObject(addr)
   210  	if stateObject == nil {
   211  		return 0
   212  	}
   213  	if stateObject.code != nil {
   214  		return len(stateObject.code)
   215  	}
   216  	size, err := self.db.ContractCodeSize(stateObject.addrHash, common.BytesToHash(stateObject.CodeHash()))
   217  	if err != nil {
   218  		self.setError(err)
   219  	}
   220  	return size
   221  }
   222  
   223  func (self *StateDB) GetCodeHash(addr common.Address) common.Hash {
   224  	stateObject := self.getStateObject(addr)
   225  	if stateObject == nil {
   226  		return common.Hash{}
   227  	}
   228  	return common.BytesToHash(stateObject.CodeHash())
   229  }
   230  
   231  func (self *StateDB) GetState(a common.Address, b common.Hash) common.Hash {
   232  	stateObject := self.getStateObject(a)
   233  	if stateObject != nil {
   234  		return stateObject.GetState(self.db, b)
   235  	}
   236  	return common.Hash{}
   237  }
   238  
   239  // StorageTrie returns the storage trie of an account.
   240  // The return value is a copy and is nil for non-existent accounts.
   241  func (self *StateDB) StorageTrie(a common.Address) Trie {
   242  	stateObject := self.getStateObject(a)
   243  	if stateObject == nil {
   244  		return nil
   245  	}
   246  	cpy := stateObject.deepCopy(self, nil)
   247  	return cpy.updateTrie(self.db)
   248  }
   249  
   250  func (self *StateDB) HasSuicided(addr common.Address) bool {
   251  	stateObject := self.getStateObject(addr)
   252  	if stateObject != nil {
   253  		return stateObject.suicided
   254  	}
   255  	return false
   256  }
   257  
   258  /*
   259   * SETTERS
   260   */
   261  
   262  // AddBalance adds amount to the account associated with addr
   263  func (self *StateDB) AddBalance(addr common.Address, amount *big.Int) {
   264  	stateObject := self.GetOrNewStateObject(addr)
   265  	if stateObject != nil {
   266  		stateObject.AddBalance(amount)
   267  	}
   268  }
   269  
   270  // SubBalance subtracts amount from the account associated with addr
   271  func (self *StateDB) SubBalance(addr common.Address, amount *big.Int) {
   272  	stateObject := self.GetOrNewStateObject(addr)
   273  	if stateObject != nil {
   274  		stateObject.SubBalance(amount)
   275  	}
   276  }
   277  
   278  func (self *StateDB) SetBalance(addr common.Address, amount *big.Int) {
   279  	stateObject := self.GetOrNewStateObject(addr)
   280  	if stateObject != nil {
   281  		stateObject.SetBalance(amount)
   282  	}
   283  }
   284  
   285  func (self *StateDB) SetNonce(addr common.Address, nonce uint64) {
   286  	stateObject := self.GetOrNewStateObject(addr)
   287  	if stateObject != nil {
   288  		stateObject.SetNonce(nonce)
   289  	}
   290  }
   291  
   292  func (self *StateDB) SetCode(addr common.Address, code []byte) {
   293  	stateObject := self.GetOrNewStateObject(addr)
   294  	if stateObject != nil {
   295  		stateObject.SetCode(crypto.Keccak256Hash(code), code)
   296  	}
   297  }
   298  
   299  func (self *StateDB) SetState(addr common.Address, key common.Hash, value common.Hash) {
   300  	stateObject := self.GetOrNewStateObject(addr)
   301  	if stateObject != nil {
   302  		stateObject.SetState(self.db, key, value)
   303  	}
   304  }
   305  
   306  // Suicide marks the given account as suicided.
   307  // This clears the account balance.
   308  //
   309  // The account's state object is still available until the state is committed,
   310  // getStateObject will return a non-nil account after Suicide.
   311  func (self *StateDB) Suicide(addr common.Address) bool {
   312  	stateObject := self.getStateObject(addr)
   313  	if stateObject == nil {
   314  		return false
   315  	}
   316  	self.journal = append(self.journal, suicideChange{
   317  		account:     &addr,
   318  		prev:        stateObject.suicided,
   319  		prevbalance: new(big.Int).Set(stateObject.Balance()),
   320  	})
   321  	stateObject.markSuicided()
   322  	stateObject.data.Balance = new(big.Int)
   323  
   324  	return true
   325  }
   326  
   327  //
   328  // Setting, updating & deleting state object methods
   329  //
   330  
   331  // updateStateObject writes the given object to the trie.
   332  func (self *StateDB) updateStateObject(stateObject *stateObject) {
   333  	addr := stateObject.Address()
   334  	data, err := rlp.EncodeToBytes(stateObject)
   335  	if err != nil {
   336  		panic(fmt.Errorf("can't encode object at %x: %v", addr[:], err))
   337  	}
   338  	self.setError(self.trie.TryUpdate(addr[:], data))
   339  }
   340  
   341  // deleteStateObject removes the given object from the state trie.
   342  func (self *StateDB) deleteStateObject(stateObject *stateObject) {
   343  	stateObject.deleted = true
   344  	addr := stateObject.Address()
   345  	self.setError(self.trie.TryDelete(addr[:]))
   346  }
   347  
   348  // Retrieve a state object given my the address. Returns nil if not found.
   349  func (self *StateDB) getStateObject(addr common.Address) (stateObject *stateObject) {
   350  	// Prefer 'live' objects.
   351  	if obj := self.stateObjects[addr]; obj != nil {
   352  		if obj.deleted {
   353  			return nil
   354  		}
   355  		return obj
   356  	}
   357  
   358  	// Load the object from the database.
   359  	enc, err := self.trie.TryGet(addr[:])
   360  	if len(enc) == 0 {
   361  		self.setError(err)
   362  		return nil
   363  	}
   364  	var data Account
   365  	if err := rlp.DecodeBytes(enc, &data); err != nil {
   366  		log.Error("Failed to decode state object", "addr", addr, "err", err)
   367  		return nil
   368  	}
   369  	// Insert into the live set.
   370  	obj := newObject(self, addr, data, self.MarkStateObjectDirty)
   371  	self.setStateObject(obj)
   372  	return obj
   373  }
   374  
   375  func (self *StateDB) setStateObject(object *stateObject) {
   376  	self.stateObjects[object.Address()] = object
   377  }
   378  
   379  // Retrieve a state object or create a new state object if nil
   380  func (self *StateDB) GetOrNewStateObject(addr common.Address) *stateObject {
   381  	stateObject := self.getStateObject(addr)
   382  	if stateObject == nil || stateObject.deleted {
   383  		stateObject, _ = self.createObject(addr)
   384  	}
   385  	return stateObject
   386  }
   387  
   388  // MarkStateObjectDirty adds the specified object to the dirty map to avoid costly
   389  // state object cache iteration to find a handful of modified ones.
   390  func (self *StateDB) MarkStateObjectDirty(addr common.Address) {
   391  	self.stateObjectsDirty[addr] = struct{}{}
   392  }
   393  
   394  // createObject creates a new state object. If there is an existing account with
   395  // the given address, it is overwritten and returned as the second return value.
   396  func (self *StateDB) createObject(addr common.Address) (newobj, prev *stateObject) {
   397  	prev = self.getStateObject(addr)
   398  	newobj = newObject(self, addr, Account{}, self.MarkStateObjectDirty)
   399  	newobj.setNonce(0) // sets the object to dirty
   400  	if prev == nil {
   401  		self.journal = append(self.journal, createObjectChange{account: &addr})
   402  	} else {
   403  		self.journal = append(self.journal, resetObjectChange{prev: prev})
   404  	}
   405  	self.setStateObject(newobj)
   406  	return newobj, prev
   407  }
   408  
   409  // CreateAccount explicitly creates a state object. If a state object with the address
   410  // already exists the balance is carried over to the new account.
   411  //
   412  // CreateAccount is called during the EVM CREATE operation. The situation might arise that
   413  // a contract does the following:
   414  //
   415  //   1. sends funds to sha(account ++ (nonce + 1))
   416  //   2. tx_create(sha(account ++ nonce)) (note that this gets the address of 1)
   417  //
   418  // Carrying over the balance ensures that Ether doesn't disappear.
   419  func (self *StateDB) CreateAccount(addr common.Address) {
   420  	new, prev := self.createObject(addr)
   421  	if prev != nil {
   422  		new.setBalance(prev.data.Balance)
   423  	}
   424  }
   425  
   426  func (db *StateDB) ForEachStorage(addr common.Address, cb func(key, value common.Hash) bool) {
   427  	so := db.getStateObject(addr)
   428  	if so == nil {
   429  		return
   430  	}
   431  
   432  	// When iterating over the storage check the cache first
   433  	for h, value := range so.cachedStorage {
   434  		cb(h, value)
   435  	}
   436  
   437  	it := trie.NewIterator(so.getTrie(db.db).NodeIterator(nil))
   438  	for it.Next() {
   439  		// ignore cached values
   440  		key := common.BytesToHash(db.trie.GetKey(it.Key))
   441  		if _, ok := so.cachedStorage[key]; !ok {
   442  			cb(key, common.BytesToHash(it.Value))
   443  		}
   444  	}
   445  }
   446  
   447  // Copy creates a deep, independent copy of the state.
   448  // Snapshots of the copied state cannot be applied to the copy.
   449  func (self *StateDB) Copy() *StateDB {
   450  	self.lock.Lock()
   451  	defer self.lock.Unlock()
   452  
   453  	// Copy all the basic fields, initialize the memory ones
   454  	state := &StateDB{
   455  		db:                self.db,
   456  		trie:              self.trie,
   457  		stateObjects:      make(map[common.Address]*stateObject, len(self.stateObjectsDirty)),
   458  		stateObjectsDirty: make(map[common.Address]struct{}, len(self.stateObjectsDirty)),
   459  		refund:            new(big.Int).Set(self.refund),
   460  		logs:              make(map[common.Hash][]*types.Log, len(self.logs)),
   461  		logSize:           self.logSize,
   462  		preimages:         make(map[common.Hash][]byte),
   463  	}
   464  	// Copy the dirty states, logs, and preimages
   465  	for addr := range self.stateObjectsDirty {
   466  		state.stateObjects[addr] = self.stateObjects[addr].deepCopy(state, state.MarkStateObjectDirty)
   467  		state.stateObjectsDirty[addr] = struct{}{}
   468  	}
   469  	for hash, logs := range self.logs {
   470  		state.logs[hash] = make([]*types.Log, len(logs))
   471  		copy(state.logs[hash], logs)
   472  	}
   473  	for hash, preimage := range self.preimages {
   474  		state.preimages[hash] = preimage
   475  	}
   476  	return state
   477  }
   478  
   479  // Snapshot returns an identifier for the current revision of the state.
   480  func (self *StateDB) Snapshot() int {
   481  	id := self.nextRevisionId
   482  	self.nextRevisionId++
   483  	self.validRevisions = append(self.validRevisions, revision{id, len(self.journal)})
   484  	return id
   485  }
   486  
   487  // RevertToSnapshot reverts all state changes made since the given revision.
   488  func (self *StateDB) RevertToSnapshot(revid int) {
   489  	// Find the snapshot in the stack of valid snapshots.
   490  	idx := sort.Search(len(self.validRevisions), func(i int) bool {
   491  		return self.validRevisions[i].id >= revid
   492  	})
   493  	if idx == len(self.validRevisions) || self.validRevisions[idx].id != revid {
   494  		panic(fmt.Errorf("revision id %v cannot be reverted", revid))
   495  	}
   496  	snapshot := self.validRevisions[idx].journalIndex
   497  
   498  	// Replay the journal to undo changes.
   499  	for i := len(self.journal) - 1; i >= snapshot; i-- {
   500  		self.journal[i].undo(self)
   501  	}
   502  	self.journal = self.journal[:snapshot]
   503  
   504  	// Remove invalidated snapshots from the stack.
   505  	self.validRevisions = self.validRevisions[:idx]
   506  }
   507  
   508  // GetRefund returns the current value of the refund counter.
   509  // The return value must not be modified by the caller and will become
   510  // invalid at the next call to AddRefund.
   511  func (self *StateDB) GetRefund() *big.Int {
   512  	return self.refund
   513  }
   514  
   515  // Finalise finalises the state by removing the self destructed objects
   516  // and clears the journal as well as the refunds.
   517  func (s *StateDB) Finalise(deleteEmptyObjects bool) {
   518  	for addr := range s.stateObjectsDirty {
   519  		stateObject := s.stateObjects[addr]
   520  		if stateObject.suicided || (deleteEmptyObjects && stateObject.empty()) {
   521  			s.deleteStateObject(stateObject)
   522  		} else {
   523  			stateObject.updateRoot(s.db)
   524  			s.updateStateObject(stateObject)
   525  		}
   526  	}
   527  	// Invalidate journal because reverting across transactions is not allowed.
   528  	s.clearJournalAndRefund()
   529  }
   530  
   531  // IntermediateRoot computes the current root hash of the state trie.
   532  // It is called in between transactions to get the root hash that
   533  // goes into transaction receipts.
   534  func (s *StateDB) IntermediateRoot(deleteEmptyObjects bool) common.Hash {
   535  	s.Finalise(deleteEmptyObjects)
   536  	return s.trie.Hash()
   537  }
   538  
   539  // Prepare sets the current transaction hash and index and block hash which is
   540  // used when the EVM emits new state logs.
   541  func (self *StateDB) Prepare(thash, bhash common.Hash, ti int) {
   542  	self.thash = thash
   543  	self.bhash = bhash
   544  	self.txIndex = ti
   545  }
   546  
   547  // DeleteSuicides flags the suicided objects for deletion so that it
   548  // won't be referenced again when called / queried up on.
   549  //
   550  // DeleteSuicides should not be used for consensus related updates
   551  // under any circumstances.
   552  func (s *StateDB) DeleteSuicides() {
   553  	// Reset refund so that any used-gas calculations can use this method.
   554  	s.clearJournalAndRefund()
   555  
   556  	for addr := range s.stateObjectsDirty {
   557  		stateObject := s.stateObjects[addr]
   558  
   559  		// If the object has been removed by a suicide
   560  		// flag the object as deleted.
   561  		if stateObject.suicided {
   562  			stateObject.deleted = true
   563  		}
   564  		delete(s.stateObjectsDirty, addr)
   565  	}
   566  }
   567  
   568  func (s *StateDB) clearJournalAndRefund() {
   569  	s.journal = nil
   570  	s.validRevisions = s.validRevisions[:0]
   571  	s.refund = new(big.Int)
   572  }
   573  
   574  // CommitTo writes the state to the given database.
   575  func (s *StateDB) CommitTo(dbw trie.DatabaseWriter, deleteEmptyObjects bool) (root common.Hash, err error) {
   576  	defer s.clearJournalAndRefund()
   577  
   578  	// Commit objects to the trie.
   579  	for addr, stateObject := range s.stateObjects {
   580  		_, isDirty := s.stateObjectsDirty[addr]
   581  		switch {
   582  		case stateObject.suicided || (isDirty && deleteEmptyObjects && stateObject.empty()):
   583  			// If the object has been removed, don't bother syncing it
   584  			// and just mark it for deletion in the trie.
   585  			s.deleteStateObject(stateObject)
   586  		case isDirty:
   587  			// Write any contract code associated with the state object
   588  			if stateObject.code != nil && stateObject.dirtyCode {
   589  				if err := dbw.Put(stateObject.CodeHash(), stateObject.code); err != nil {
   590  					return common.Hash{}, err
   591  				}
   592  				stateObject.dirtyCode = false
   593  			}
   594  			// Write any storage changes in the state object to its storage trie.
   595  			if err := stateObject.CommitTrie(s.db, dbw); err != nil {
   596  				return common.Hash{}, err
   597  			}
   598  			// Update the object in the main account trie.
   599  			s.updateStateObject(stateObject)
   600  		}
   601  		delete(s.stateObjectsDirty, addr)
   602  	}
   603  	// Write trie changes.
   604  	root, err = s.trie.CommitTo(dbw)
   605  	log.Debug("Trie cache stats after commit", "misses", trie.CacheMisses(), "unloads", trie.CacheUnloads())
   606  	return root, err
   607  }