statedb.go 24 KB

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