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