github.com/aquanetwork/aquachain@v1.7.8/core/state/state_object.go (about)

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