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