state_object.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  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. "io"
  21. "math/big"
  22. "github.com/ethereum/go-ethereum/common"
  23. "github.com/ethereum/go-ethereum/crypto"
  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. var emptyCodeHash = crypto.Sha3(nil)
  30. type Code []byte
  31. func (self Code) String() string {
  32. return string(self) //strings.Join(Disassemble(self), " ")
  33. }
  34. type Storage map[string]common.Hash
  35. func (self Storage) String() (str string) {
  36. for key, value := range self {
  37. str += fmt.Sprintf("%X : %X\n", key, value)
  38. }
  39. return
  40. }
  41. func (self Storage) Copy() Storage {
  42. cpy := make(Storage)
  43. for key, value := range self {
  44. cpy[key] = value
  45. }
  46. return cpy
  47. }
  48. type StateObject struct {
  49. db trie.Database // State database for storing state changes
  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 trie.Database) *StateObject {
  73. object := &StateObject{
  74. db: db,
  75. address: address,
  76. balance: new(big.Int),
  77. dirty: true,
  78. codeHash: emptyCodeHash,
  79. storage: make(Storage),
  80. }
  81. object.trie, _ = trie.NewSecure(common.Hash{}, db)
  82. return object
  83. }
  84. func (self *StateObject) MarkForDeletion() {
  85. self.remove = true
  86. self.dirty = true
  87. if glog.V(logger.Core) {
  88. glog.Infof("%x: #%d %v X\n", self.Address(), self.nonce, self.balance)
  89. }
  90. }
  91. func (c *StateObject) getAddr(addr common.Hash) common.Hash {
  92. var ret []byte
  93. rlp.DecodeBytes(c.trie.Get(addr[:]), &ret)
  94. return common.BytesToHash(ret)
  95. }
  96. func (c *StateObject) setAddr(addr []byte, value common.Hash) {
  97. v, err := rlp.EncodeToBytes(bytes.TrimLeft(value[:], "\x00"))
  98. if err != nil {
  99. // if RLPing failed we better panic and not fail silently. This would be considered a consensus issue
  100. panic(err)
  101. }
  102. c.trie.Update(addr, v)
  103. }
  104. func (self *StateObject) Storage() Storage {
  105. return self.storage
  106. }
  107. func (self *StateObject) GetState(key common.Hash) common.Hash {
  108. strkey := key.Str()
  109. value, exists := self.storage[strkey]
  110. if !exists {
  111. value = self.getAddr(key)
  112. if (value != common.Hash{}) {
  113. self.storage[strkey] = value
  114. }
  115. }
  116. return value
  117. }
  118. func (self *StateObject) SetState(k, value common.Hash) {
  119. self.storage[k.Str()] = value
  120. self.dirty = true
  121. }
  122. // Update updates the current cached storage to the trie
  123. func (self *StateObject) Update() {
  124. for key, value := range self.storage {
  125. if (value == common.Hash{}) {
  126. self.trie.Delete([]byte(key))
  127. continue
  128. }
  129. self.setAddr([]byte(key), value)
  130. }
  131. }
  132. func (c *StateObject) AddBalance(amount *big.Int) {
  133. c.SetBalance(new(big.Int).Add(c.balance, amount))
  134. if glog.V(logger.Core) {
  135. glog.Infof("%x: #%d %v (+ %v)\n", c.Address(), c.nonce, c.balance, amount)
  136. }
  137. }
  138. func (c *StateObject) SubBalance(amount *big.Int) {
  139. c.SetBalance(new(big.Int).Sub(c.balance, amount))
  140. if glog.V(logger.Core) {
  141. glog.Infof("%x: #%d %v (- %v)\n", c.Address(), c.nonce, c.balance, amount)
  142. }
  143. }
  144. func (c *StateObject) SetBalance(amount *big.Int) {
  145. c.balance = amount
  146. c.dirty = true
  147. }
  148. func (c *StateObject) St() Storage {
  149. return c.storage
  150. }
  151. // Return the gas back to the origin. Used by the Virtual machine or Closures
  152. func (c *StateObject) ReturnGas(gas, price *big.Int) {}
  153. func (self *StateObject) Copy() *StateObject {
  154. stateObject := NewStateObject(self.Address(), self.db)
  155. stateObject.balance.Set(self.balance)
  156. stateObject.codeHash = common.CopyBytes(self.codeHash)
  157. stateObject.nonce = self.nonce
  158. stateObject.trie = self.trie
  159. stateObject.code = common.CopyBytes(self.code)
  160. stateObject.initCode = common.CopyBytes(self.initCode)
  161. stateObject.storage = self.storage.Copy()
  162. stateObject.remove = self.remove
  163. stateObject.dirty = self.dirty
  164. stateObject.deleted = self.deleted
  165. return stateObject
  166. }
  167. //
  168. // Attribute accessors
  169. //
  170. func (self *StateObject) Balance() *big.Int {
  171. return self.balance
  172. }
  173. // Returns the address of the contract/account
  174. func (c *StateObject) Address() common.Address {
  175. return c.address
  176. }
  177. // Sets the address of the contract/account
  178. func (c *StateObject) SetAddress(addr common.Address) {
  179. c.address = addr
  180. }
  181. func (self *StateObject) Trie() *trie.SecureTrie {
  182. return self.trie
  183. }
  184. func (self *StateObject) Root() []byte {
  185. return self.trie.Root()
  186. }
  187. func (self *StateObject) Code() []byte {
  188. return self.code
  189. }
  190. func (self *StateObject) SetCode(code []byte) {
  191. self.code = code
  192. self.codeHash = crypto.Sha3(code)
  193. self.dirty = true
  194. }
  195. func (self *StateObject) SetNonce(nonce uint64) {
  196. self.nonce = nonce
  197. self.dirty = true
  198. }
  199. func (self *StateObject) Nonce() uint64 {
  200. return self.nonce
  201. }
  202. // Never called, but must be present to allow StateObject to be used
  203. // as a vm.Account interface that also satisfies the vm.ContractRef
  204. // interface. Interfaces are awesome.
  205. func (self *StateObject) Value() *big.Int {
  206. return nil
  207. }
  208. func (self *StateObject) EachStorage(cb func(key, value []byte)) {
  209. // When iterating over the storage check the cache first
  210. for h, v := range self.storage {
  211. cb([]byte(h), v.Bytes())
  212. }
  213. it := self.trie.Iterator()
  214. for it.Next() {
  215. // ignore cached values
  216. key := self.trie.GetKey(it.Key)
  217. if _, ok := self.storage[string(key)]; !ok {
  218. cb(key, it.Value)
  219. }
  220. }
  221. }
  222. // Encoding
  223. type extStateObject struct {
  224. Nonce uint64
  225. Balance *big.Int
  226. Root common.Hash
  227. CodeHash []byte
  228. }
  229. // EncodeRLP implements rlp.Encoder.
  230. func (c *StateObject) EncodeRLP(w io.Writer) error {
  231. return rlp.Encode(w, []interface{}{c.nonce, c.balance, c.Root(), c.codeHash})
  232. }
  233. // DecodeObject decodes an RLP-encoded state object.
  234. func DecodeObject(address common.Address, db trie.Database, data []byte) (*StateObject, error) {
  235. var (
  236. obj = &StateObject{address: address, db: db, storage: make(Storage)}
  237. ext extStateObject
  238. err error
  239. )
  240. if err = rlp.DecodeBytes(data, &ext); err != nil {
  241. return nil, err
  242. }
  243. if obj.trie, err = trie.NewSecure(ext.Root, db); err != nil {
  244. return nil, err
  245. }
  246. if !bytes.Equal(ext.CodeHash, emptyCodeHash) {
  247. if obj.code, err = db.Get(ext.CodeHash); err != nil {
  248. return nil, fmt.Errorf("can't find code for hash %x: %v", ext.CodeHash, err)
  249. }
  250. }
  251. obj.nonce = ext.Nonce
  252. obj.balance = ext.Balance
  253. obj.codeHash = ext.CodeHash
  254. return obj, nil
  255. }