statedb.go 20 KB

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