state_object.go 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  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. // 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, 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. value, exists := self.storage[key]
  109. if !exists {
  110. value = self.getAddr(key)
  111. if (value != common.Hash{}) {
  112. self.storage[key] = value
  113. }
  114. }
  115. return value
  116. }
  117. func (self *StateObject) SetState(key, value common.Hash) {
  118. self.storage[key] = value
  119. self.dirty = true
  120. }
  121. // Update updates the current cached storage to the trie
  122. func (self *StateObject) Update() {
  123. for key, value := range self.storage {
  124. if (value == common.Hash{}) {
  125. self.trie.Delete(key[:])
  126. continue
  127. }
  128. self.setAddr(key, value)
  129. }
  130. }
  131. func (c *StateObject) AddBalance(amount *big.Int) {
  132. c.SetBalance(new(big.Int).Add(c.balance, amount))
  133. if glog.V(logger.Core) {
  134. glog.Infof("%x: #%d %v (+ %v)\n", c.Address(), c.nonce, c.balance, amount)
  135. }
  136. }
  137. func (c *StateObject) SubBalance(amount *big.Int) {
  138. c.SetBalance(new(big.Int).Sub(c.balance, amount))
  139. if glog.V(logger.Core) {
  140. glog.Infof("%x: #%d %v (- %v)\n", c.Address(), c.nonce, c.balance, amount)
  141. }
  142. }
  143. func (c *StateObject) SetBalance(amount *big.Int) {
  144. c.balance = amount
  145. c.dirty = true
  146. }
  147. func (c *StateObject) St() Storage {
  148. return c.storage
  149. }
  150. // Return the gas back to the origin. Used by the Virtual machine or Closures
  151. func (c *StateObject) ReturnGas(gas, price *big.Int) {}
  152. func (self *StateObject) Copy() *StateObject {
  153. stateObject := NewStateObject(self.Address(), self.db)
  154. stateObject.balance.Set(self.balance)
  155. stateObject.codeHash = common.CopyBytes(self.codeHash)
  156. stateObject.nonce = self.nonce
  157. stateObject.trie = self.trie
  158. stateObject.code = common.CopyBytes(self.code)
  159. stateObject.initCode = common.CopyBytes(self.initCode)
  160. stateObject.storage = self.storage.Copy()
  161. stateObject.remove = self.remove
  162. stateObject.dirty = self.dirty
  163. stateObject.deleted = self.deleted
  164. return stateObject
  165. }
  166. //
  167. // Attribute accessors
  168. //
  169. func (self *StateObject) Balance() *big.Int {
  170. return self.balance
  171. }
  172. // Returns the address of the contract/account
  173. func (c *StateObject) Address() common.Address {
  174. return c.address
  175. }
  176. func (self *StateObject) Trie() *trie.SecureTrie {
  177. return self.trie
  178. }
  179. func (self *StateObject) Root() []byte {
  180. return self.trie.Root()
  181. }
  182. func (self *StateObject) Code() []byte {
  183. return self.code
  184. }
  185. func (self *StateObject) SetCode(code []byte) {
  186. self.code = code
  187. self.codeHash = crypto.Keccak256(code)
  188. self.dirty = true
  189. }
  190. func (self *StateObject) SetNonce(nonce uint64) {
  191. self.nonce = nonce
  192. self.dirty = true
  193. }
  194. func (self *StateObject) Nonce() uint64 {
  195. return self.nonce
  196. }
  197. // Never called, but must be present to allow StateObject to be used
  198. // as a vm.Account interface that also satisfies the vm.ContractRef
  199. // interface. Interfaces are awesome.
  200. func (self *StateObject) Value() *big.Int {
  201. panic("Value on StateObject should never be called")
  202. }
  203. func (self *StateObject) ForEachStorage(cb func(key, value common.Hash) bool) {
  204. // When iterating over the storage check the cache first
  205. for h, value := range self.storage {
  206. cb(h, value)
  207. }
  208. it := self.trie.Iterator()
  209. for it.Next() {
  210. // ignore cached values
  211. key := common.BytesToHash(self.trie.GetKey(it.Key))
  212. if _, ok := self.storage[key]; !ok {
  213. cb(key, common.BytesToHash(it.Value))
  214. }
  215. }
  216. }
  217. type extStateObject struct {
  218. Nonce uint64
  219. Balance *big.Int
  220. Root common.Hash
  221. CodeHash []byte
  222. }
  223. // EncodeRLP implements rlp.Encoder.
  224. func (c *StateObject) EncodeRLP(w io.Writer) error {
  225. return rlp.Encode(w, []interface{}{c.nonce, c.balance, c.Root(), c.codeHash})
  226. }
  227. // DecodeObject decodes an RLP-encoded state object.
  228. func DecodeObject(address common.Address, db trie.Database, data []byte) (*StateObject, error) {
  229. var (
  230. obj = &StateObject{address: address, db: db, storage: make(Storage)}
  231. ext extStateObject
  232. err error
  233. )
  234. if err = rlp.DecodeBytes(data, &ext); err != nil {
  235. return nil, err
  236. }
  237. if obj.trie, err = trie.NewSecure(ext.Root, db); err != nil {
  238. return nil, err
  239. }
  240. if !bytes.Equal(ext.CodeHash, emptyCodeHash) {
  241. if obj.code, err = db.Get(ext.CodeHash); err != nil {
  242. return nil, fmt.Errorf("can't get code for hash %x: %v", ext.CodeHash, err)
  243. }
  244. }
  245. obj.nonce = ext.Nonce
  246. obj.balance = ext.Balance
  247. obj.codeHash = ext.CodeHash
  248. return obj, nil
  249. }