statedb.go 32 KB

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