state_object.go 10.0 KB

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