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