state_object.go 8.1 KB

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