statedb.go 28 KB

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