statedb.go 20 KB

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