github.com/luckypickle/go-ethereum-vet@v1.14.2/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  
    25  	"github.com/luckypickle/go-ethereum-vet/common"
    26  	"github.com/luckypickle/go-ethereum-vet/crypto"
    27  	"github.com/luckypickle/go-ethereum-vet/rlp"
    28  )
    29  
    30  var emptyCodeHash = crypto.Keccak256(nil)
    31  
    32  type Code []byte
    33  
    34  func (self Code) String() string {
    35  	return string(self) //strings.Join(Disassemble(self), " ")
    36  }
    37  
    38  type Storage map[common.Hash]common.Hash
    39  
    40  func (self Storage) String() (str string) {
    41  	for key, value := range self {
    42  		str += fmt.Sprintf("%X : %X\n", key, value)
    43  	}
    44  
    45  	return
    46  }
    47  
    48  func (self Storage) Copy() Storage {
    49  	cpy := make(Storage)
    50  	for key, value := range self {
    51  		cpy[key] = value
    52  	}
    53  
    54  	return cpy
    55  }
    56  
    57  // stateObject represents an Ethereum account which is being modified.
    58  //
    59  // The usage pattern is as follows:
    60  // First you need to obtain a state object.
    61  // Account values can be accessed and modified through the object.
    62  // Finally, call CommitTrie to write the modified storage trie into a database.
    63  type stateObject struct {
    64  	address  common.Address
    65  	addrHash common.Hash // hash of ethereum address of the account
    66  	data     Account
    67  	db       *StateDB
    68  
    69  	// DB error.
    70  	// State objects are used by the consensus core and VM which are
    71  	// unable to deal with database-level errors. Any error that occurs
    72  	// during a database read is memoized here and will eventually be returned
    73  	// by StateDB.Commit.
    74  	dbErr error
    75  
    76  	// Write caches.
    77  	trie Trie // storage trie, which becomes non-nil on first access
    78  	code Code // contract bytecode, which gets set when code is loaded
    79  
    80  	cachedStorage Storage // Storage entry cache to avoid duplicate reads
    81  	dirtyStorage  Storage // Storage entries that need to be flushed to disk
    82  
    83  	// Cache flags.
    84  	// When an object is marked suicided it will be delete from the trie
    85  	// during the "update" phase of the state transition.
    86  	dirtyCode bool // true if the code was updated
    87  	suicided  bool
    88  	deleted   bool
    89  }
    90  
    91  // empty returns whether the account is considered empty.
    92  func (s *stateObject) empty() bool {
    93  	return s.data.Nonce == 0 && s.data.Balance.Sign() == 0 && bytes.Equal(s.data.CodeHash, emptyCodeHash)
    94  }
    95  
    96  // Account is the Ethereum consensus representation of accounts.
    97  // These objects are stored in the main account trie.
    98  type Account struct {
    99  	Nonce    uint64
   100  	Balance  *big.Int
   101  	Root     common.Hash // merkle root of the storage trie
   102  	CodeHash []byte
   103  }
   104  
   105  // newObject creates a state object.
   106  func newObject(db *StateDB, address common.Address, data Account) *stateObject {
   107  	if data.Balance == nil {
   108  		data.Balance = new(big.Int)
   109  	}
   110  	if data.CodeHash == nil {
   111  		data.CodeHash = emptyCodeHash
   112  	}
   113  	return &stateObject{
   114  		db:            db,
   115  		address:       address,
   116  		addrHash:      crypto.Keccak256Hash(address[:]),
   117  		data:          data,
   118  		cachedStorage: make(Storage),
   119  		dirtyStorage:  make(Storage),
   120  	}
   121  }
   122  
   123  // EncodeRLP implements rlp.Encoder.
   124  func (c *stateObject) EncodeRLP(w io.Writer) error {
   125  	return rlp.Encode(w, c.data)
   126  }
   127  
   128  // setError remembers the first non-nil error it is called with.
   129  func (self *stateObject) setError(err error) {
   130  	if self.dbErr == nil {
   131  		self.dbErr = err
   132  	}
   133  }
   134  
   135  func (self *stateObject) markSuicided() {
   136  	self.suicided = true
   137  }
   138  
   139  func (c *stateObject) touch() {
   140  	c.db.journal.append(touchChange{
   141  		account: &c.address,
   142  	})
   143  	if c.address == ripemd {
   144  		// Explicitly put it in the dirty-cache, which is otherwise generated from
   145  		// flattened journals.
   146  		c.db.journal.dirty(c.address)
   147  	}
   148  }
   149  
   150  func (c *stateObject) getTrie(db Database) Trie {
   151  	if c.trie == nil {
   152  		var err error
   153  		c.trie, err = db.OpenStorageTrie(c.addrHash, c.data.Root)
   154  		if err != nil {
   155  			c.trie, _ = db.OpenStorageTrie(c.addrHash, common.Hash{})
   156  			c.setError(fmt.Errorf("can't create storage trie: %v", err))
   157  		}
   158  	}
   159  	return c.trie
   160  }
   161  
   162  // GetState returns a value in account storage.
   163  func (self *stateObject) GetState(db Database, key common.Hash) common.Hash {
   164  	value, exists := self.cachedStorage[key]
   165  	if exists {
   166  		return value
   167  	}
   168  	// Load from DB in case it is missing.
   169  	enc, err := self.getTrie(db).TryGet(key[:])
   170  	if err != nil {
   171  		self.setError(err)
   172  		return common.Hash{}
   173  	}
   174  	if len(enc) > 0 {
   175  		_, content, _, err := rlp.Split(enc)
   176  		if err != nil {
   177  			self.setError(err)
   178  		}
   179  		value.SetBytes(content)
   180  	}
   181  	self.cachedStorage[key] = value
   182  	return value
   183  }
   184  
   185  // SetState updates a value in account storage.
   186  func (self *stateObject) SetState(db Database, key, value common.Hash) {
   187  	self.db.journal.append(storageChange{
   188  		account:  &self.address,
   189  		key:      key,
   190  		prevalue: self.GetState(db, key),
   191  	})
   192  	self.setState(key, value)
   193  }
   194  
   195  func (self *stateObject) setState(key, value common.Hash) {
   196  	self.cachedStorage[key] = value
   197  	self.dirtyStorage[key] = value
   198  }
   199  
   200  // updateTrie writes cached storage modifications into the object's storage trie.
   201  func (self *stateObject) updateTrie(db Database) Trie {
   202  	tr := self.getTrie(db)
   203  	for key, value := range self.dirtyStorage {
   204  		delete(self.dirtyStorage, key)
   205  		if (value == common.Hash{}) {
   206  			self.setError(tr.TryDelete(key[:]))
   207  			continue
   208  		}
   209  		// Encoding []byte cannot fail, ok to ignore the error.
   210  		v, _ := rlp.EncodeToBytes(bytes.TrimLeft(value[:], "\x00"))
   211  		self.setError(tr.TryUpdate(key[:], v))
   212  	}
   213  	return tr
   214  }
   215  
   216  // UpdateRoot sets the trie root to the current root hash of
   217  func (self *stateObject) updateRoot(db Database) {
   218  	self.updateTrie(db)
   219  	self.data.Root = self.trie.Hash()
   220  }
   221  
   222  // CommitTrie the storage trie of the object to db.
   223  // This updates the trie root.
   224  func (self *stateObject) CommitTrie(db Database) error {
   225  	self.updateTrie(db)
   226  	if self.dbErr != nil {
   227  		return self.dbErr
   228  	}
   229  	root, err := self.trie.Commit(nil)
   230  	if err == nil {
   231  		self.data.Root = root
   232  	}
   233  	return err
   234  }
   235  
   236  // AddBalance removes amount from c's balance.
   237  // It is used to add funds to the destination account of a transfer.
   238  func (c *stateObject) AddBalance(amount *big.Int) {
   239  	// EIP158: We must check emptiness for the objects such that the account
   240  	// clearing (0,0,0 objects) can take effect.
   241  	if amount.Sign() == 0 {
   242  		if c.empty() {
   243  			c.touch()
   244  		}
   245  
   246  		return
   247  	}
   248  	c.SetBalance(new(big.Int).Add(c.Balance(), amount))
   249  }
   250  
   251  // SubBalance removes amount from c's balance.
   252  // It is used to remove funds from the origin account of a transfer.
   253  func (c *stateObject) SubBalance(amount *big.Int) {
   254  	if amount.Sign() == 0 {
   255  		return
   256  	}
   257  	c.SetBalance(new(big.Int).Sub(c.Balance(), amount))
   258  }
   259  
   260  func (self *stateObject) SetBalance(amount *big.Int) {
   261  	self.db.journal.append(balanceChange{
   262  		account: &self.address,
   263  		prev:    new(big.Int).Set(self.data.Balance),
   264  	})
   265  	self.setBalance(amount)
   266  }
   267  
   268  func (self *stateObject) setBalance(amount *big.Int) {
   269  	self.data.Balance = amount
   270  }
   271  
   272  // Return the gas back to the origin. Used by the Virtual machine or Closures
   273  func (c *stateObject) ReturnGas(gas *big.Int) {}
   274  
   275  func (self *stateObject) deepCopy(db *StateDB) *stateObject {
   276  	stateObject := newObject(db, self.address, self.data)
   277  	if self.trie != nil {
   278  		stateObject.trie = db.db.CopyTrie(self.trie)
   279  	}
   280  	stateObject.code = self.code
   281  	stateObject.dirtyStorage = self.dirtyStorage.Copy()
   282  	stateObject.cachedStorage = self.dirtyStorage.Copy()
   283  	stateObject.suicided = self.suicided
   284  	stateObject.dirtyCode = self.dirtyCode
   285  	stateObject.deleted = self.deleted
   286  	return stateObject
   287  }
   288  
   289  //
   290  // Attribute accessors
   291  //
   292  
   293  // Returns the address of the contract/account
   294  func (c *stateObject) Address() common.Address {
   295  	return c.address
   296  }
   297  
   298  // Code returns the contract code associated with this object, if any.
   299  func (self *stateObject) Code(db Database) []byte {
   300  	if self.code != nil {
   301  		return self.code
   302  	}
   303  	if bytes.Equal(self.CodeHash(), emptyCodeHash) {
   304  		return nil
   305  	}
   306  	code, err := db.ContractCode(self.addrHash, common.BytesToHash(self.CodeHash()))
   307  	if err != nil {
   308  		self.setError(fmt.Errorf("can't load code hash %x: %v", self.CodeHash(), err))
   309  	}
   310  	self.code = code
   311  	return code
   312  }
   313  
   314  func (self *stateObject) SetCode(codeHash common.Hash, code []byte) {
   315  	prevcode := self.Code(self.db.db)
   316  	self.db.journal.append(codeChange{
   317  		account:  &self.address,
   318  		prevhash: self.CodeHash(),
   319  		prevcode: prevcode,
   320  	})
   321  	self.setCode(codeHash, code)
   322  }
   323  
   324  func (self *stateObject) setCode(codeHash common.Hash, code []byte) {
   325  	self.code = code
   326  	self.data.CodeHash = codeHash[:]
   327  	self.dirtyCode = true
   328  }
   329  
   330  func (self *stateObject) SetNonce(nonce uint64) {
   331  	self.db.journal.append(nonceChange{
   332  		account: &self.address,
   333  		prev:    self.data.Nonce,
   334  	})
   335  	self.setNonce(nonce)
   336  }
   337  
   338  func (self *stateObject) setNonce(nonce uint64) {
   339  	self.data.Nonce = nonce
   340  }
   341  
   342  func (self *stateObject) CodeHash() []byte {
   343  	return self.data.CodeHash
   344  }
   345  
   346  func (self *stateObject) Balance() *big.Int {
   347  	return self.data.Balance
   348  }
   349  
   350  func (self *stateObject) Nonce() uint64 {
   351  	return self.data.Nonce
   352  }
   353  
   354  // Never called, but must be present to allow stateObject to be used
   355  // as a vm.Account interface that also satisfies the vm.ContractRef
   356  // interface. Interfaces are awesome.
   357  func (self *stateObject) Value() *big.Int {
   358  	panic("Value on stateObject should never be called")
   359  }