statedb.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728
  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 provides a caching layer atop the Ethereum state trie.
  17. package state
  18. import (
  19. "errors"
  20. "fmt"
  21. "math/big"
  22. "sort"
  23. "time"
  24. "github.com/ethereum/go-ethereum/common"
  25. "github.com/ethereum/go-ethereum/core/types"
  26. "github.com/ethereum/go-ethereum/crypto"
  27. "github.com/ethereum/go-ethereum/log"
  28. "github.com/ethereum/go-ethereum/metrics"
  29. "github.com/ethereum/go-ethereum/rlp"
  30. "github.com/ethereum/go-ethereum/trie"
  31. )
  32. type revision struct {
  33. id int
  34. journalIndex int
  35. }
  36. var (
  37. // emptyRoot is the known root hash of an empty trie.
  38. emptyRoot = common.HexToHash("56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421")
  39. // emptyCode is the known hash of the empty EVM bytecode.
  40. emptyCode = crypto.Keccak256Hash(nil)
  41. )
  42. type proofList [][]byte
  43. func (n *proofList) Put(key []byte, value []byte) error {
  44. *n = append(*n, value)
  45. return nil
  46. }
  47. func (n *proofList) Delete(key []byte) error {
  48. panic("not supported")
  49. }
  50. // StateDBs within the ethereum protocol are used to store anything
  51. // within the merkle trie. StateDBs take care of caching and storing
  52. // nested states. It's the general query interface to retrieve:
  53. // * Contracts
  54. // * Accounts
  55. type StateDB struct {
  56. db Database
  57. trie Trie
  58. // This map holds 'live' objects, which will get modified while processing a state transition.
  59. stateObjects map[common.Address]*stateObject
  60. stateObjectsDirty map[common.Address]struct{}
  61. // DB error.
  62. // State objects are used by the consensus core and VM which are
  63. // unable to deal with database-level errors. Any error that occurs
  64. // during a database read is memoized here and will eventually be returned
  65. // by StateDB.Commit.
  66. dbErr error
  67. // The refund counter, also used by state transitioning.
  68. refund uint64
  69. thash, bhash common.Hash
  70. txIndex int
  71. logs map[common.Hash][]*types.Log
  72. logSize uint
  73. preimages map[common.Hash][]byte
  74. // Journal of state modifications. This is the backbone of
  75. // Snapshot and RevertToSnapshot.
  76. journal *journal
  77. validRevisions []revision
  78. nextRevisionId int
  79. // Measurements gathered during execution for debugging purposes
  80. AccountReads time.Duration
  81. AccountHashes time.Duration
  82. AccountUpdates time.Duration
  83. AccountCommits time.Duration
  84. StorageReads time.Duration
  85. StorageHashes time.Duration
  86. StorageUpdates time.Duration
  87. StorageCommits time.Duration
  88. }
  89. // Create a new state from a given trie.
  90. func New(root common.Hash, db Database) (*StateDB, error) {
  91. tr, err := db.OpenTrie(root)
  92. if err != nil {
  93. return nil, err
  94. }
  95. return &StateDB{
  96. db: db,
  97. trie: tr,
  98. stateObjects: make(map[common.Address]*stateObject),
  99. stateObjectsDirty: make(map[common.Address]struct{}),
  100. logs: make(map[common.Hash][]*types.Log),
  101. preimages: make(map[common.Hash][]byte),
  102. journal: newJournal(),
  103. }, nil
  104. }
  105. // setError remembers the first non-nil error it is called with.
  106. func (self *StateDB) setError(err error) {
  107. if self.dbErr == nil {
  108. self.dbErr = err
  109. }
  110. }
  111. func (self *StateDB) Error() error {
  112. return self.dbErr
  113. }
  114. // Reset clears out all ephemeral state objects from the state db, but keeps
  115. // the underlying state trie to avoid reloading data for the next operations.
  116. func (self *StateDB) Reset(root common.Hash) error {
  117. tr, err := self.db.OpenTrie(root)
  118. if err != nil {
  119. return err
  120. }
  121. self.trie = tr
  122. self.stateObjects = make(map[common.Address]*stateObject)
  123. self.stateObjectsDirty = make(map[common.Address]struct{})
  124. self.thash = common.Hash{}
  125. self.bhash = common.Hash{}
  126. self.txIndex = 0
  127. self.logs = make(map[common.Hash][]*types.Log)
  128. self.logSize = 0
  129. self.preimages = make(map[common.Hash][]byte)
  130. self.clearJournalAndRefund()
  131. return nil
  132. }
  133. func (self *StateDB) AddLog(log *types.Log) {
  134. self.journal.append(addLogChange{txhash: self.thash})
  135. log.TxHash = self.thash
  136. log.BlockHash = self.bhash
  137. log.TxIndex = uint(self.txIndex)
  138. log.Index = self.logSize
  139. self.logs[self.thash] = append(self.logs[self.thash], log)
  140. self.logSize++
  141. }
  142. func (self *StateDB) GetLogs(hash common.Hash) []*types.Log {
  143. return self.logs[hash]
  144. }
  145. func (self *StateDB) Logs() []*types.Log {
  146. var logs []*types.Log
  147. for _, lgs := range self.logs {
  148. logs = append(logs, lgs...)
  149. }
  150. return logs
  151. }
  152. // AddPreimage records a SHA3 preimage seen by the VM.
  153. func (self *StateDB) AddPreimage(hash common.Hash, preimage []byte) {
  154. if _, ok := self.preimages[hash]; !ok {
  155. self.journal.append(addPreimageChange{hash: hash})
  156. pi := make([]byte, len(preimage))
  157. copy(pi, preimage)
  158. self.preimages[hash] = pi
  159. }
  160. }
  161. // Preimages returns a list of SHA3 preimages that have been submitted.
  162. func (self *StateDB) Preimages() map[common.Hash][]byte {
  163. return self.preimages
  164. }
  165. // AddRefund adds gas to the refund counter
  166. func (self *StateDB) AddRefund(gas uint64) {
  167. self.journal.append(refundChange{prev: self.refund})
  168. self.refund += gas
  169. }
  170. // SubRefund removes gas from the refund counter.
  171. // This method will panic if the refund counter goes below zero
  172. func (self *StateDB) SubRefund(gas uint64) {
  173. self.journal.append(refundChange{prev: self.refund})
  174. if gas > self.refund {
  175. panic("Refund counter below zero")
  176. }
  177. self.refund -= gas
  178. }
  179. // Exist reports whether the given account address exists in the state.
  180. // Notably this also returns true for suicided accounts.
  181. func (self *StateDB) Exist(addr common.Address) bool {
  182. return self.getStateObject(addr) != nil
  183. }
  184. // Empty returns whether the state object is either non-existent
  185. // or empty according to the EIP161 specification (balance = nonce = code = 0)
  186. func (self *StateDB) Empty(addr common.Address) bool {
  187. so := self.getStateObject(addr)
  188. return so == nil || so.empty()
  189. }
  190. // Retrieve the balance from the given address or 0 if object not found
  191. func (self *StateDB) GetBalance(addr common.Address) *big.Int {
  192. stateObject := self.getStateObject(addr)
  193. if stateObject != nil {
  194. return stateObject.Balance()
  195. }
  196. return common.Big0
  197. }
  198. func (self *StateDB) GetNonce(addr common.Address) uint64 {
  199. stateObject := self.getStateObject(addr)
  200. if stateObject != nil {
  201. return stateObject.Nonce()
  202. }
  203. return 0
  204. }
  205. // TxIndex returns the current transaction index set by Prepare.
  206. func (self *StateDB) TxIndex() int {
  207. return self.txIndex
  208. }
  209. // BlockHash returns the current block hash set by Prepare.
  210. func (self *StateDB) BlockHash() common.Hash {
  211. return self.bhash
  212. }
  213. func (self *StateDB) GetCode(addr common.Address) []byte {
  214. stateObject := self.getStateObject(addr)
  215. if stateObject != nil {
  216. return stateObject.Code(self.db)
  217. }
  218. return nil
  219. }
  220. func (self *StateDB) GetCodeSize(addr common.Address) int {
  221. stateObject := self.getStateObject(addr)
  222. if stateObject == nil {
  223. return 0
  224. }
  225. if stateObject.code != nil {
  226. return len(stateObject.code)
  227. }
  228. size, err := self.db.ContractCodeSize(stateObject.addrHash, common.BytesToHash(stateObject.CodeHash()))
  229. if err != nil {
  230. self.setError(err)
  231. }
  232. return size
  233. }
  234. func (self *StateDB) GetCodeHash(addr common.Address) common.Hash {
  235. stateObject := self.getStateObject(addr)
  236. if stateObject == nil {
  237. return common.Hash{}
  238. }
  239. return common.BytesToHash(stateObject.CodeHash())
  240. }
  241. // GetState retrieves a value from the given account's storage trie.
  242. func (self *StateDB) GetState(addr common.Address, hash common.Hash) common.Hash {
  243. stateObject := self.getStateObject(addr)
  244. if stateObject != nil {
  245. return stateObject.GetState(self.db, hash)
  246. }
  247. return common.Hash{}
  248. }
  249. // GetProof returns the MerkleProof for a given Account
  250. func (self *StateDB) GetProof(a common.Address) ([][]byte, error) {
  251. var proof proofList
  252. err := self.trie.Prove(crypto.Keccak256(a.Bytes()), 0, &proof)
  253. return [][]byte(proof), err
  254. }
  255. // GetProof returns the StorageProof for given key
  256. func (self *StateDB) GetStorageProof(a common.Address, key common.Hash) ([][]byte, error) {
  257. var proof proofList
  258. trie := self.StorageTrie(a)
  259. if trie == nil {
  260. return proof, errors.New("storage trie for requested address does not exist")
  261. }
  262. err := trie.Prove(crypto.Keccak256(key.Bytes()), 0, &proof)
  263. return [][]byte(proof), err
  264. }
  265. // GetCommittedState retrieves a value from the given account's committed storage trie.
  266. func (self *StateDB) GetCommittedState(addr common.Address, hash common.Hash) common.Hash {
  267. stateObject := self.getStateObject(addr)
  268. if stateObject != nil {
  269. return stateObject.GetCommittedState(self.db, hash)
  270. }
  271. return common.Hash{}
  272. }
  273. // Database retrieves the low level database supporting the lower level trie ops.
  274. func (self *StateDB) Database() Database {
  275. return self.db
  276. }
  277. // StorageTrie returns the storage trie of an account.
  278. // The return value is a copy and is nil for non-existent accounts.
  279. func (self *StateDB) StorageTrie(addr common.Address) Trie {
  280. stateObject := self.getStateObject(addr)
  281. if stateObject == nil {
  282. return nil
  283. }
  284. cpy := stateObject.deepCopy(self)
  285. return cpy.updateTrie(self.db)
  286. }
  287. func (self *StateDB) HasSuicided(addr common.Address) bool {
  288. stateObject := self.getStateObject(addr)
  289. if stateObject != nil {
  290. return stateObject.suicided
  291. }
  292. return false
  293. }
  294. /*
  295. * SETTERS
  296. */
  297. // AddBalance adds amount to the account associated with addr.
  298. func (self *StateDB) AddBalance(addr common.Address, amount *big.Int) {
  299. stateObject := self.GetOrNewStateObject(addr)
  300. if stateObject != nil {
  301. stateObject.AddBalance(amount)
  302. }
  303. }
  304. // SubBalance subtracts amount from the account associated with addr.
  305. func (self *StateDB) SubBalance(addr common.Address, amount *big.Int) {
  306. stateObject := self.GetOrNewStateObject(addr)
  307. if stateObject != nil {
  308. stateObject.SubBalance(amount)
  309. }
  310. }
  311. func (self *StateDB) SetBalance(addr common.Address, amount *big.Int) {
  312. stateObject := self.GetOrNewStateObject(addr)
  313. if stateObject != nil {
  314. stateObject.SetBalance(amount)
  315. }
  316. }
  317. func (self *StateDB) SetNonce(addr common.Address, nonce uint64) {
  318. stateObject := self.GetOrNewStateObject(addr)
  319. if stateObject != nil {
  320. stateObject.SetNonce(nonce)
  321. }
  322. }
  323. func (self *StateDB) SetCode(addr common.Address, code []byte) {
  324. stateObject := self.GetOrNewStateObject(addr)
  325. if stateObject != nil {
  326. stateObject.SetCode(crypto.Keccak256Hash(code), code)
  327. }
  328. }
  329. func (self *StateDB) SetState(addr common.Address, key, value common.Hash) {
  330. stateObject := self.GetOrNewStateObject(addr)
  331. if stateObject != nil {
  332. stateObject.SetState(self.db, key, value)
  333. }
  334. }
  335. // Suicide marks the given account as suicided.
  336. // This clears the account balance.
  337. //
  338. // The account's state object is still available until the state is committed,
  339. // getStateObject will return a non-nil account after Suicide.
  340. func (self *StateDB) Suicide(addr common.Address) bool {
  341. stateObject := self.getStateObject(addr)
  342. if stateObject == nil {
  343. return false
  344. }
  345. self.journal.append(suicideChange{
  346. account: &addr,
  347. prev: stateObject.suicided,
  348. prevbalance: new(big.Int).Set(stateObject.Balance()),
  349. })
  350. stateObject.markSuicided()
  351. stateObject.data.Balance = new(big.Int)
  352. return true
  353. }
  354. //
  355. // Setting, updating & deleting state object methods.
  356. //
  357. // updateStateObject writes the given object to the trie.
  358. func (s *StateDB) updateStateObject(stateObject *stateObject) {
  359. // Track the amount of time wasted on updating the account from the trie
  360. if metrics.EnabledExpensive {
  361. defer func(start time.Time) { s.AccountUpdates += time.Since(start) }(time.Now())
  362. }
  363. // Encode the account and update the account trie
  364. addr := stateObject.Address()
  365. data, err := rlp.EncodeToBytes(stateObject)
  366. if err != nil {
  367. panic(fmt.Errorf("can't encode object at %x: %v", addr[:], err))
  368. }
  369. s.setError(s.trie.TryUpdate(addr[:], data))
  370. }
  371. // deleteStateObject removes the given object from the state trie.
  372. func (s *StateDB) deleteStateObject(stateObject *stateObject) {
  373. // Track the amount of time wasted on deleting the account from the trie
  374. if metrics.EnabledExpensive {
  375. defer func(start time.Time) { s.AccountUpdates += time.Since(start) }(time.Now())
  376. }
  377. // Delete the account from the trie
  378. stateObject.deleted = true
  379. addr := stateObject.Address()
  380. s.setError(s.trie.TryDelete(addr[:]))
  381. }
  382. // Retrieve a state object given by the address. Returns nil if not found.
  383. func (s *StateDB) getStateObject(addr common.Address) (stateObject *stateObject) {
  384. // Prefer live objects
  385. if obj := s.stateObjects[addr]; obj != nil {
  386. if obj.deleted {
  387. return nil
  388. }
  389. return obj
  390. }
  391. // Track the amount of time wasted on loading the object from the database
  392. if metrics.EnabledExpensive {
  393. defer func(start time.Time) { s.AccountReads += time.Since(start) }(time.Now())
  394. }
  395. // Load the object from the database
  396. enc, err := s.trie.TryGet(addr[:])
  397. if len(enc) == 0 {
  398. s.setError(err)
  399. return nil
  400. }
  401. var data Account
  402. if err := rlp.DecodeBytes(enc, &data); err != nil {
  403. log.Error("Failed to decode state object", "addr", addr, "err", err)
  404. return nil
  405. }
  406. // Insert into the live set
  407. obj := newObject(s, addr, data)
  408. s.setStateObject(obj)
  409. return obj
  410. }
  411. func (self *StateDB) setStateObject(object *stateObject) {
  412. self.stateObjects[object.Address()] = object
  413. }
  414. // Retrieve a state object or create a new state object if nil.
  415. func (self *StateDB) GetOrNewStateObject(addr common.Address) *stateObject {
  416. stateObject := self.getStateObject(addr)
  417. if stateObject == nil || stateObject.deleted {
  418. stateObject, _ = self.createObject(addr)
  419. }
  420. return stateObject
  421. }
  422. // createObject creates a new state object. If there is an existing account with
  423. // the given address, it is overwritten and returned as the second return value.
  424. func (self *StateDB) createObject(addr common.Address) (newobj, prev *stateObject) {
  425. prev = self.getStateObject(addr)
  426. newobj = newObject(self, addr, Account{})
  427. newobj.setNonce(0) // sets the object to dirty
  428. if prev == nil {
  429. self.journal.append(createObjectChange{account: &addr})
  430. } else {
  431. self.journal.append(resetObjectChange{prev: prev})
  432. }
  433. self.setStateObject(newobj)
  434. return newobj, prev
  435. }
  436. // CreateAccount explicitly creates a state object. If a state object with the address
  437. // already exists the balance is carried over to the new account.
  438. //
  439. // CreateAccount is called during the EVM CREATE operation. The situation might arise that
  440. // a contract does the following:
  441. //
  442. // 1. sends funds to sha(account ++ (nonce + 1))
  443. // 2. tx_create(sha(account ++ nonce)) (note that this gets the address of 1)
  444. //
  445. // Carrying over the balance ensures that Ether doesn't disappear.
  446. func (self *StateDB) CreateAccount(addr common.Address) {
  447. newObj, prev := self.createObject(addr)
  448. if prev != nil {
  449. newObj.setBalance(prev.data.Balance)
  450. }
  451. }
  452. func (db *StateDB) ForEachStorage(addr common.Address, cb func(key, value common.Hash) bool) error {
  453. so := db.getStateObject(addr)
  454. if so == nil {
  455. return nil
  456. }
  457. it := trie.NewIterator(so.getTrie(db.db).NodeIterator(nil))
  458. for it.Next() {
  459. key := common.BytesToHash(db.trie.GetKey(it.Key))
  460. if value, dirty := so.dirtyStorage[key]; dirty {
  461. if !cb(key, value) {
  462. return nil
  463. }
  464. continue
  465. }
  466. if len(it.Value) > 0 {
  467. _, content, _, err := rlp.Split(it.Value)
  468. if err != nil {
  469. return err
  470. }
  471. if !cb(key, common.BytesToHash(content)) {
  472. return nil
  473. }
  474. }
  475. }
  476. return nil
  477. }
  478. // Copy creates a deep, independent copy of the state.
  479. // Snapshots of the copied state cannot be applied to the copy.
  480. func (self *StateDB) Copy() *StateDB {
  481. // Copy all the basic fields, initialize the memory ones
  482. state := &StateDB{
  483. db: self.db,
  484. trie: self.db.CopyTrie(self.trie),
  485. stateObjects: make(map[common.Address]*stateObject, len(self.journal.dirties)),
  486. stateObjectsDirty: make(map[common.Address]struct{}, len(self.journal.dirties)),
  487. refund: self.refund,
  488. logs: make(map[common.Hash][]*types.Log, len(self.logs)),
  489. logSize: self.logSize,
  490. preimages: make(map[common.Hash][]byte, len(self.preimages)),
  491. journal: newJournal(),
  492. }
  493. // Copy the dirty states, logs, and preimages
  494. for addr := range self.journal.dirties {
  495. // As documented [here](https://github.com/ethereum/go-ethereum/pull/16485#issuecomment-380438527),
  496. // and in the Finalise-method, there is a case where an object is in the journal but not
  497. // in the stateObjects: OOG after touch on ripeMD prior to Byzantium. Thus, we need to check for
  498. // nil
  499. if object, exist := self.stateObjects[addr]; exist {
  500. state.stateObjects[addr] = object.deepCopy(state)
  501. state.stateObjectsDirty[addr] = struct{}{}
  502. }
  503. }
  504. // Above, we don't copy the actual journal. This means that if the copy is copied, the
  505. // loop above will be a no-op, since the copy's journal is empty.
  506. // Thus, here we iterate over stateObjects, to enable copies of copies
  507. for addr := range self.stateObjectsDirty {
  508. if _, exist := state.stateObjects[addr]; !exist {
  509. state.stateObjects[addr] = self.stateObjects[addr].deepCopy(state)
  510. state.stateObjectsDirty[addr] = struct{}{}
  511. }
  512. }
  513. for hash, logs := range self.logs {
  514. cpy := make([]*types.Log, len(logs))
  515. for i, l := range logs {
  516. cpy[i] = new(types.Log)
  517. *cpy[i] = *l
  518. }
  519. state.logs[hash] = cpy
  520. }
  521. for hash, preimage := range self.preimages {
  522. state.preimages[hash] = preimage
  523. }
  524. return state
  525. }
  526. // Snapshot returns an identifier for the current revision of the state.
  527. func (self *StateDB) Snapshot() int {
  528. id := self.nextRevisionId
  529. self.nextRevisionId++
  530. self.validRevisions = append(self.validRevisions, revision{id, self.journal.length()})
  531. return id
  532. }
  533. // RevertToSnapshot reverts all state changes made since the given revision.
  534. func (self *StateDB) RevertToSnapshot(revid int) {
  535. // Find the snapshot in the stack of valid snapshots.
  536. idx := sort.Search(len(self.validRevisions), func(i int) bool {
  537. return self.validRevisions[i].id >= revid
  538. })
  539. if idx == len(self.validRevisions) || self.validRevisions[idx].id != revid {
  540. panic(fmt.Errorf("revision id %v cannot be reverted", revid))
  541. }
  542. snapshot := self.validRevisions[idx].journalIndex
  543. // Replay the journal to undo changes and remove invalidated snapshots
  544. self.journal.revert(self, snapshot)
  545. self.validRevisions = self.validRevisions[:idx]
  546. }
  547. // GetRefund returns the current value of the refund counter.
  548. func (self *StateDB) GetRefund() uint64 {
  549. return self.refund
  550. }
  551. // Finalise finalises the state by removing the self destructed objects
  552. // and clears the journal as well as the refunds.
  553. func (s *StateDB) Finalise(deleteEmptyObjects bool) {
  554. for addr := range s.journal.dirties {
  555. stateObject, exist := s.stateObjects[addr]
  556. if !exist {
  557. // ripeMD is 'touched' at block 1714175, in tx 0x1237f737031e40bcde4a8b7e717b2d15e3ecadfe49bb1bbc71ee9deb09c6fcf2
  558. // That tx goes out of gas, and although the notion of 'touched' does not exist there, the
  559. // touch-event will still be recorded in the journal. Since ripeMD is a special snowflake,
  560. // it will persist in the journal even though the journal is reverted. In this special circumstance,
  561. // it may exist in `s.journal.dirties` but not in `s.stateObjects`.
  562. // Thus, we can safely ignore it here
  563. continue
  564. }
  565. if stateObject.suicided || (deleteEmptyObjects && stateObject.empty()) {
  566. s.deleteStateObject(stateObject)
  567. } else {
  568. stateObject.updateRoot(s.db)
  569. s.updateStateObject(stateObject)
  570. }
  571. s.stateObjectsDirty[addr] = struct{}{}
  572. }
  573. // Invalidate journal because reverting across transactions is not allowed.
  574. s.clearJournalAndRefund()
  575. }
  576. // IntermediateRoot computes the current root hash of the state trie.
  577. // It is called in between transactions to get the root hash that
  578. // goes into transaction receipts.
  579. func (s *StateDB) IntermediateRoot(deleteEmptyObjects bool) common.Hash {
  580. s.Finalise(deleteEmptyObjects)
  581. // Track the amount of time wasted on hashing the account trie
  582. if metrics.EnabledExpensive {
  583. defer func(start time.Time) { s.AccountHashes += time.Since(start) }(time.Now())
  584. }
  585. return s.trie.Hash()
  586. }
  587. // Prepare sets the current transaction hash and index and block hash which is
  588. // used when the EVM emits new state logs.
  589. func (self *StateDB) Prepare(thash, bhash common.Hash, ti int) {
  590. self.thash = thash
  591. self.bhash = bhash
  592. self.txIndex = ti
  593. }
  594. func (s *StateDB) clearJournalAndRefund() {
  595. s.journal = newJournal()
  596. s.validRevisions = s.validRevisions[:0]
  597. s.refund = 0
  598. }
  599. // Commit writes the state to the underlying in-memory trie database.
  600. func (s *StateDB) Commit(deleteEmptyObjects bool) (root common.Hash, err error) {
  601. defer s.clearJournalAndRefund()
  602. for addr := range s.journal.dirties {
  603. s.stateObjectsDirty[addr] = struct{}{}
  604. }
  605. // Commit objects to the trie, measuring the elapsed time
  606. for addr, stateObject := range s.stateObjects {
  607. _, isDirty := s.stateObjectsDirty[addr]
  608. switch {
  609. case stateObject.suicided || (isDirty && deleteEmptyObjects && stateObject.empty()):
  610. // If the object has been removed, don't bother syncing it
  611. // and just mark it for deletion in the trie.
  612. s.deleteStateObject(stateObject)
  613. case isDirty:
  614. // Write any contract code associated with the state object
  615. if stateObject.code != nil && stateObject.dirtyCode {
  616. s.db.TrieDB().InsertBlob(common.BytesToHash(stateObject.CodeHash()), stateObject.code)
  617. stateObject.dirtyCode = false
  618. }
  619. // Write any storage changes in the state object to its storage trie.
  620. if err := stateObject.CommitTrie(s.db); err != nil {
  621. return common.Hash{}, err
  622. }
  623. // Update the object in the main account trie.
  624. s.updateStateObject(stateObject)
  625. }
  626. delete(s.stateObjectsDirty, addr)
  627. }
  628. // Write the account trie changes, measuing the amount of wasted time
  629. if metrics.EnabledExpensive {
  630. defer func(start time.Time) { s.AccountCommits += time.Since(start) }(time.Now())
  631. }
  632. root, err = s.trie.Commit(func(leaf []byte, parent common.Hash) error {
  633. var account Account
  634. if err := rlp.DecodeBytes(leaf, &account); err != nil {
  635. return nil
  636. }
  637. if account.Root != emptyRoot {
  638. s.db.TrieDB().Reference(account.Root, parent)
  639. }
  640. code := common.BytesToHash(account.CodeHash)
  641. if code != emptyCode {
  642. s.db.TrieDB().Reference(code, parent)
  643. }
  644. return nil
  645. })
  646. return root, err
  647. }