github.com/CommerciumBlockchain/go-commercium@v0.0.0-20220709212705-b46438a77516/core/state/state_object.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
    18  
    19  import (
    20  	"bytes"
    21  	"fmt"
    22  	"io"
    23  	"math/big"
    24  	"time"
    25  
    26  	"github.com/CommerciumBlockchain/go-commercium/common"
    27  	"github.com/CommerciumBlockchain/go-commercium/crypto"
    28  	"github.com/CommerciumBlockchain/go-commercium/crypto/fixed"
    29  	"github.com/CommerciumBlockchain/go-commercium/metrics"
    30  	"github.com/CommerciumBlockchain/go-commercium/rlp"
    31  )
    32  
    33  var emptyCodeHash = crypto.Keccak256(nil)
    34  
    35  type Code []byte
    36  
    37  func (c Code) String() string {
    38  	return string(c) //strings.Join(Disassemble(c), " ")
    39  }
    40  
    41  type Storage map[common.Hash]common.Hash
    42  
    43  func (s Storage) String() (str string) {
    44  	for key, value := range s {
    45  		str += fmt.Sprintf("%X : %X\n", key, value)
    46  	}
    47  
    48  	return
    49  }
    50  
    51  func (s Storage) Copy() Storage {
    52  	cpy := make(Storage)
    53  	for key, value := range s {
    54  		cpy[key] = value
    55  	}
    56  
    57  	return cpy
    58  }
    59  
    60  // stateObject represents an Ethereum account which is being modified.
    61  //
    62  // The usage pattern is as follows:
    63  // First you need to obtain a state object.
    64  // Account values can be accessed and modified through the object.
    65  // Finally, call CommitTrie to write the modified storage trie into a database.
    66  type stateObject struct {
    67  	address  common.Address
    68  	addrHash common.Hash // hash of ethereum address of the account
    69  	data     Account
    70  	db       *StateDB
    71  
    72  	// DB error.
    73  	// State objects are used by the consensus core and VM which are
    74  	// unable to deal with database-level errors. Any error that occurs
    75  	// during a database read is memoized here and will eventually be returned
    76  	// by StateDB.Commit.
    77  	dbErr error
    78  
    79  	// Write caches.
    80  	trie Trie // storage trie, which becomes non-nil on first access
    81  	code Code // contract bytecode, which gets set when code is loaded
    82  
    83  	originStorage  Storage // Storage cache of original entries to dedup rewrites, reset for every transaction
    84  	pendingStorage Storage // Storage entries that need to be flushed to disk, at the end of an entire block
    85  	dirtyStorage   Storage // Storage entries that have been modified in the current transaction execution
    86  	fakeStorage    Storage // Fake storage which constructed by caller for debugging purpose.
    87  
    88  	// Cache flags.
    89  	// When an object is marked suicided it will be delete from the trie
    90  	// during the "update" phase of the state transition.
    91  	dirtyCode bool // true if the code was updated
    92  	suicided  bool
    93  	deleted   bool
    94  }
    95  
    96  // empty returns whether the account is considered empty.
    97  func (s *stateObject) empty() bool {
    98  	return s.data.Nonce == 0 && s.data.Balance.Sign() == 0 && bytes.Equal(s.data.CodeHash, emptyCodeHash)
    99  }
   100  
   101  // Account is the Ethereum consensus representation of accounts.
   102  // These objects are stored in the main account trie.
   103  type Account struct {
   104  	Nonce    uint64
   105  	Balance  *big.Int
   106  	Root     common.Hash // merkle root of the storage trie
   107  	CodeHash []byte
   108  }
   109  
   110  // newObject creates a state object.
   111  func newObject(db *StateDB, address common.Address, data Account) *stateObject {
   112  	if data.Balance == nil {
   113  		data.Balance = new(big.Int)
   114  	}
   115  	if data.CodeHash == nil {
   116  		data.CodeHash = emptyCodeHash
   117  	}
   118  	if data.Root == (common.Hash{}) {
   119  		data.Root = emptyRoot
   120  	}
   121  	return &stateObject{
   122  		db:             db,
   123  		address:        address,
   124  		addrHash:       fixed.LegacyKeccak20(address),
   125  		data:           data,
   126  		originStorage:  make(Storage),
   127  		pendingStorage: make(Storage),
   128  		dirtyStorage:   make(Storage),
   129  	}
   130  }
   131  
   132  // EncodeRLP implements rlp.Encoder.
   133  func (s *stateObject) EncodeRLP(w io.Writer) error {
   134  	return rlp.Encode(w, s.data)
   135  }
   136  
   137  // setError remembers the first non-nil error it is called with.
   138  func (s *stateObject) setError(err error) {
   139  	if s.dbErr == nil {
   140  		s.dbErr = err
   141  	}
   142  }
   143  
   144  func (s *stateObject) markSuicided() {
   145  	s.suicided = true
   146  }
   147  
   148  func (s *stateObject) touch() {
   149  	s.db.journal.append(touchChange{
   150  		account: &s.address,
   151  	})
   152  	if s.address == ripemd {
   153  		// Explicitly put it in the dirty-cache, which is otherwise generated from
   154  		// flattened journals.
   155  		s.db.journal.dirty(s.address)
   156  	}
   157  }
   158  
   159  func (s *stateObject) getTrie(db Database) Trie {
   160  	if s.trie == nil {
   161  		var err error
   162  		s.trie, err = db.OpenStorageTrie(s.addrHash, s.data.Root)
   163  		if err != nil {
   164  			s.trie, _ = db.OpenStorageTrie(s.addrHash, common.Hash{})
   165  			s.setError(fmt.Errorf("can't create storage trie: %v", err))
   166  		}
   167  	}
   168  	return s.trie
   169  }
   170  
   171  // GetState retrieves a value from the account storage trie.
   172  func (s *stateObject) GetState(db Database, key common.Hash) common.Hash {
   173  	// If the fake storage is set, only lookup the state here(in the debugging mode)
   174  	if s.fakeStorage != nil {
   175  		return s.fakeStorage[key]
   176  	}
   177  	// If we have a dirty value for this state entry, return it
   178  	value, dirty := s.dirtyStorage[key]
   179  	if dirty {
   180  		return value
   181  	}
   182  	// Otherwise return the entry's original value
   183  	return s.GetCommittedState(db, key)
   184  }
   185  
   186  // GetCommittedState retrieves a value from the committed account storage trie.
   187  func (s *stateObject) GetCommittedState(db Database, key common.Hash) common.Hash {
   188  	// If the fake storage is set, only lookup the state here(in the debugging mode)
   189  	if s.fakeStorage != nil {
   190  		return s.fakeStorage[key]
   191  	}
   192  	// If we have a pending write or clean cached, return that
   193  	if value, pending := s.pendingStorage[key]; pending {
   194  		return value
   195  	}
   196  	if value, cached := s.originStorage[key]; cached {
   197  		return value
   198  	}
   199  	// If no live objects are available, attempt to use snapshots
   200  	var (
   201  		enc []byte
   202  		err error
   203  	)
   204  	if s.db.snap != nil {
   205  		if metrics.EnabledExpensive {
   206  			defer func(start time.Time) { s.db.SnapshotStorageReads += time.Since(start) }(time.Now())
   207  		}
   208  		// If the object was destructed in *this* block (and potentially resurrected),
   209  		// the storage has been cleared out, and we should *not* consult the previous
   210  		// snapshot about any storage values. The only possible alternatives are:
   211  		//   1) resurrect happened, and new slot values were set -- those should
   212  		//      have been handles via pendingStorage above.
   213  		//   2) we don't have new values, and can deliver empty response back
   214  		if _, destructed := s.db.snapDestructs[s.addrHash]; destructed {
   215  			return common.Hash{}
   216  		}
   217  		enc, err = s.db.snap.Storage(s.addrHash, fixed.LegacyKeccak32(key))
   218  	}
   219  	// If snapshot unavailable or reading from it failed, load from the database
   220  	if s.db.snap == nil || err != nil {
   221  		if metrics.EnabledExpensive {
   222  			defer func(start time.Time) { s.db.StorageReads += time.Since(start) }(time.Now())
   223  		}
   224  		if enc, err = s.getTrie(db).TryGetHash(key); err != nil {
   225  			s.setError(err)
   226  			return common.Hash{}
   227  		}
   228  	}
   229  	var value common.Hash
   230  	if len(enc) > 0 {
   231  		_, content, _, err := rlp.Split(enc)
   232  		if err != nil {
   233  			s.setError(err)
   234  		}
   235  		value.SetBytes(content)
   236  	}
   237  	s.originStorage[key] = value
   238  	return value
   239  }
   240  
   241  // SetState updates a value in account storage.
   242  func (s *stateObject) SetState(db Database, key, value common.Hash) {
   243  	// If the fake storage is set, put the temporary state update here.
   244  	if s.fakeStorage != nil {
   245  		s.fakeStorage[key] = value
   246  		return
   247  	}
   248  	// If the new value is the same as old, don't set
   249  	prev := s.GetState(db, key)
   250  	if prev == value {
   251  		return
   252  	}
   253  	// New value is different, update and journal the change
   254  	s.db.journal.append(storageChange{
   255  		account:  &s.address,
   256  		key:      key,
   257  		prevalue: prev,
   258  	})
   259  	s.setState(key, value)
   260  }
   261  
   262  // SetStorage replaces the entire state storage with the given one.
   263  //
   264  // After this function is called, all original state will be ignored and state
   265  // lookup only happens in the fake state storage.
   266  //
   267  // Note this function should only be used for debugging purpose.
   268  func (s *stateObject) SetStorage(storage map[common.Hash]common.Hash) {
   269  	// Allocate fake storage if it's nil.
   270  	if s.fakeStorage == nil {
   271  		s.fakeStorage = make(Storage)
   272  	}
   273  	for key, value := range storage {
   274  		s.fakeStorage[key] = value
   275  	}
   276  	// Don't bother journal since this function should only be used for
   277  	// debugging and the `fake` storage won't be committed to database.
   278  }
   279  
   280  func (s *stateObject) setState(key, value common.Hash) {
   281  	s.dirtyStorage[key] = value
   282  }
   283  
   284  // finalise moves all dirty storage slots into the pending area to be hashed or
   285  // committed later. It is invoked at the end of every transaction.
   286  func (s *stateObject) finalise() {
   287  	for key, value := range s.dirtyStorage {
   288  		s.pendingStorage[key] = value
   289  	}
   290  	if len(s.dirtyStorage) > 0 {
   291  		s.dirtyStorage = make(Storage)
   292  	}
   293  }
   294  
   295  // updateTrie writes cached storage modifications into the object's storage trie.
   296  // It will return nil if the trie has not been loaded and no changes have been made
   297  func (s *stateObject) updateTrie(db Database) Trie {
   298  	// Make sure all dirty slots are finalized into the pending storage area
   299  	s.finalise()
   300  	if len(s.pendingStorage) == 0 {
   301  		return s.trie
   302  	}
   303  	// Track the amount of time wasted on updating the storage trie
   304  	if metrics.EnabledExpensive {
   305  		defer func(start time.Time) { s.db.StorageUpdates += time.Since(start) }(time.Now())
   306  	}
   307  	// Retrieve the snapshot storage map for the object
   308  	var storage map[common.Hash][]byte
   309  	if s.db.snap != nil {
   310  		// Retrieve the old storage map, if available, create a new one otherwise
   311  		storage = s.db.snapStorage[s.addrHash]
   312  		if storage == nil {
   313  			storage = make(map[common.Hash][]byte)
   314  			s.db.snapStorage[s.addrHash] = storage
   315  		}
   316  	}
   317  	// Insert all the pending updates into the trie
   318  	tr := s.getTrie(db)
   319  	for key, value := range s.pendingStorage {
   320  		// Skip noop changes, persist actual changes
   321  		if value == s.originStorage[key] {
   322  			continue
   323  		}
   324  		s.originStorage[key] = value
   325  
   326  		var v []byte
   327  		if (value == common.Hash{}) {
   328  			s.setError(tr.TryDeleteHash(key))
   329  		} else {
   330  			// Encoding []byte cannot fail, ok to ignore the error.
   331  			v, _ = rlp.EncodeToBytes(common.TrimLeftZeroes(value[:]))
   332  			s.setError(tr.TryUpdateHash(key, v))
   333  		}
   334  		// If state snapshotting is active, cache the data til commit
   335  		if storage != nil {
   336  			storage[fixed.LegacyKeccak32(key)] = v // v will be nil if value is 0x00
   337  		}
   338  	}
   339  	if len(s.pendingStorage) > 0 {
   340  		s.pendingStorage = make(Storage)
   341  	}
   342  	return tr
   343  }
   344  
   345  // UpdateRoot sets the trie root to the current root hash of
   346  func (s *stateObject) updateRoot(db Database) {
   347  	// If nothing changed, don't bother with hashing anything
   348  	if s.updateTrie(db) == nil {
   349  		return
   350  	}
   351  	// Track the amount of time wasted on hashing the storage trie
   352  	if metrics.EnabledExpensive {
   353  		defer func(start time.Time) { s.db.StorageHashes += time.Since(start) }(time.Now())
   354  	}
   355  	s.data.Root = s.trie.Hash()
   356  }
   357  
   358  // CommitTrie the storage trie of the object to db.
   359  // This updates the trie root.
   360  func (s *stateObject) CommitTrie(db Database) error {
   361  	// If nothing changed, don't bother with hashing anything
   362  	if s.updateTrie(db) == nil {
   363  		return nil
   364  	}
   365  	if s.dbErr != nil {
   366  		return s.dbErr
   367  	}
   368  	// Track the amount of time wasted on committing the storage trie
   369  	if metrics.EnabledExpensive {
   370  		defer func(start time.Time) { s.db.StorageCommits += time.Since(start) }(time.Now())
   371  	}
   372  	root, err := s.trie.Commit(nil)
   373  	if err == nil {
   374  		s.data.Root = root
   375  	}
   376  	return err
   377  }
   378  
   379  // AddBalance adds amount to s's balance.
   380  // It is used to add funds to the destination account of a transfer.
   381  func (s *stateObject) AddBalance(amount *big.Int) {
   382  	// EIP161: We must check emptiness for the objects such that the account
   383  	// clearing (0,0,0 objects) can take effect.
   384  	if amount.Sign() == 0 {
   385  		if s.empty() {
   386  			s.touch()
   387  		}
   388  		return
   389  	}
   390  	s.SetBalance(new(big.Int).Add(s.Balance(), amount))
   391  }
   392  
   393  // SubBalance removes amount from s's balance.
   394  // It is used to remove funds from the origin account of a transfer.
   395  func (s *stateObject) SubBalance(amount *big.Int) {
   396  	if amount.Sign() == 0 {
   397  		return
   398  	}
   399  	s.SetBalance(new(big.Int).Sub(s.Balance(), amount))
   400  }
   401  
   402  func (s *stateObject) SetBalance(amount *big.Int) {
   403  	s.db.journal.append(balanceChange{
   404  		account: &s.address,
   405  		prev:    new(big.Int).Set(s.data.Balance),
   406  	})
   407  	s.setBalance(amount)
   408  }
   409  
   410  func (s *stateObject) setBalance(amount *big.Int) {
   411  	s.data.Balance = amount
   412  }
   413  
   414  // Return the gas back to the origin. Used by the Virtual machine or Closures
   415  func (s *stateObject) ReturnGas(gas *big.Int) {}
   416  
   417  func (s *stateObject) deepCopy(db *StateDB) *stateObject {
   418  	stateObject := newObject(db, s.address, s.data)
   419  	if s.trie != nil {
   420  		stateObject.trie = db.db.CopyTrie(s.trie)
   421  	}
   422  	stateObject.code = s.code
   423  	stateObject.dirtyStorage = s.dirtyStorage.Copy()
   424  	stateObject.originStorage = s.originStorage.Copy()
   425  	stateObject.pendingStorage = s.pendingStorage.Copy()
   426  	stateObject.suicided = s.suicided
   427  	stateObject.dirtyCode = s.dirtyCode
   428  	stateObject.deleted = s.deleted
   429  	return stateObject
   430  }
   431  
   432  //
   433  // Attribute accessors
   434  //
   435  
   436  // Returns the address of the contract/account
   437  func (s *stateObject) Address() common.Address {
   438  	return s.address
   439  }
   440  
   441  // Code returns the contract code associated with this object, if any.
   442  func (s *stateObject) Code(db Database) []byte {
   443  	if s.code != nil {
   444  		return s.code
   445  	}
   446  	if bytes.Equal(s.CodeHash(), emptyCodeHash) {
   447  		return nil
   448  	}
   449  	code, err := db.ContractCode(s.addrHash, common.BytesToHash(s.CodeHash()))
   450  	if err != nil {
   451  		s.setError(fmt.Errorf("can't load code hash %x: %v", s.CodeHash(), err))
   452  	}
   453  	s.code = code
   454  	return code
   455  }
   456  
   457  // CodeSize returns the size of the contract code associated with this object,
   458  // or zero if none. This method is an almost mirror of Code, but uses a cache
   459  // inside the database to avoid loading codes seen recently.
   460  func (s *stateObject) CodeSize(db Database) int {
   461  	if s.code != nil {
   462  		return len(s.code)
   463  	}
   464  	if bytes.Equal(s.CodeHash(), emptyCodeHash) {
   465  		return 0
   466  	}
   467  	size, err := db.ContractCodeSize(s.addrHash, common.BytesToHash(s.CodeHash()))
   468  	if err != nil {
   469  		s.setError(fmt.Errorf("can't load code size %x: %v", s.CodeHash(), err))
   470  	}
   471  	return size
   472  }
   473  
   474  func (s *stateObject) SetCode(codeHash common.Hash, code []byte) {
   475  	prevcode := s.Code(s.db.db)
   476  	s.db.journal.append(codeChange{
   477  		account:  &s.address,
   478  		prevhash: s.CodeHash(),
   479  		prevcode: prevcode,
   480  	})
   481  	s.setCode(codeHash, code)
   482  }
   483  
   484  func (s *stateObject) setCode(codeHash common.Hash, code []byte) {
   485  	s.code = code
   486  	s.data.CodeHash = codeHash[:]
   487  	s.dirtyCode = true
   488  }
   489  
   490  func (s *stateObject) SetNonce(nonce uint64) {
   491  	s.db.journal.append(nonceChange{
   492  		account: &s.address,
   493  		prev:    s.data.Nonce,
   494  	})
   495  	s.setNonce(nonce)
   496  }
   497  
   498  func (s *stateObject) setNonce(nonce uint64) {
   499  	s.data.Nonce = nonce
   500  }
   501  
   502  func (s *stateObject) CodeHash() []byte {
   503  	return s.data.CodeHash
   504  }
   505  
   506  func (s *stateObject) Balance() *big.Int {
   507  	return s.data.Balance
   508  }
   509  
   510  func (s *stateObject) Nonce() uint64 {
   511  	return s.data.Nonce
   512  }
   513  
   514  // Never called, but must be present to allow stateObject to be used
   515  // as a vm.Account interface that also satisfies the vm.ContractRef
   516  // interface. Interfaces are awesome.
   517  func (s *stateObject) Value() *big.Int {
   518  	panic("Value on stateObject should never be called")
   519  }