statedb.go 20 KB

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