github.com/arieschain/arieschain@v0.0.0-20191023063405-37c074544356/core/state/state_object.go (about)

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