state_object.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576
  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. "time"
  23. "github.com/ethereum/go-ethereum/common"
  24. "github.com/ethereum/go-ethereum/crypto"
  25. "github.com/ethereum/go-ethereum/metrics"
  26. "github.com/ethereum/go-ethereum/rlp"
  27. )
  28. var emptyCodeHash = crypto.Keccak256(nil)
  29. type Code []byte
  30. func (c Code) String() string {
  31. return string(c) //strings.Join(Disassemble(c), " ")
  32. }
  33. type Storage map[common.Hash]common.Hash
  34. func (s Storage) String() (str string) {
  35. for key, value := range s {
  36. str += fmt.Sprintf("%X : %X\n", key, value)
  37. }
  38. return
  39. }
  40. func (s Storage) Copy() Storage {
  41. cpy := make(Storage)
  42. for key, value := range s {
  43. cpy[key] = value
  44. }
  45. return cpy
  46. }
  47. // StateObject represents an Ethereum account which is being modified.
  48. //
  49. // The usage pattern is as follows:
  50. // First you need to obtain a state object.
  51. // Account values can be accessed and modified through the object.
  52. // Finally, call CommitTrie to write the modified storage trie into a database.
  53. type StateObject struct {
  54. address common.Address
  55. addrHash common.Hash // hash of ethereum address of the 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 // storage trie, which becomes non-nil on first access
  66. code Code // contract bytecode, which gets set when code is loaded
  67. originStorage Storage // Storage cache of original entries to dedup rewrites, reset for every transaction
  68. pendingStorage Storage // Storage entries that need to be flushed to disk, at the end of an entire block
  69. dirtyStorage Storage // Storage entries that have been modified in the current transaction execution
  70. fakeStorage Storage // Fake storage which constructed by caller for debugging purpose.
  71. // Cache flags.
  72. // When an object is marked suicided it will be delete from the trie
  73. // during the "update" phase of the state transition.
  74. dirtyCode bool // true if the code was updated
  75. suicided bool
  76. deleted bool
  77. //encode
  78. encodeData []byte
  79. }
  80. // empty returns whether the account is considered empty.
  81. func (s *StateObject) empty() bool {
  82. return s.data.Nonce == 0 && s.data.Balance.Sign() == 0 && bytes.Equal(s.data.CodeHash, emptyCodeHash)
  83. }
  84. // Account is the Ethereum consensus representation of accounts.
  85. // These objects are stored in the main account trie.
  86. type Account struct {
  87. Nonce uint64
  88. Balance *big.Int
  89. Root common.Hash // merkle root of the storage trie
  90. CodeHash []byte
  91. }
  92. // newObject creates a state object.
  93. func newObject(db *StateDB, address common.Address, data Account) *StateObject {
  94. if data.Balance == nil {
  95. data.Balance = new(big.Int)
  96. }
  97. if data.CodeHash == nil {
  98. data.CodeHash = emptyCodeHash
  99. }
  100. if data.Root == (common.Hash{}) {
  101. data.Root = emptyRoot
  102. }
  103. return &StateObject{
  104. db: db,
  105. address: address,
  106. addrHash: crypto.Keccak256Hash(address[:]),
  107. data: data,
  108. originStorage: make(Storage),
  109. pendingStorage: make(Storage),
  110. dirtyStorage: make(Storage),
  111. }
  112. }
  113. // EncodeRLP implements rlp.Encoder.
  114. func (s *StateObject) EncodeRLP(w io.Writer) error {
  115. return rlp.Encode(w, s.data)
  116. }
  117. // setError remembers the first non-nil error it is called with.
  118. func (s *StateObject) setError(err error) {
  119. if s.dbErr == nil {
  120. s.dbErr = err
  121. }
  122. }
  123. func (s *StateObject) markSuicided() {
  124. s.suicided = true
  125. }
  126. func (s *StateObject) touch() {
  127. s.db.journal.append(touchChange{
  128. account: &s.address,
  129. })
  130. if s.address == ripemd {
  131. // Explicitly put it in the dirty-cache, which is otherwise generated from
  132. // flattened journals.
  133. s.db.journal.dirty(s.address)
  134. }
  135. }
  136. func (s *StateObject) getTrie(db Database) Trie {
  137. if s.trie == nil {
  138. // Try fetching from prefetcher first
  139. // We don't prefetch empty tries
  140. if s.data.Root != emptyRoot && s.db.prefetcher != nil {
  141. // When the miner is creating the pending state, there is no
  142. // prefetcher
  143. s.trie = s.db.prefetcher.trie(s.data.Root)
  144. }
  145. if s.trie == nil {
  146. var err error
  147. s.trie, err = db.OpenStorageTrie(s.addrHash, s.data.Root)
  148. if err != nil {
  149. s.trie, _ = db.OpenStorageTrie(s.addrHash, common.Hash{})
  150. s.setError(fmt.Errorf("can't create storage trie: %v", err))
  151. }
  152. }
  153. }
  154. return s.trie
  155. }
  156. // GetState retrieves a value from the account storage trie.
  157. func (s *StateObject) GetState(db Database, key common.Hash) common.Hash {
  158. // If the fake storage is set, only lookup the state here(in the debugging mode)
  159. if s.fakeStorage != nil {
  160. return s.fakeStorage[key]
  161. }
  162. // If we have a dirty value for this state entry, return it
  163. value, dirty := s.dirtyStorage[key]
  164. if dirty {
  165. return value
  166. }
  167. // Otherwise return the entry's original value
  168. return s.GetCommittedState(db, key)
  169. }
  170. // GetCommittedState retrieves a value from the committed account storage trie.
  171. func (s *StateObject) GetCommittedState(db Database, key common.Hash) common.Hash {
  172. // If the fake storage is set, only lookup the state here(in the debugging mode)
  173. if s.fakeStorage != nil {
  174. return s.fakeStorage[key]
  175. }
  176. // If we have a pending write or clean cached, return that
  177. if value, pending := s.pendingStorage[key]; pending {
  178. return value
  179. }
  180. if value, cached := s.originStorage[key]; cached {
  181. return value
  182. }
  183. // If no live objects are available, attempt to use snapshots
  184. var (
  185. enc []byte
  186. err error
  187. meter *time.Duration
  188. )
  189. readStart := time.Now()
  190. if metrics.EnabledExpensive {
  191. // If the snap is 'under construction', the first lookup may fail. If that
  192. // happens, we don't want to double-count the time elapsed. Thus this
  193. // dance with the metering.
  194. defer func() {
  195. if meter != nil {
  196. *meter += time.Since(readStart)
  197. }
  198. }()
  199. }
  200. if s.db.snap != nil {
  201. if metrics.EnabledExpensive {
  202. meter = &s.db.SnapshotStorageReads
  203. }
  204. // If the object was destructed in *this* block (and potentially resurrected),
  205. // the storage has been cleared out, and we should *not* consult the previous
  206. // snapshot about any storage values. The only possible alternatives are:
  207. // 1) resurrect happened, and new slot values were set -- those should
  208. // have been handles via pendingStorage above.
  209. // 2) we don't have new values, and can deliver empty response back
  210. if _, destructed := s.db.snapDestructs[s.address]; destructed {
  211. return common.Hash{}
  212. }
  213. enc, err = s.db.snap.Storage(s.addrHash, crypto.Keccak256Hash(key.Bytes()))
  214. }
  215. // If snapshot unavailable or reading from it failed, load from the database
  216. if s.db.snap == nil || err != nil {
  217. if meter != nil {
  218. // If we already spent time checking the snapshot, account for it
  219. // and reset the readStart
  220. *meter += time.Since(readStart)
  221. readStart = time.Now()
  222. }
  223. if metrics.EnabledExpensive {
  224. meter = &s.db.StorageReads
  225. }
  226. if enc, err = s.getTrie(db).TryGet(key.Bytes()); err != nil {
  227. s.setError(err)
  228. return common.Hash{}
  229. }
  230. }
  231. var value common.Hash
  232. if len(enc) > 0 {
  233. _, content, _, err := rlp.Split(enc)
  234. if err != nil {
  235. s.setError(err)
  236. }
  237. value.SetBytes(content)
  238. }
  239. s.originStorage[key] = value
  240. return value
  241. }
  242. // SetState updates a value in account storage.
  243. func (s *StateObject) SetState(db Database, key, value common.Hash) {
  244. // If the fake storage is set, put the temporary state update here.
  245. if s.fakeStorage != nil {
  246. s.fakeStorage[key] = value
  247. return
  248. }
  249. // If the new value is the same as old, don't set
  250. prev := s.GetState(db, key)
  251. if prev == value {
  252. return
  253. }
  254. // New value is different, update and journal the change
  255. s.db.journal.append(storageChange{
  256. account: &s.address,
  257. key: key,
  258. prevalue: prev,
  259. })
  260. s.setState(key, value)
  261. }
  262. // SetStorage replaces the entire state storage with the given one.
  263. //
  264. // After this function is called, all original state will be ignored and state
  265. // lookup only happens in the fake state storage.
  266. //
  267. // Note this function should only be used for debugging purpose.
  268. func (s *StateObject) SetStorage(storage map[common.Hash]common.Hash) {
  269. // Allocate fake storage if it's nil.
  270. if s.fakeStorage == nil {
  271. s.fakeStorage = make(Storage)
  272. }
  273. for key, value := range storage {
  274. s.fakeStorage[key] = value
  275. }
  276. // Don't bother journal since this function should only be used for
  277. // debugging and the `fake` storage won't be committed to database.
  278. }
  279. func (s *StateObject) setState(key, value common.Hash) {
  280. s.dirtyStorage[key] = value
  281. }
  282. // finalise moves all dirty storage slots into the pending area to be hashed or
  283. // committed later. It is invoked at the end of every transaction.
  284. func (s *StateObject) finalise(prefetch bool) {
  285. slotsToPrefetch := make([][]byte, 0, len(s.dirtyStorage))
  286. for key, value := range s.dirtyStorage {
  287. s.pendingStorage[key] = value
  288. if value != s.originStorage[key] {
  289. slotsToPrefetch = append(slotsToPrefetch, common.CopyBytes(key[:])) // Copy needed for closure
  290. }
  291. }
  292. if s.db.prefetcher != nil && prefetch && len(slotsToPrefetch) > 0 && s.data.Root != emptyRoot {
  293. s.db.prefetcher.prefetch(s.data.Root, slotsToPrefetch, s.addrHash)
  294. }
  295. if len(s.dirtyStorage) > 0 {
  296. s.dirtyStorage = make(Storage)
  297. }
  298. }
  299. // updateTrie writes cached storage modifications into the object's storage trie.
  300. // It will return nil if the trie has not been loaded and no changes have been made
  301. func (s *StateObject) updateTrie(db Database) Trie {
  302. // Make sure all dirty slots are finalized into the pending storage area
  303. s.finalise(false) // Don't prefetch any more, pull directly if need be
  304. if len(s.pendingStorage) == 0 {
  305. return s.trie
  306. }
  307. // Track the amount of time wasted on updating the storage trie
  308. if metrics.EnabledExpensive {
  309. defer func(start time.Time) {
  310. s.db.MetricsMux.Lock()
  311. s.db.StorageUpdates += time.Since(start)
  312. s.db.MetricsMux.Unlock()
  313. }(time.Now())
  314. }
  315. // The snapshot storage map for the object
  316. var storage map[string][]byte
  317. // Insert all the pending updates into the trie
  318. tr := s.getTrie(db)
  319. usedStorage := make([][]byte, 0, len(s.pendingStorage))
  320. for key, value := range s.pendingStorage {
  321. // Skip noop changes, persist actual changes
  322. if value == s.originStorage[key] {
  323. continue
  324. }
  325. s.originStorage[key] = value
  326. var v []byte
  327. if (value == common.Hash{}) {
  328. s.setError(tr.TryDelete(key[:]))
  329. } else {
  330. // Encoding []byte cannot fail, ok to ignore the error.
  331. v, _ = rlp.EncodeToBytes(common.TrimLeftZeroes(value[:]))
  332. s.setError(tr.TryUpdate(key[:], v))
  333. }
  334. // If state snapshotting is active, cache the data til commit
  335. if s.db.snap != nil {
  336. s.db.snapMux.Lock()
  337. if storage == nil {
  338. // Retrieve the old storage map, if available, create a new one otherwise
  339. if storage = s.db.snapStorage[s.address]; storage == nil {
  340. storage = make(map[string][]byte)
  341. s.db.snapStorage[s.address] = storage
  342. }
  343. }
  344. storage[string(key[:])] = v // v will be nil if value is 0x00
  345. s.db.snapMux.Unlock()
  346. }
  347. usedStorage = append(usedStorage, common.CopyBytes(key[:])) // Copy needed for closure
  348. }
  349. if s.db.prefetcher != nil {
  350. s.db.prefetcher.used(s.data.Root, usedStorage)
  351. }
  352. if len(s.pendingStorage) > 0 {
  353. s.pendingStorage = make(Storage)
  354. }
  355. return tr
  356. }
  357. // UpdateRoot sets the trie root to the current root hash of
  358. func (s *StateObject) updateRoot(db Database) {
  359. // If nothing changed, don't bother with hashing anything
  360. if s.updateTrie(db) == nil {
  361. return
  362. }
  363. // Track the amount of time wasted on hashing the storage trie
  364. if metrics.EnabledExpensive {
  365. defer func(start time.Time) {
  366. s.db.MetricsMux.Lock()
  367. s.db.StorageHashes += time.Since(start)
  368. s.db.MetricsMux.Unlock()
  369. }(time.Now())
  370. }
  371. s.data.Root = s.trie.Hash()
  372. }
  373. // CommitTrie the storage trie of the object to db.
  374. // This updates the trie root.
  375. func (s *StateObject) CommitTrie(db Database) error {
  376. // If nothing changed, don't bother with hashing anything
  377. if s.updateTrie(db) == nil {
  378. if s.trie != nil && s.data.Root != emptyRoot {
  379. db.CacheStorage(s.addrHash, s.data.Root, s.trie)
  380. }
  381. return nil
  382. }
  383. if s.dbErr != nil {
  384. return s.dbErr
  385. }
  386. // Track the amount of time wasted on committing the storage trie
  387. if metrics.EnabledExpensive {
  388. defer func(start time.Time) { s.db.StorageCommits += time.Since(start) }(time.Now())
  389. }
  390. root, err := s.trie.Commit(nil)
  391. if err == nil {
  392. s.data.Root = root
  393. }
  394. if s.data.Root != emptyRoot {
  395. db.CacheStorage(s.addrHash, s.data.Root, s.trie)
  396. }
  397. return err
  398. }
  399. // AddBalance adds amount to s's balance.
  400. // It is used to add funds to the destination account of a transfer.
  401. func (s *StateObject) AddBalance(amount *big.Int) {
  402. // EIP161: We must check emptiness for the objects such that the account
  403. // clearing (0,0,0 objects) can take effect.
  404. if amount.Sign() == 0 {
  405. if s.empty() {
  406. s.touch()
  407. }
  408. return
  409. }
  410. s.SetBalance(new(big.Int).Add(s.Balance(), amount))
  411. }
  412. // SubBalance removes amount from s's balance.
  413. // It is used to remove funds from the origin account of a transfer.
  414. func (s *StateObject) SubBalance(amount *big.Int) {
  415. if amount.Sign() == 0 {
  416. return
  417. }
  418. s.SetBalance(new(big.Int).Sub(s.Balance(), amount))
  419. }
  420. func (s *StateObject) SetBalance(amount *big.Int) {
  421. s.db.journal.append(balanceChange{
  422. account: &s.address,
  423. prev: new(big.Int).Set(s.data.Balance),
  424. })
  425. s.setBalance(amount)
  426. }
  427. func (s *StateObject) setBalance(amount *big.Int) {
  428. s.data.Balance = amount
  429. }
  430. // Return the gas back to the origin. Used by the Virtual machine or Closures
  431. func (s *StateObject) ReturnGas(gas *big.Int) {}
  432. func (s *StateObject) deepCopy(db *StateDB) *StateObject {
  433. stateObject := newObject(db, s.address, s.data)
  434. if s.trie != nil {
  435. stateObject.trie = db.db.CopyTrie(s.trie)
  436. }
  437. stateObject.code = s.code
  438. stateObject.dirtyStorage = s.dirtyStorage.Copy()
  439. stateObject.originStorage = s.originStorage.Copy()
  440. stateObject.pendingStorage = s.pendingStorage.Copy()
  441. stateObject.suicided = s.suicided
  442. stateObject.dirtyCode = s.dirtyCode
  443. stateObject.deleted = s.deleted
  444. return stateObject
  445. }
  446. //
  447. // Attribute accessors
  448. //
  449. // Returns the address of the contract/account
  450. func (s *StateObject) Address() common.Address {
  451. return s.address
  452. }
  453. // Code returns the contract code associated with this object, if any.
  454. func (s *StateObject) Code(db Database) []byte {
  455. if s.code != nil {
  456. return s.code
  457. }
  458. if bytes.Equal(s.CodeHash(), emptyCodeHash) {
  459. return nil
  460. }
  461. code, err := db.ContractCode(s.addrHash, common.BytesToHash(s.CodeHash()))
  462. if err != nil {
  463. s.setError(fmt.Errorf("can't load code hash %x: %v", s.CodeHash(), err))
  464. }
  465. s.code = code
  466. return code
  467. }
  468. // CodeSize returns the size of the contract code associated with this object,
  469. // or zero if none. This method is an almost mirror of Code, but uses a cache
  470. // inside the database to avoid loading codes seen recently.
  471. func (s *StateObject) CodeSize(db Database) int {
  472. if s.code != nil {
  473. return len(s.code)
  474. }
  475. if bytes.Equal(s.CodeHash(), emptyCodeHash) {
  476. return 0
  477. }
  478. size, err := db.ContractCodeSize(s.addrHash, common.BytesToHash(s.CodeHash()))
  479. if err != nil {
  480. s.setError(fmt.Errorf("can't load code size %x: %v", s.CodeHash(), err))
  481. }
  482. return size
  483. }
  484. func (s *StateObject) SetCode(codeHash common.Hash, code []byte) {
  485. prevcode := s.Code(s.db.db)
  486. s.db.journal.append(codeChange{
  487. account: &s.address,
  488. prevhash: s.CodeHash(),
  489. prevcode: prevcode,
  490. })
  491. s.setCode(codeHash, code)
  492. }
  493. func (s *StateObject) setCode(codeHash common.Hash, code []byte) {
  494. s.code = code
  495. s.data.CodeHash = codeHash[:]
  496. s.dirtyCode = true
  497. }
  498. func (s *StateObject) SetNonce(nonce uint64) {
  499. s.db.journal.append(nonceChange{
  500. account: &s.address,
  501. prev: s.data.Nonce,
  502. })
  503. s.setNonce(nonce)
  504. }
  505. func (s *StateObject) setNonce(nonce uint64) {
  506. s.data.Nonce = nonce
  507. }
  508. func (s *StateObject) CodeHash() []byte {
  509. return s.data.CodeHash
  510. }
  511. func (s *StateObject) Balance() *big.Int {
  512. return s.data.Balance
  513. }
  514. func (s *StateObject) Nonce() uint64 {
  515. return s.data.Nonce
  516. }
  517. // Never called, but must be present to allow StateObject to be used
  518. // as a vm.Account interface that also satisfies the vm.ContractRef
  519. // interface. Interfaces are awesome.
  520. func (s *StateObject) Value() *big.Int {
  521. panic("Value on StateObject should never be called")
  522. }