state_object.go 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  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. // StateObject represents an Ethereum account which is being modified.
  49. //
  50. // The usage pattern is as follows:
  51. // First you need to obtain a state object.
  52. // Account values can be accessed and modified through the object.
  53. // Finally, call CommitTrie to write the modified storage trie into a database.
  54. type StateObject struct {
  55. address common.Address // Ethereum address of this account
  56. data Account
  57. // DB error.
  58. // State objects are used by the consensus core and VM which are
  59. // unable to deal with database-level errors. Any error that occurs
  60. // during a database read is memoized here and will eventually be returned
  61. // by StateDB.Commit.
  62. dbErr error
  63. // Write caches.
  64. trie *trie.SecureTrie // storage trie, which becomes non-nil on first access
  65. code Code // contract bytecode, which gets set when code is loaded
  66. storage Storage // Cached storage (flushed when updated)
  67. // Cache flags.
  68. // When an object is marked for deletion it will be delete from the trie
  69. // during the "update" phase of the state transition
  70. dirtyCode bool // true if the code was updated
  71. remove bool
  72. deleted bool
  73. onDirty func(addr common.Address) // Callback method to mark a state object newly dirty
  74. }
  75. // Account is the Ethereum consensus representation of accounts.
  76. // These objects are stored in the main account trie.
  77. type Account struct {
  78. Nonce uint64
  79. Balance *big.Int
  80. Root common.Hash // merkle root of the storage trie
  81. CodeHash []byte
  82. codeSize *int
  83. }
  84. // NewObject creates a state object.
  85. func NewObject(address common.Address, data Account, onDirty func(addr common.Address)) *StateObject {
  86. if data.Balance == nil {
  87. data.Balance = new(big.Int)
  88. }
  89. if data.CodeHash == nil {
  90. data.CodeHash = emptyCodeHash
  91. }
  92. return &StateObject{address: address, data: data, storage: make(Storage), onDirty: onDirty}
  93. }
  94. // EncodeRLP implements rlp.Encoder.
  95. func (c *StateObject) EncodeRLP(w io.Writer) error {
  96. return rlp.Encode(w, c.data)
  97. }
  98. // setError remembers the first non-nil error it is called with.
  99. func (self *StateObject) setError(err error) {
  100. if self.dbErr == nil {
  101. self.dbErr = err
  102. }
  103. }
  104. func (self *StateObject) MarkForDeletion() {
  105. self.remove = true
  106. if self.onDirty != nil {
  107. self.onDirty(self.Address())
  108. self.onDirty = nil
  109. }
  110. if glog.V(logger.Core) {
  111. glog.Infof("%x: #%d %v X\n", self.Address(), self.Nonce(), self.Balance())
  112. }
  113. }
  114. func (c *StateObject) getTrie(db trie.Database) *trie.SecureTrie {
  115. if c.trie == nil {
  116. var err error
  117. c.trie, err = trie.NewSecure(c.data.Root, db)
  118. if err != nil {
  119. c.trie, _ = trie.NewSecure(common.Hash{}, db)
  120. c.setError(fmt.Errorf("can't create storage trie: %v", err))
  121. }
  122. }
  123. return c.trie
  124. }
  125. // GetState returns a value in account storage.
  126. func (self *StateObject) GetState(db trie.Database, key common.Hash) common.Hash {
  127. value, exists := self.storage[key]
  128. if exists {
  129. return value
  130. }
  131. // Load from DB in case it is missing.
  132. tr := self.getTrie(db)
  133. var ret []byte
  134. rlp.DecodeBytes(tr.Get(key[:]), &ret)
  135. value = common.BytesToHash(ret)
  136. if (value != common.Hash{}) {
  137. self.storage[key] = value
  138. }
  139. return value
  140. }
  141. // SetState updates a value in account storage.
  142. func (self *StateObject) SetState(key, value common.Hash) {
  143. self.storage[key] = value
  144. if self.onDirty != nil {
  145. self.onDirty(self.Address())
  146. self.onDirty = nil
  147. }
  148. }
  149. // updateTrie writes cached storage modifications into the object's storage trie.
  150. func (self *StateObject) updateTrie(db trie.Database) {
  151. tr := self.getTrie(db)
  152. for key, value := range self.storage {
  153. if (value == common.Hash{}) {
  154. tr.Delete(key[:])
  155. continue
  156. }
  157. // Encoding []byte cannot fail, ok to ignore the error.
  158. v, _ := rlp.EncodeToBytes(bytes.TrimLeft(value[:], "\x00"))
  159. tr.Update(key[:], v)
  160. }
  161. }
  162. // UpdateRoot sets the trie root to the current root hash of
  163. func (self *StateObject) UpdateRoot(db trie.Database) {
  164. self.updateTrie(db)
  165. self.data.Root = self.trie.Hash()
  166. }
  167. // CommitTrie the storage trie of the object to dwb.
  168. // This updates the trie root.
  169. func (self *StateObject) CommitTrie(db trie.Database, dbw trie.DatabaseWriter) error {
  170. self.updateTrie(db)
  171. if self.dbErr != nil {
  172. fmt.Println("dbErr:", self.dbErr)
  173. return self.dbErr
  174. }
  175. root, err := self.trie.CommitTo(dbw)
  176. if err == nil {
  177. self.data.Root = root
  178. }
  179. return err
  180. }
  181. func (c *StateObject) AddBalance(amount *big.Int) {
  182. if amount.Cmp(common.Big0) == 0 {
  183. return
  184. }
  185. c.SetBalance(new(big.Int).Add(c.Balance(), amount))
  186. if glog.V(logger.Core) {
  187. glog.Infof("%x: #%d %v (+ %v)\n", c.Address(), c.Nonce(), c.Balance(), amount)
  188. }
  189. }
  190. func (c *StateObject) SubBalance(amount *big.Int) {
  191. if amount.Cmp(common.Big0) == 0 {
  192. return
  193. }
  194. c.SetBalance(new(big.Int).Sub(c.Balance(), amount))
  195. if glog.V(logger.Core) {
  196. glog.Infof("%x: #%d %v (- %v)\n", c.Address(), c.Nonce(), c.Balance(), amount)
  197. }
  198. }
  199. func (self *StateObject) SetBalance(amount *big.Int) {
  200. self.data.Balance = amount
  201. if self.onDirty != nil {
  202. self.onDirty(self.Address())
  203. self.onDirty = nil
  204. }
  205. }
  206. // Return the gas back to the origin. Used by the Virtual machine or Closures
  207. func (c *StateObject) ReturnGas(gas, price *big.Int) {}
  208. func (self *StateObject) Copy(db trie.Database, onDirty func(addr common.Address)) *StateObject {
  209. stateObject := NewObject(self.address, self.data, onDirty)
  210. stateObject.trie = self.trie
  211. stateObject.code = self.code
  212. stateObject.storage = self.storage.Copy()
  213. stateObject.remove = self.remove
  214. stateObject.dirtyCode = self.dirtyCode
  215. stateObject.deleted = self.deleted
  216. return stateObject
  217. }
  218. //
  219. // Attribute accessors
  220. //
  221. // Returns the address of the contract/account
  222. func (c *StateObject) Address() common.Address {
  223. return c.address
  224. }
  225. // Code returns the contract code associated with this object, if any.
  226. func (self *StateObject) Code(db trie.Database) []byte {
  227. if self.code != nil {
  228. return self.code
  229. }
  230. if bytes.Equal(self.CodeHash(), emptyCodeHash) {
  231. return nil
  232. }
  233. code, err := db.Get(self.CodeHash())
  234. if err != nil {
  235. self.setError(fmt.Errorf("can't load code hash %x: %v", self.CodeHash(), err))
  236. }
  237. self.code = code
  238. return code
  239. }
  240. // CodeSize returns the size of the contract code associated with this object.
  241. func (self *StateObject) CodeSize(db trie.Database) int {
  242. if self.data.codeSize == nil {
  243. self.data.codeSize = new(int)
  244. *self.data.codeSize = len(self.Code(db))
  245. }
  246. return *self.data.codeSize
  247. }
  248. func (self *StateObject) SetCode(code []byte) {
  249. self.code = code
  250. self.data.CodeHash = crypto.Keccak256(code)
  251. self.data.codeSize = new(int)
  252. *self.data.codeSize = len(code)
  253. self.dirtyCode = true
  254. if self.onDirty != nil {
  255. self.onDirty(self.Address())
  256. self.onDirty = nil
  257. }
  258. }
  259. func (self *StateObject) SetNonce(nonce uint64) {
  260. self.data.Nonce = nonce
  261. if self.onDirty != nil {
  262. self.onDirty(self.Address())
  263. self.onDirty = nil
  264. }
  265. }
  266. func (self *StateObject) CodeHash() []byte {
  267. return self.data.CodeHash
  268. }
  269. func (self *StateObject) Balance() *big.Int {
  270. return self.data.Balance
  271. }
  272. func (self *StateObject) Nonce() uint64 {
  273. return self.data.Nonce
  274. }
  275. // Never called, but must be present to allow StateObject to be used
  276. // as a vm.Account interface that also satisfies the vm.ContractRef
  277. // interface. Interfaces are awesome.
  278. func (self *StateObject) Value() *big.Int {
  279. panic("Value on StateObject should never be called")
  280. }
  281. func (self *StateObject) ForEachStorage(cb func(key, value common.Hash) bool) {
  282. // When iterating over the storage check the cache first
  283. for h, value := range self.storage {
  284. cb(h, value)
  285. }
  286. it := self.trie.Iterator()
  287. for it.Next() {
  288. // ignore cached values
  289. key := common.BytesToHash(self.trie.GetKey(it.Key))
  290. if _, ok := self.storage[key]; !ok {
  291. cb(key, common.BytesToHash(it.Value))
  292. }
  293. }
  294. }