statedb.go 35 KB

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