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