state_object.go 11 KB

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