statedb.go 20 KB

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