state_object.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. // Copyright 2015 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. package light
  17. import (
  18. "bytes"
  19. "fmt"
  20. "math/big"
  21. "github.com/ethereum/go-ethereum/common"
  22. "github.com/ethereum/go-ethereum/crypto"
  23. "github.com/ethereum/go-ethereum/rlp"
  24. "golang.org/x/net/context"
  25. )
  26. var emptyCodeHash = crypto.Keccak256(nil)
  27. // Code represents a contract code in binary form
  28. type Code []byte
  29. // String returns a string representation of the code
  30. func (self Code) String() string {
  31. return string(self) //strings.Join(Disassemble(self), " ")
  32. }
  33. // Storage is a memory map cache of a contract storage
  34. type Storage map[common.Hash]common.Hash
  35. // String returns a string representation of the storage cache
  36. func (self Storage) String() (str string) {
  37. for key, value := range self {
  38. str += fmt.Sprintf("%X : %X\n", key, value)
  39. }
  40. return
  41. }
  42. // Copy copies the contents of a storage cache
  43. func (self Storage) Copy() Storage {
  44. cpy := make(Storage)
  45. for key, value := range self {
  46. cpy[key] = value
  47. }
  48. return cpy
  49. }
  50. // StateObject is a memory representation of an account or contract and its storage.
  51. // This version is ODR capable, caching only the already accessed part of the
  52. // storage, retrieving unknown parts on-demand from the ODR backend. Changes are
  53. // never stored in the local database, only in the memory objects.
  54. type StateObject struct {
  55. odr OdrBackend
  56. trie *LightTrie
  57. // Address belonging to this account
  58. address common.Address
  59. // The balance of the account
  60. balance *big.Int
  61. // The nonce of the account
  62. nonce uint64
  63. // The code hash if code is present (i.e. a contract)
  64. codeHash []byte
  65. // The code for this account
  66. code Code
  67. // Cached storage (flushed when updated)
  68. storage Storage
  69. // Mark for deletion
  70. // When an object is marked for deletion it will be delete from the trie
  71. // during the "update" phase of the state transition
  72. remove bool
  73. deleted bool
  74. dirty bool
  75. }
  76. // NewStateObject creates a new StateObject of the specified account address
  77. func NewStateObject(address common.Address, odr OdrBackend) *StateObject {
  78. object := &StateObject{
  79. odr: odr,
  80. address: address,
  81. balance: new(big.Int),
  82. dirty: true,
  83. codeHash: emptyCodeHash,
  84. storage: make(Storage),
  85. }
  86. object.trie = NewLightTrie(&TrieID{}, odr, true)
  87. return object
  88. }
  89. // MarkForDeletion marks an account to be removed
  90. func (self *StateObject) MarkForDeletion() {
  91. self.remove = true
  92. self.dirty = true
  93. }
  94. // getAddr gets the storage value at the given address from the trie
  95. func (c *StateObject) getAddr(ctx context.Context, addr common.Hash) (common.Hash, error) {
  96. var ret []byte
  97. val, err := c.trie.Get(ctx, addr[:])
  98. if err != nil {
  99. return common.Hash{}, err
  100. }
  101. rlp.DecodeBytes(val, &ret)
  102. return common.BytesToHash(ret), nil
  103. }
  104. // Storage returns the storage cache object of the account
  105. func (self *StateObject) Storage() Storage {
  106. return self.storage
  107. }
  108. // GetState returns the storage value at the given address from either the cache
  109. // or the trie
  110. func (self *StateObject) GetState(ctx context.Context, key common.Hash) (common.Hash, error) {
  111. value, exists := self.storage[key]
  112. if !exists {
  113. var err error
  114. value, err = self.getAddr(ctx, key)
  115. if err != nil {
  116. return common.Hash{}, err
  117. }
  118. if (value != common.Hash{}) {
  119. self.storage[key] = value
  120. }
  121. }
  122. return value, nil
  123. }
  124. // SetState sets the storage value at the given address
  125. func (self *StateObject) SetState(k, value common.Hash) {
  126. self.storage[k] = value
  127. self.dirty = true
  128. }
  129. // AddBalance adds the given amount to the account balance
  130. func (c *StateObject) AddBalance(amount *big.Int) {
  131. c.SetBalance(new(big.Int).Add(c.balance, amount))
  132. }
  133. // SubBalance subtracts the given amount from the account balance
  134. func (c *StateObject) SubBalance(amount *big.Int) {
  135. c.SetBalance(new(big.Int).Sub(c.balance, amount))
  136. }
  137. // SetBalance sets the account balance to the given amount
  138. func (c *StateObject) SetBalance(amount *big.Int) {
  139. c.balance = amount
  140. c.dirty = true
  141. }
  142. // ReturnGas returns the gas back to the origin. Used by the Virtual machine or Closures
  143. func (c *StateObject) ReturnGas(gas *big.Int) {}
  144. // Copy creates a copy of the state object
  145. func (self *StateObject) Copy() *StateObject {
  146. stateObject := NewStateObject(self.Address(), self.odr)
  147. stateObject.balance.Set(self.balance)
  148. stateObject.codeHash = common.CopyBytes(self.codeHash)
  149. stateObject.nonce = self.nonce
  150. stateObject.trie = self.trie
  151. stateObject.code = self.code
  152. stateObject.storage = self.storage.Copy()
  153. stateObject.remove = self.remove
  154. stateObject.dirty = self.dirty
  155. stateObject.deleted = self.deleted
  156. return stateObject
  157. }
  158. //
  159. // Attribute accessors
  160. //
  161. // empty returns whether the account is considered empty.
  162. func (self *StateObject) empty() bool {
  163. return self.nonce == 0 && self.balance.Sign() == 0 && bytes.Equal(self.codeHash, emptyCodeHash)
  164. }
  165. // Balance returns the account balance
  166. func (self *StateObject) Balance() *big.Int {
  167. return self.balance
  168. }
  169. // Address returns the address of the contract/account
  170. func (self *StateObject) Address() common.Address {
  171. return self.address
  172. }
  173. // Code returns the contract code
  174. func (self *StateObject) Code() []byte {
  175. return self.code
  176. }
  177. // SetCode sets the contract code
  178. func (self *StateObject) SetCode(hash common.Hash, code []byte) {
  179. self.code = code
  180. self.codeHash = hash[:]
  181. self.dirty = true
  182. }
  183. // SetNonce sets the account nonce
  184. func (self *StateObject) SetNonce(nonce uint64) {
  185. self.nonce = nonce
  186. self.dirty = true
  187. }
  188. // Nonce returns the account nonce
  189. func (self *StateObject) Nonce() uint64 {
  190. return self.nonce
  191. }
  192. // ForEachStorage calls a callback function for every key/value pair found
  193. // in the local storage cache. Note that unlike core/state.StateObject,
  194. // light.StateObject only returns cached values and doesn't download the
  195. // entire storage tree.
  196. func (self *StateObject) ForEachStorage(cb func(key, value common.Hash) bool) {
  197. for h, v := range self.storage {
  198. cb(h, v)
  199. }
  200. }
  201. // Never called, but must be present to allow StateObject to be used
  202. // as a vm.Account interface that also satisfies the vm.ContractRef
  203. // interface. Interfaces are awesome.
  204. func (self *StateObject) Value() *big.Int {
  205. panic("Value on StateObject should never be called")
  206. }
  207. // Encoding
  208. type extStateObject struct {
  209. Nonce uint64
  210. Balance *big.Int
  211. Root common.Hash
  212. CodeHash []byte
  213. }
  214. // DecodeObject decodes an RLP-encoded state object.
  215. func DecodeObject(ctx context.Context, stateID *TrieID, address common.Address, odr OdrBackend, data []byte) (*StateObject, error) {
  216. var (
  217. obj = &StateObject{address: address, odr: odr, storage: make(Storage)}
  218. ext extStateObject
  219. err error
  220. )
  221. if err = rlp.DecodeBytes(data, &ext); err != nil {
  222. return nil, err
  223. }
  224. trieID := StorageTrieID(stateID, address, ext.Root)
  225. obj.trie = NewLightTrie(trieID, odr, true)
  226. if !bytes.Equal(ext.CodeHash, emptyCodeHash) {
  227. if obj.code, err = retrieveContractCode(ctx, obj.odr, trieID, common.BytesToHash(ext.CodeHash)); err != nil {
  228. return nil, fmt.Errorf("can't find code for hash %x: %v", ext.CodeHash, err)
  229. }
  230. }
  231. obj.nonce = ext.Nonce
  232. obj.balance = ext.Balance
  233. obj.codeHash = ext.CodeHash
  234. return obj, nil
  235. }