github.com/shrimpyuk/bor@v0.2.15-0.20220224151350-fb4ec6020bae/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/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/metrics"
    30  	"github.com/ethereum/go-ethereum/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     types.StateAccount
    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  // newObject creates a state object.
   102  func newObject(db *StateDB, address common.Address, data types.StateAccount) *stateObject {
   103  	if data.Balance == nil {
   104  		data.Balance = new(big.Int)
   105  	}
   106  	if data.CodeHash == nil {
   107  		data.CodeHash = emptyCodeHash
   108  	}
   109  	if data.Root == (common.Hash{}) {
   110  		data.Root = emptyRoot
   111  	}
   112  	return &stateObject{
   113  		db:             db,
   114  		address:        address,
   115  		addrHash:       crypto.Keccak256Hash(address[:]),
   116  		data:           data,
   117  		originStorage:  make(Storage),
   118  		pendingStorage: make(Storage),
   119  		dirtyStorage:   make(Storage),
   120  	}
   121  }
   122  
   123  // EncodeRLP implements rlp.Encoder.
   124  func (s *stateObject) EncodeRLP(w io.Writer) error {
   125  	return rlp.Encode(w, &s.data)
   126  }
   127  
   128  // setError remembers the first non-nil error it is called with.
   129  func (s *stateObject) setError(err error) {
   130  	if s.dbErr == nil {
   131  		s.dbErr = err
   132  	}
   133  }
   134  
   135  func (s *stateObject) markSuicided() {
   136  	s.suicided = true
   137  }
   138  
   139  func (s *stateObject) touch() {
   140  	s.db.journal.append(touchChange{
   141  		account: &s.address,
   142  	})
   143  	if s.address == ripemd {
   144  		// Explicitly put it in the dirty-cache, which is otherwise generated from
   145  		// flattened journals.
   146  		s.db.journal.dirty(s.address)
   147  	}
   148  }
   149  
   150  func (s *stateObject) getTrie(db Database) Trie {
   151  	if s.trie == nil {
   152  		// Try fetching from prefetcher first
   153  		// We don't prefetch empty tries
   154  		if s.data.Root != emptyRoot && s.db.prefetcher != nil {
   155  			// When the miner is creating the pending state, there is no
   156  			// prefetcher
   157  			s.trie = s.db.prefetcher.trie(s.data.Root)
   158  		}
   159  		if s.trie == nil {
   160  			var err error
   161  			s.trie, err = db.OpenStorageTrie(s.addrHash, s.data.Root)
   162  			if err != nil {
   163  				s.trie, _ = db.OpenStorageTrie(s.addrHash, common.Hash{})
   164  				s.setError(fmt.Errorf("can't create storage trie: %v", err))
   165  			}
   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  		meter *time.Duration
   204  	)
   205  	readStart := time.Now()
   206  	if metrics.EnabledExpensive {
   207  		// If the snap is 'under construction', the first lookup may fail. If that
   208  		// happens, we don't want to double-count the time elapsed. Thus this
   209  		// dance with the metering.
   210  		defer func() {
   211  			if meter != nil {
   212  				*meter += time.Since(readStart)
   213  			}
   214  		}()
   215  	}
   216  	if s.db.snap != nil {
   217  		if metrics.EnabledExpensive {
   218  			meter = &s.db.SnapshotStorageReads
   219  		}
   220  		// If the object was destructed in *this* block (and potentially resurrected),
   221  		// the storage has been cleared out, and we should *not* consult the previous
   222  		// snapshot about any storage values. The only possible alternatives are:
   223  		//   1) resurrect happened, and new slot values were set -- those should
   224  		//      have been handles via pendingStorage above.
   225  		//   2) we don't have new values, and can deliver empty response back
   226  		if _, destructed := s.db.snapDestructs[s.addrHash]; destructed {
   227  			return common.Hash{}
   228  		}
   229  		enc, err = s.db.snap.Storage(s.addrHash, crypto.Keccak256Hash(key.Bytes()))
   230  	}
   231  	// If the snapshot is unavailable or reading from it fails, load from the database.
   232  	if s.db.snap == nil || err != nil {
   233  		if meter != nil {
   234  			// If we already spent time checking the snapshot, account for it
   235  			// and reset the readStart
   236  			*meter += time.Since(readStart)
   237  			readStart = time.Now()
   238  		}
   239  		if metrics.EnabledExpensive {
   240  			meter = &s.db.StorageReads
   241  		}
   242  		if enc, err = s.getTrie(db).TryGet(key.Bytes()); err != nil {
   243  			s.setError(err)
   244  			return common.Hash{}
   245  		}
   246  	}
   247  	var value common.Hash
   248  	if len(enc) > 0 {
   249  		_, content, _, err := rlp.Split(enc)
   250  		if err != nil {
   251  			s.setError(err)
   252  		}
   253  		value.SetBytes(content)
   254  	}
   255  	s.originStorage[key] = value
   256  	return value
   257  }
   258  
   259  // SetState updates a value in account storage.
   260  func (s *stateObject) SetState(db Database, key, value common.Hash) {
   261  	// If the fake storage is set, put the temporary state update here.
   262  	if s.fakeStorage != nil {
   263  		s.fakeStorage[key] = value
   264  		return
   265  	}
   266  	// If the new value is the same as old, don't set
   267  	prev := s.GetState(db, key)
   268  	if prev == value {
   269  		return
   270  	}
   271  	// New value is different, update and journal the change
   272  	s.db.journal.append(storageChange{
   273  		account:  &s.address,
   274  		key:      key,
   275  		prevalue: prev,
   276  	})
   277  	s.setState(key, value)
   278  }
   279  
   280  // SetStorage replaces the entire state storage with the given one.
   281  //
   282  // After this function is called, all original state will be ignored and state
   283  // lookup only happens in the fake state storage.
   284  //
   285  // Note this function should only be used for debugging purpose.
   286  func (s *stateObject) SetStorage(storage map[common.Hash]common.Hash) {
   287  	// Allocate fake storage if it's nil.
   288  	if s.fakeStorage == nil {
   289  		s.fakeStorage = make(Storage)
   290  	}
   291  	for key, value := range storage {
   292  		s.fakeStorage[key] = value
   293  	}
   294  	// Don't bother journal since this function should only be used for
   295  	// debugging and the `fake` storage won't be committed to database.
   296  }
   297  
   298  func (s *stateObject) setState(key, value common.Hash) {
   299  	s.dirtyStorage[key] = value
   300  }
   301  
   302  // finalise moves all dirty storage slots into the pending area to be hashed or
   303  // committed later. It is invoked at the end of every transaction.
   304  func (s *stateObject) finalise(prefetch bool) {
   305  	slotsToPrefetch := make([][]byte, 0, len(s.dirtyStorage))
   306  	for key, value := range s.dirtyStorage {
   307  		s.pendingStorage[key] = value
   308  		if value != s.originStorage[key] {
   309  			slotsToPrefetch = append(slotsToPrefetch, common.CopyBytes(key[:])) // Copy needed for closure
   310  		}
   311  	}
   312  	if s.db.prefetcher != nil && prefetch && len(slotsToPrefetch) > 0 && s.data.Root != emptyRoot {
   313  		s.db.prefetcher.prefetch(s.data.Root, slotsToPrefetch)
   314  	}
   315  	if len(s.dirtyStorage) > 0 {
   316  		s.dirtyStorage = make(Storage)
   317  	}
   318  }
   319  
   320  // updateTrie writes cached storage modifications into the object's storage trie.
   321  // It will return nil if the trie has not been loaded and no changes have been made
   322  func (s *stateObject) updateTrie(db Database) Trie {
   323  	// Make sure all dirty slots are finalized into the pending storage area
   324  	s.finalise(false) // Don't prefetch anymore, pull directly if need be
   325  	if len(s.pendingStorage) == 0 {
   326  		return s.trie
   327  	}
   328  	// Track the amount of time wasted on updating the storage trie
   329  	if metrics.EnabledExpensive {
   330  		defer func(start time.Time) { s.db.StorageUpdates += time.Since(start) }(time.Now())
   331  	}
   332  	// The snapshot storage map for the object
   333  	var storage map[common.Hash][]byte
   334  	// Insert all the pending updates into the trie
   335  	tr := s.getTrie(db)
   336  	hasher := s.db.hasher
   337  
   338  	usedStorage := make([][]byte, 0, len(s.pendingStorage))
   339  	for key, value := range s.pendingStorage {
   340  		// Skip noop changes, persist actual changes
   341  		if value == s.originStorage[key] {
   342  			continue
   343  		}
   344  		s.originStorage[key] = value
   345  
   346  		var v []byte
   347  		if (value == common.Hash{}) {
   348  			s.setError(tr.TryDelete(key[:]))
   349  			s.db.StorageDeleted += 1
   350  		} else {
   351  			// Encoding []byte cannot fail, ok to ignore the error.
   352  			v, _ = rlp.EncodeToBytes(common.TrimLeftZeroes(value[:]))
   353  			s.setError(tr.TryUpdate(key[:], v))
   354  			s.db.StorageUpdated += 1
   355  		}
   356  		// If state snapshotting is active, cache the data til commit
   357  		if s.db.snap != nil {
   358  			if storage == nil {
   359  				// Retrieve the old storage map, if available, create a new one otherwise
   360  				if storage = s.db.snapStorage[s.addrHash]; storage == nil {
   361  					storage = make(map[common.Hash][]byte)
   362  					s.db.snapStorage[s.addrHash] = storage
   363  				}
   364  			}
   365  			storage[crypto.HashData(hasher, key[:])] = v // v will be nil if it's deleted
   366  		}
   367  		usedStorage = append(usedStorage, common.CopyBytes(key[:])) // Copy needed for closure
   368  	}
   369  	if s.db.prefetcher != nil {
   370  		s.db.prefetcher.used(s.data.Root, usedStorage)
   371  	}
   372  	if len(s.pendingStorage) > 0 {
   373  		s.pendingStorage = make(Storage)
   374  	}
   375  	return tr
   376  }
   377  
   378  // UpdateRoot sets the trie root to the current root hash of
   379  func (s *stateObject) updateRoot(db Database) {
   380  	// If nothing changed, don't bother with hashing anything
   381  	if s.updateTrie(db) == nil {
   382  		return
   383  	}
   384  	// Track the amount of time wasted on hashing the storage trie
   385  	if metrics.EnabledExpensive {
   386  		defer func(start time.Time) { s.db.StorageHashes += time.Since(start) }(time.Now())
   387  	}
   388  	s.data.Root = s.trie.Hash()
   389  }
   390  
   391  // CommitTrie the storage trie of the object to db.
   392  // This updates the trie root.
   393  func (s *stateObject) CommitTrie(db Database) (int, error) {
   394  	// If nothing changed, don't bother with hashing anything
   395  	if s.updateTrie(db) == nil {
   396  		return 0, nil
   397  	}
   398  	if s.dbErr != nil {
   399  		return 0, s.dbErr
   400  	}
   401  	// Track the amount of time wasted on committing the storage trie
   402  	if metrics.EnabledExpensive {
   403  		defer func(start time.Time) { s.db.StorageCommits += time.Since(start) }(time.Now())
   404  	}
   405  	root, committed, err := s.trie.Commit(nil)
   406  	if err == nil {
   407  		s.data.Root = root
   408  	}
   409  	return committed, err
   410  }
   411  
   412  // AddBalance adds amount to s's balance.
   413  // It is used to add funds to the destination account of a transfer.
   414  func (s *stateObject) AddBalance(amount *big.Int) {
   415  	// EIP161: We must check emptiness for the objects such that the account
   416  	// clearing (0,0,0 objects) can take effect.
   417  	if amount.Sign() == 0 {
   418  		if s.empty() {
   419  			s.touch()
   420  		}
   421  		return
   422  	}
   423  	s.SetBalance(new(big.Int).Add(s.Balance(), amount))
   424  }
   425  
   426  // SubBalance removes amount from s's balance.
   427  // It is used to remove funds from the origin account of a transfer.
   428  func (s *stateObject) SubBalance(amount *big.Int) {
   429  	if amount.Sign() == 0 {
   430  		return
   431  	}
   432  	s.SetBalance(new(big.Int).Sub(s.Balance(), amount))
   433  }
   434  
   435  func (s *stateObject) SetBalance(amount *big.Int) {
   436  	s.db.journal.append(balanceChange{
   437  		account: &s.address,
   438  		prev:    new(big.Int).Set(s.data.Balance),
   439  	})
   440  	s.setBalance(amount)
   441  }
   442  
   443  func (s *stateObject) setBalance(amount *big.Int) {
   444  	s.data.Balance = amount
   445  }
   446  
   447  func (s *stateObject) deepCopy(db *StateDB) *stateObject {
   448  	stateObject := newObject(db, s.address, s.data)
   449  	if s.trie != nil {
   450  		stateObject.trie = db.db.CopyTrie(s.trie)
   451  	}
   452  	stateObject.code = s.code
   453  	stateObject.dirtyStorage = s.dirtyStorage.Copy()
   454  	stateObject.originStorage = s.originStorage.Copy()
   455  	stateObject.pendingStorage = s.pendingStorage.Copy()
   456  	stateObject.suicided = s.suicided
   457  	stateObject.dirtyCode = s.dirtyCode
   458  	stateObject.deleted = s.deleted
   459  	return stateObject
   460  }
   461  
   462  //
   463  // Attribute accessors
   464  //
   465  
   466  // Returns the address of the contract/account
   467  func (s *stateObject) Address() common.Address {
   468  	return s.address
   469  }
   470  
   471  // Code returns the contract code associated with this object, if any.
   472  func (s *stateObject) Code(db Database) []byte {
   473  	if s.code != nil {
   474  		return s.code
   475  	}
   476  	if bytes.Equal(s.CodeHash(), emptyCodeHash) {
   477  		return nil
   478  	}
   479  	code, err := db.ContractCode(s.addrHash, common.BytesToHash(s.CodeHash()))
   480  	if err != nil {
   481  		s.setError(fmt.Errorf("can't load code hash %x: %v", s.CodeHash(), err))
   482  	}
   483  	s.code = code
   484  	return code
   485  }
   486  
   487  // CodeSize returns the size of the contract code associated with this object,
   488  // or zero if none. This method is an almost mirror of Code, but uses a cache
   489  // inside the database to avoid loading codes seen recently.
   490  func (s *stateObject) CodeSize(db Database) int {
   491  	if s.code != nil {
   492  		return len(s.code)
   493  	}
   494  	if bytes.Equal(s.CodeHash(), emptyCodeHash) {
   495  		return 0
   496  	}
   497  	size, err := db.ContractCodeSize(s.addrHash, common.BytesToHash(s.CodeHash()))
   498  	if err != nil {
   499  		s.setError(fmt.Errorf("can't load code size %x: %v", s.CodeHash(), err))
   500  	}
   501  	return size
   502  }
   503  
   504  func (s *stateObject) SetCode(codeHash common.Hash, code []byte) {
   505  	prevcode := s.Code(s.db.db)
   506  	s.db.journal.append(codeChange{
   507  		account:  &s.address,
   508  		prevhash: s.CodeHash(),
   509  		prevcode: prevcode,
   510  	})
   511  	s.setCode(codeHash, code)
   512  }
   513  
   514  func (s *stateObject) setCode(codeHash common.Hash, code []byte) {
   515  	s.code = code
   516  	s.data.CodeHash = codeHash[:]
   517  	s.dirtyCode = true
   518  }
   519  
   520  func (s *stateObject) SetNonce(nonce uint64) {
   521  	s.db.journal.append(nonceChange{
   522  		account: &s.address,
   523  		prev:    s.data.Nonce,
   524  	})
   525  	s.setNonce(nonce)
   526  }
   527  
   528  func (s *stateObject) setNonce(nonce uint64) {
   529  	s.data.Nonce = nonce
   530  }
   531  
   532  func (s *stateObject) CodeHash() []byte {
   533  	return s.data.CodeHash
   534  }
   535  
   536  func (s *stateObject) Balance() *big.Int {
   537  	return s.data.Balance
   538  }
   539  
   540  func (s *stateObject) Nonce() uint64 {
   541  	return s.data.Nonce
   542  }
   543  
   544  // Never called, but must be present to allow stateObject to be used
   545  // as a vm.Account interface that also satisfies the vm.ContractRef
   546  // interface. Interfaces are awesome.
   547  func (s *stateObject) Value() *big.Int {
   548  	panic("Value on stateObject should never be called")
   549  }