github.com/hyperion-hyn/go-ethereum@v2.4.0+incompatible/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/ethereum/go-ethereum/common"
    26  	"github.com/ethereum/go-ethereum/crypto"
    27  	"github.com/ethereum/go-ethereum/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  	originStorage Storage // Storage cache of original entries to dedup rewrites
    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  	touched   bool
    89  	deleted   bool
    90  }
    91  
    92  // empty returns whether the account is considered empty.
    93  func (s *stateObject) empty() bool {
    94  	return s.data.Nonce == 0 && s.data.Balance.Sign() == 0 && bytes.Equal(s.data.CodeHash, emptyCodeHash)
    95  }
    96  
    97  // Account is the Ethereum consensus representation of accounts.
    98  // These objects are stored in the main account trie.
    99  type Account struct {
   100  	Nonce    uint64
   101  	Balance  *big.Int
   102  	Root     common.Hash // merkle root of the storage trie
   103  	CodeHash []byte
   104  }
   105  
   106  // newObject creates a state object.
   107  func newObject(db *StateDB, address common.Address, data Account) *stateObject {
   108  	if data.Balance == nil {
   109  		data.Balance = new(big.Int)
   110  	}
   111  	if data.CodeHash == nil {
   112  		data.CodeHash = emptyCodeHash
   113  	}
   114  	return &stateObject{
   115  		db:            db,
   116  		address:       address,
   117  		addrHash:      crypto.Keccak256Hash(address[:]),
   118  		data:          data,
   119  		originStorage: make(Storage),
   120  		dirtyStorage:  make(Storage),
   121  	}
   122  }
   123  
   124  // EncodeRLP implements rlp.Encoder.
   125  func (c *stateObject) EncodeRLP(w io.Writer) error {
   126  	return rlp.Encode(w, c.data)
   127  }
   128  
   129  // setError remembers the first non-nil error it is called with.
   130  func (self *stateObject) setError(err error) {
   131  	if self.dbErr == nil {
   132  		self.dbErr = err
   133  	}
   134  }
   135  
   136  func (self *stateObject) markSuicided() {
   137  	self.suicided = true
   138  }
   139  
   140  func (c *stateObject) touch() {
   141  	c.db.journal.append(touchChange{
   142  		account: &c.address,
   143  	})
   144  	if c.address == ripemd {
   145  		// Explicitly put it in the dirty-cache, which is otherwise generated from
   146  		// flattened journals.
   147  		c.db.journal.dirty(c.address)
   148  	}
   149  	c.touched = true
   150  }
   151  
   152  func (c *stateObject) getTrie(db Database) Trie {
   153  	if c.trie == nil {
   154  		var err error
   155  		c.trie, err = db.OpenStorageTrie(c.addrHash, c.data.Root)
   156  		if err != nil {
   157  			c.trie, _ = db.OpenStorageTrie(c.addrHash, common.Hash{})
   158  			c.setError(fmt.Errorf("can't create storage trie: %v", err))
   159  		}
   160  	}
   161  	return c.trie
   162  }
   163  
   164  func (so *stateObject) storageRoot(db Database) common.Hash {
   165  	return so.getTrie(db).Hash()
   166  }
   167  
   168  // GetState retrieves a value from the account storage trie.
   169  func (self *stateObject) GetState(db Database, key common.Hash) common.Hash {
   170  	// If we have a dirty value for this state entry, return it
   171  	value, dirty := self.dirtyStorage[key]
   172  	if dirty {
   173  		return value
   174  	}
   175  	// Otherwise return the entry's original value
   176  	return self.GetCommittedState(db, key)
   177  }
   178  
   179  // GetCommittedState retrieves a value from the committed account storage trie.
   180  func (self *stateObject) GetCommittedState(db Database, key common.Hash) common.Hash {
   181  	// If we have the original value cached, return that
   182  	value, cached := self.originStorage[key]
   183  	if cached {
   184  		return value
   185  	}
   186  	// Otherwise load the value from the database
   187  	enc, err := self.getTrie(db).TryGet(key[:])
   188  	if err != nil {
   189  		self.setError(err)
   190  		return common.Hash{}
   191  	}
   192  	if len(enc) > 0 {
   193  		_, content, _, err := rlp.Split(enc)
   194  		if err != nil {
   195  			self.setError(err)
   196  		}
   197  		value.SetBytes(content)
   198  	}
   199  	self.originStorage[key] = value
   200  	return value
   201  }
   202  
   203  // SetState updates a value in account storage.
   204  func (self *stateObject) SetState(db Database, key, value common.Hash) {
   205  	// If the new value is the same as old, don't set
   206  	prev := self.GetState(db, key)
   207  	if prev == value {
   208  		return
   209  	}
   210  	// New value is different, update and journal the change
   211  	self.db.journal.append(storageChange{
   212  		account:  &self.address,
   213  		key:      key,
   214  		prevalue: prev,
   215  	})
   216  	self.setState(key, value)
   217  }
   218  
   219  func (self *stateObject) setState(key, value common.Hash) {
   220  	self.dirtyStorage[key] = value
   221  }
   222  
   223  // updateTrie writes cached storage modifications into the object's storage trie.
   224  func (self *stateObject) updateTrie(db Database) Trie {
   225  	tr := self.getTrie(db)
   226  	for key, value := range self.dirtyStorage {
   227  		delete(self.dirtyStorage, key)
   228  
   229  		// Skip noop changes, persist actual changes
   230  		if value == self.originStorage[key] {
   231  			continue
   232  		}
   233  		self.originStorage[key] = value
   234  
   235  		if (value == common.Hash{}) {
   236  			self.setError(tr.TryDelete(key[:]))
   237  			continue
   238  		}
   239  		// Encoding []byte cannot fail, ok to ignore the error.
   240  		v, _ := rlp.EncodeToBytes(bytes.TrimLeft(value[:], "\x00"))
   241  		self.setError(tr.TryUpdate(key[:], v))
   242  	}
   243  	return tr
   244  }
   245  
   246  // UpdateRoot sets the trie root to the current root hash of
   247  func (self *stateObject) updateRoot(db Database) {
   248  	self.updateTrie(db)
   249  	self.data.Root = self.trie.Hash()
   250  }
   251  
   252  // CommitTrie the storage trie of the object to db.
   253  // This updates the trie root.
   254  func (self *stateObject) CommitTrie(db Database) error {
   255  	self.updateTrie(db)
   256  	if self.dbErr != nil {
   257  		return self.dbErr
   258  	}
   259  	root, err := self.trie.Commit(nil)
   260  	if err == nil {
   261  		self.data.Root = root
   262  	}
   263  	return err
   264  }
   265  
   266  // AddBalance removes amount from c's balance.
   267  // It is used to add funds to the destination account of a transfer.
   268  func (c *stateObject) AddBalance(amount *big.Int) {
   269  	// EIP158: We must check emptiness for the objects such that the account
   270  	// clearing (0,0,0 objects) can take effect.
   271  	if amount.Sign() == 0 {
   272  		if c.empty() {
   273  			c.touch()
   274  		}
   275  
   276  		return
   277  	}
   278  	c.SetBalance(new(big.Int).Add(c.Balance(), amount))
   279  }
   280  
   281  // SubBalance removes amount from c's balance.
   282  // It is used to remove funds from the origin account of a transfer.
   283  func (c *stateObject) SubBalance(amount *big.Int) {
   284  	if amount.Sign() == 0 {
   285  		return
   286  	}
   287  	c.SetBalance(new(big.Int).Sub(c.Balance(), amount))
   288  }
   289  
   290  func (self *stateObject) SetBalance(amount *big.Int) {
   291  	self.db.journal.append(balanceChange{
   292  		account: &self.address,
   293  		prev:    new(big.Int).Set(self.data.Balance),
   294  	})
   295  	self.setBalance(amount)
   296  }
   297  
   298  func (self *stateObject) setBalance(amount *big.Int) {
   299  	self.data.Balance = amount
   300  }
   301  
   302  // Return the gas back to the origin. Used by the Virtual machine or Closures
   303  func (c *stateObject) ReturnGas(gas *big.Int) {}
   304  
   305  func (self *stateObject) deepCopy(db *StateDB) *stateObject {
   306  	stateObject := newObject(db, self.address, self.data)
   307  	if self.trie != nil {
   308  		stateObject.trie = db.db.CopyTrie(self.trie)
   309  	}
   310  	stateObject.code = self.code
   311  	stateObject.dirtyStorage = self.dirtyStorage.Copy()
   312  	stateObject.originStorage = self.originStorage.Copy()
   313  	stateObject.suicided = self.suicided
   314  	stateObject.dirtyCode = self.dirtyCode
   315  	stateObject.deleted = self.deleted
   316  	return stateObject
   317  }
   318  
   319  //
   320  // Attribute accessors
   321  //
   322  
   323  // Returns the address of the contract/account
   324  func (c *stateObject) Address() common.Address {
   325  	return c.address
   326  }
   327  
   328  // Code returns the contract code associated with this object, if any.
   329  func (self *stateObject) Code(db Database) []byte {
   330  	if self.code != nil {
   331  		return self.code
   332  	}
   333  	if bytes.Equal(self.CodeHash(), emptyCodeHash) {
   334  		return nil
   335  	}
   336  	code, err := db.ContractCode(self.addrHash, common.BytesToHash(self.CodeHash()))
   337  	if err != nil {
   338  		self.setError(fmt.Errorf("can't load code hash %x: %v", self.CodeHash(), err))
   339  	}
   340  	self.code = code
   341  	return code
   342  }
   343  
   344  func (self *stateObject) SetCode(codeHash common.Hash, code []byte) {
   345  	prevcode := self.Code(self.db.db)
   346  	self.db.journal.append(codeChange{
   347  		account:  &self.address,
   348  		prevhash: self.CodeHash(),
   349  		prevcode: prevcode,
   350  	})
   351  	self.setCode(codeHash, code)
   352  }
   353  
   354  func (self *stateObject) setCode(codeHash common.Hash, code []byte) {
   355  	self.code = code
   356  	self.data.CodeHash = codeHash[:]
   357  	self.dirtyCode = true
   358  }
   359  
   360  func (self *stateObject) SetNonce(nonce uint64) {
   361  	self.db.journal.append(nonceChange{
   362  		account: &self.address,
   363  		prev:    self.data.Nonce,
   364  	})
   365  	self.setNonce(nonce)
   366  }
   367  
   368  func (self *stateObject) setNonce(nonce uint64) {
   369  	self.data.Nonce = nonce
   370  }
   371  
   372  func (self *stateObject) CodeHash() []byte {
   373  	return self.data.CodeHash
   374  }
   375  
   376  func (self *stateObject) Balance() *big.Int {
   377  	return self.data.Balance
   378  }
   379  
   380  func (self *stateObject) Nonce() uint64 {
   381  	return self.data.Nonce
   382  }
   383  
   384  // Never called, but must be present to allow stateObject to be used
   385  // as a vm.Account interface that also satisfies the vm.ContractRef
   386  // interface. Interfaces are awesome.
   387  func (self *stateObject) Value() *big.Int {
   388  	panic("Value on stateObject should never be called")
   389  }