state_object.go 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. // Copyright 2014 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 state
  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/ethdb"
  24. "github.com/ethereum/go-ethereum/logger"
  25. "github.com/ethereum/go-ethereum/logger/glog"
  26. "github.com/ethereum/go-ethereum/rlp"
  27. "github.com/ethereum/go-ethereum/trie"
  28. )
  29. type Code []byte
  30. func (self Code) String() string {
  31. return string(self) //strings.Join(Disassemble(self), " ")
  32. }
  33. type Storage map[string]common.Hash
  34. func (self Storage) String() (str string) {
  35. for key, value := range self {
  36. str += fmt.Sprintf("%X : %X\n", key, value)
  37. }
  38. return
  39. }
  40. func (self Storage) Copy() Storage {
  41. cpy := make(Storage)
  42. for key, value := range self {
  43. cpy[key] = value
  44. }
  45. return cpy
  46. }
  47. type StateObject struct {
  48. // State database for storing state changes
  49. db ethdb.Database
  50. trie *trie.SecureTrie
  51. // Address belonging to this account
  52. address common.Address
  53. // The balance of the account
  54. balance *big.Int
  55. // The nonce of the account
  56. nonce uint64
  57. // The code hash if code is present (i.e. a contract)
  58. codeHash []byte
  59. // The code for this account
  60. code Code
  61. // Temporarily initialisation code
  62. initCode Code
  63. // Cached storage (flushed when updated)
  64. storage Storage
  65. // Mark for deletion
  66. // When an object is marked for deletion it will be delete from the trie
  67. // during the "update" phase of the state transition
  68. remove bool
  69. deleted bool
  70. dirty bool
  71. }
  72. func NewStateObject(address common.Address, db ethdb.Database) *StateObject {
  73. object := &StateObject{db: db, address: address, balance: new(big.Int), dirty: true}
  74. object.trie, _ = trie.NewSecure(common.Hash{}, db)
  75. object.storage = make(Storage)
  76. return object
  77. }
  78. func NewStateObjectFromBytes(address common.Address, data []byte, db ethdb.Database) *StateObject {
  79. var extobject struct {
  80. Nonce uint64
  81. Balance *big.Int
  82. Root common.Hash
  83. CodeHash []byte
  84. }
  85. err := rlp.Decode(bytes.NewReader(data), &extobject)
  86. if err != nil {
  87. glog.Errorf("can't decode state object %x: %v", address, err)
  88. return nil
  89. }
  90. trie, err := trie.NewSecure(extobject.Root, db)
  91. if err != nil {
  92. // TODO: bubble this up or panic
  93. glog.Errorf("can't create account trie with root %x: %v", extobject.Root[:], err)
  94. return nil
  95. }
  96. object := &StateObject{address: address, db: db}
  97. object.nonce = extobject.Nonce
  98. object.balance = extobject.Balance
  99. object.codeHash = extobject.CodeHash
  100. object.trie = trie
  101. object.storage = make(map[string]common.Hash)
  102. object.code, _ = db.Get(extobject.CodeHash)
  103. return object
  104. }
  105. func (self *StateObject) MarkForDeletion() {
  106. self.remove = true
  107. self.dirty = true
  108. if glog.V(logger.Core) {
  109. glog.Infof("%x: #%d %v X\n", self.Address(), self.nonce, self.balance)
  110. }
  111. }
  112. func (c *StateObject) getAddr(addr common.Hash) common.Hash {
  113. var ret []byte
  114. rlp.DecodeBytes(c.trie.Get(addr[:]), &ret)
  115. return common.BytesToHash(ret)
  116. }
  117. func (c *StateObject) setAddr(addr []byte, value common.Hash) {
  118. v, err := rlp.EncodeToBytes(bytes.TrimLeft(value[:], "\x00"))
  119. if err != nil {
  120. // if RLPing failed we better panic and not fail silently. This would be considered a consensus issue
  121. panic(err)
  122. }
  123. c.trie.Update(addr, v)
  124. }
  125. func (self *StateObject) Storage() Storage {
  126. return self.storage
  127. }
  128. func (self *StateObject) GetState(key common.Hash) common.Hash {
  129. strkey := key.Str()
  130. value, exists := self.storage[strkey]
  131. if !exists {
  132. value = self.getAddr(key)
  133. if (value != common.Hash{}) {
  134. self.storage[strkey] = value
  135. }
  136. }
  137. return value
  138. }
  139. func (self *StateObject) SetState(k, value common.Hash) {
  140. self.storage[k.Str()] = value
  141. self.dirty = true
  142. }
  143. // Update updates the current cached storage to the trie
  144. func (self *StateObject) Update() {
  145. for key, value := range self.storage {
  146. if (value == common.Hash{}) {
  147. self.trie.Delete([]byte(key))
  148. continue
  149. }
  150. self.setAddr([]byte(key), value)
  151. }
  152. }
  153. func (c *StateObject) AddBalance(amount *big.Int) {
  154. c.SetBalance(new(big.Int).Add(c.balance, amount))
  155. if glog.V(logger.Core) {
  156. glog.Infof("%x: #%d %v (+ %v)\n", c.Address(), c.nonce, c.balance, amount)
  157. }
  158. }
  159. func (c *StateObject) SubBalance(amount *big.Int) {
  160. c.SetBalance(new(big.Int).Sub(c.balance, amount))
  161. if glog.V(logger.Core) {
  162. glog.Infof("%x: #%d %v (- %v)\n", c.Address(), c.nonce, c.balance, amount)
  163. }
  164. }
  165. func (c *StateObject) SetBalance(amount *big.Int) {
  166. c.balance = amount
  167. c.dirty = true
  168. }
  169. func (c *StateObject) St() Storage {
  170. return c.storage
  171. }
  172. // Return the gas back to the origin. Used by the Virtual machine or Closures
  173. func (c *StateObject) ReturnGas(gas, price *big.Int) {}
  174. func (self *StateObject) Copy() *StateObject {
  175. stateObject := NewStateObject(self.Address(), self.db)
  176. stateObject.balance.Set(self.balance)
  177. stateObject.codeHash = common.CopyBytes(self.codeHash)
  178. stateObject.nonce = self.nonce
  179. stateObject.trie = self.trie
  180. stateObject.code = common.CopyBytes(self.code)
  181. stateObject.initCode = common.CopyBytes(self.initCode)
  182. stateObject.storage = self.storage.Copy()
  183. stateObject.remove = self.remove
  184. stateObject.dirty = self.dirty
  185. stateObject.deleted = self.deleted
  186. return stateObject
  187. }
  188. //
  189. // Attribute accessors
  190. //
  191. func (self *StateObject) Balance() *big.Int {
  192. return self.balance
  193. }
  194. // Returns the address of the contract/account
  195. func (c *StateObject) Address() common.Address {
  196. return c.address
  197. }
  198. func (self *StateObject) Trie() *trie.SecureTrie {
  199. return self.trie
  200. }
  201. func (self *StateObject) Root() []byte {
  202. return self.trie.Root()
  203. }
  204. func (self *StateObject) Code() []byte {
  205. return self.code
  206. }
  207. func (self *StateObject) SetCode(code []byte) {
  208. self.code = code
  209. self.dirty = true
  210. }
  211. func (self *StateObject) SetNonce(nonce uint64) {
  212. self.nonce = nonce
  213. self.dirty = true
  214. }
  215. func (self *StateObject) Nonce() uint64 {
  216. return self.nonce
  217. }
  218. func (self *StateObject) EachStorage(cb func(key, value []byte)) {
  219. // When iterating over the storage check the cache first
  220. for h, v := range self.storage {
  221. cb([]byte(h), v.Bytes())
  222. }
  223. it := self.trie.Iterator()
  224. for it.Next() {
  225. // ignore cached values
  226. key := self.trie.GetKey(it.Key)
  227. if _, ok := self.storage[string(key)]; !ok {
  228. cb(key, it.Value)
  229. }
  230. }
  231. }
  232. //
  233. // Encoding
  234. //
  235. // State object encoding methods
  236. func (c *StateObject) RlpEncode() []byte {
  237. return common.Encode([]interface{}{c.nonce, c.balance, c.Root(), c.CodeHash()})
  238. }
  239. func (c *StateObject) CodeHash() common.Bytes {
  240. return crypto.Sha3(c.code)
  241. }
  242. // Storage change object. Used by the manifest for notifying changes to
  243. // the sub channels.
  244. type StorageState struct {
  245. StateAddress []byte
  246. Address []byte
  247. Value *big.Int
  248. }