state_object.go 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  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.Keccak256(nil)
  30. type Code []byte
  31. func (self Code) String() string {
  32. return string(self) //strings.Join(Disassemble(self), " ")
  33. }
  34. type Storage map[common.Hash]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. // Cached storage (flushed when updated)
  62. storage Storage
  63. // Mark for deletion
  64. // When an object is marked for deletion it will be delete from the trie
  65. // during the "update" phase of the state transition
  66. remove bool
  67. deleted bool
  68. dirty bool
  69. }
  70. func NewStateObject(address common.Address, db trie.Database) *StateObject {
  71. object := &StateObject{
  72. db: db,
  73. address: address,
  74. balance: new(big.Int),
  75. dirty: true,
  76. codeHash: emptyCodeHash,
  77. storage: make(Storage),
  78. }
  79. object.trie, _ = trie.NewSecure(common.Hash{}, db)
  80. return object
  81. }
  82. func (self *StateObject) MarkForDeletion() {
  83. self.remove = true
  84. self.dirty = true
  85. if glog.V(logger.Core) {
  86. glog.Infof("%x: #%d %v X\n", self.Address(), self.nonce, self.balance)
  87. }
  88. }
  89. func (c *StateObject) getAddr(addr common.Hash) common.Hash {
  90. var ret []byte
  91. rlp.DecodeBytes(c.trie.Get(addr[:]), &ret)
  92. return common.BytesToHash(ret)
  93. }
  94. func (c *StateObject) setAddr(addr, value common.Hash) {
  95. v, err := rlp.EncodeToBytes(bytes.TrimLeft(value[:], "\x00"))
  96. if err != nil {
  97. // if RLPing failed we better panic and not fail silently. This would be considered a consensus issue
  98. panic(err)
  99. }
  100. c.trie.Update(addr[:], v)
  101. }
  102. func (self *StateObject) Storage() Storage {
  103. return self.storage
  104. }
  105. func (self *StateObject) GetState(key common.Hash) common.Hash {
  106. value, exists := self.storage[key]
  107. if !exists {
  108. value = self.getAddr(key)
  109. if (value != common.Hash{}) {
  110. self.storage[key] = value
  111. }
  112. }
  113. return value
  114. }
  115. func (self *StateObject) SetState(key, value common.Hash) {
  116. self.storage[key] = value
  117. self.dirty = true
  118. }
  119. // Update updates the current cached storage to the trie
  120. func (self *StateObject) Update() {
  121. for key, value := range self.storage {
  122. if (value == common.Hash{}) {
  123. self.trie.Delete(key[:])
  124. continue
  125. }
  126. self.setAddr(key, value)
  127. }
  128. }
  129. func (c *StateObject) AddBalance(amount *big.Int) {
  130. c.SetBalance(new(big.Int).Add(c.balance, amount))
  131. if glog.V(logger.Core) {
  132. glog.Infof("%x: #%d %v (+ %v)\n", c.Address(), c.nonce, c.balance, amount)
  133. }
  134. }
  135. func (c *StateObject) SubBalance(amount *big.Int) {
  136. c.SetBalance(new(big.Int).Sub(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. func (c *StateObject) SetBalance(amount *big.Int) {
  142. c.balance = amount
  143. c.dirty = true
  144. }
  145. func (c *StateObject) St() Storage {
  146. return c.storage
  147. }
  148. // Return the gas back to the origin. Used by the Virtual machine or Closures
  149. func (c *StateObject) ReturnGas(gas, price *big.Int) {}
  150. func (self *StateObject) Copy() *StateObject {
  151. stateObject := NewStateObject(self.Address(), self.db)
  152. stateObject.balance.Set(self.balance)
  153. stateObject.codeHash = common.CopyBytes(self.codeHash)
  154. stateObject.nonce = self.nonce
  155. stateObject.trie = self.trie
  156. stateObject.code = self.code
  157. stateObject.storage = self.storage.Copy()
  158. stateObject.remove = self.remove
  159. stateObject.dirty = self.dirty
  160. stateObject.deleted = self.deleted
  161. return stateObject
  162. }
  163. //
  164. // Attribute accessors
  165. //
  166. func (self *StateObject) Balance() *big.Int {
  167. return self.balance
  168. }
  169. // Returns the address of the contract/account
  170. func (c *StateObject) Address() common.Address {
  171. return c.address
  172. }
  173. func (self *StateObject) Trie() *trie.SecureTrie {
  174. return self.trie
  175. }
  176. func (self *StateObject) Root() []byte {
  177. return self.trie.Root()
  178. }
  179. func (self *StateObject) Code() []byte {
  180. return self.code
  181. }
  182. func (self *StateObject) SetCode(code []byte) {
  183. self.code = code
  184. self.codeHash = crypto.Keccak256(code)
  185. self.dirty = true
  186. }
  187. func (self *StateObject) SetNonce(nonce uint64) {
  188. self.nonce = nonce
  189. self.dirty = true
  190. }
  191. func (self *StateObject) Nonce() uint64 {
  192. return self.nonce
  193. }
  194. // Never called, but must be present to allow StateObject to be used
  195. // as a vm.Account interface that also satisfies the vm.ContractRef
  196. // interface. Interfaces are awesome.
  197. func (self *StateObject) Value() *big.Int {
  198. panic("Value on StateObject should never be called")
  199. }
  200. func (self *StateObject) ForEachStorage(cb func(key, value common.Hash) bool) {
  201. // When iterating over the storage check the cache first
  202. for h, value := range self.storage {
  203. cb(h, value)
  204. }
  205. it := self.trie.Iterator()
  206. for it.Next() {
  207. // ignore cached values
  208. key := common.BytesToHash(self.trie.GetKey(it.Key))
  209. if _, ok := self.storage[key]; !ok {
  210. cb(key, common.BytesToHash(it.Value))
  211. }
  212. }
  213. }
  214. type extStateObject struct {
  215. Nonce uint64
  216. Balance *big.Int
  217. Root common.Hash
  218. CodeHash []byte
  219. }
  220. // EncodeRLP implements rlp.Encoder.
  221. func (c *StateObject) EncodeRLP(w io.Writer) error {
  222. return rlp.Encode(w, []interface{}{c.nonce, c.balance, c.Root(), c.codeHash})
  223. }
  224. // DecodeObject decodes an RLP-encoded state object.
  225. func DecodeObject(address common.Address, db trie.Database, data []byte) (*StateObject, error) {
  226. var (
  227. obj = &StateObject{address: address, db: db, 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. if obj.trie, err = trie.NewSecure(ext.Root, db); err != nil {
  235. return nil, err
  236. }
  237. if !bytes.Equal(ext.CodeHash, emptyCodeHash) {
  238. if obj.code, err = db.Get(ext.CodeHash); err != nil {
  239. return nil, fmt.Errorf("can't get 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. }