state_object.go 8.1 KB

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