statedb.go 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257
  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. "runtime"
  23. "sort"
  24. "sync"
  25. "time"
  26. "github.com/ethereum/go-ethereum/common"
  27. "github.com/ethereum/go-ethereum/core/rawdb"
  28. "github.com/ethereum/go-ethereum/core/state/snapshot"
  29. "github.com/ethereum/go-ethereum/core/types"
  30. "github.com/ethereum/go-ethereum/crypto"
  31. "github.com/ethereum/go-ethereum/ethdb"
  32. "github.com/ethereum/go-ethereum/log"
  33. "github.com/ethereum/go-ethereum/metrics"
  34. "github.com/ethereum/go-ethereum/rlp"
  35. "github.com/ethereum/go-ethereum/trie"
  36. )
  37. const (
  38. preLoadLimit = 64
  39. defaultNumOfSlots = 100
  40. )
  41. type revision struct {
  42. id int
  43. journalIndex int
  44. }
  45. var (
  46. // emptyRoot is the known root hash of an empty trie.
  47. emptyRoot = common.HexToHash("56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421")
  48. emptyAddr = crypto.Keccak256Hash(common.Address{}.Bytes())
  49. )
  50. type proofList [][]byte
  51. func (n *proofList) Put(key []byte, value []byte) error {
  52. *n = append(*n, value)
  53. return nil
  54. }
  55. func (n *proofList) Delete(key []byte) error {
  56. panic("not supported")
  57. }
  58. // StateDB structs within the ethereum protocol are used to store anything
  59. // within the merkle trie. StateDBs take care of caching and storing
  60. // nested states. It's the general query interface to retrieve:
  61. // * Contracts
  62. // * Accounts
  63. type StateDB struct {
  64. db Database
  65. prefetcher *triePrefetcher
  66. originalRoot common.Hash // The pre-state root, before any changes were made
  67. trie Trie
  68. hasher crypto.KeccakState
  69. snapMux sync.Mutex
  70. snaps *snapshot.Tree
  71. snap snapshot.Snapshot
  72. snapDestructs map[common.Hash]struct{}
  73. snapAccounts map[common.Hash][]byte
  74. snapStorage map[common.Hash]map[common.Hash][]byte
  75. // This map holds 'live' objects, which will get modified while processing a state transition.
  76. stateObjects map[common.Address]*StateObject
  77. stateObjectsPending map[common.Address]struct{} // State objects finalized but not yet written to the trie
  78. stateObjectsDirty map[common.Address]struct{} // State objects modified in the current execution
  79. // DB error.
  80. // State objects are used by the consensus core and VM which are
  81. // unable to deal with database-level errors. Any error that occurs
  82. // during a database read is memoized here and will eventually be returned
  83. // by StateDB.Commit.
  84. dbErr error
  85. // The refund counter, also used by state transitioning.
  86. refund uint64
  87. thash, bhash common.Hash
  88. txIndex int
  89. logs map[common.Hash][]*types.Log
  90. logSize uint
  91. preimages map[common.Hash][]byte
  92. // Per-transaction access list
  93. accessList *accessList
  94. // Journal of state modifications. This is the backbone of
  95. // Snapshot and RevertToSnapshot.
  96. journal *journal
  97. validRevisions []revision
  98. nextRevisionId int
  99. // Measurements gathered during execution for debugging purposes
  100. MetricsMux sync.Mutex
  101. AccountReads time.Duration
  102. AccountHashes time.Duration
  103. AccountUpdates time.Duration
  104. AccountCommits time.Duration
  105. StorageReads time.Duration
  106. StorageHashes time.Duration
  107. StorageUpdates time.Duration
  108. StorageCommits time.Duration
  109. SnapshotAccountReads time.Duration
  110. SnapshotStorageReads time.Duration
  111. SnapshotCommits time.Duration
  112. }
  113. // New creates a new state from a given trie.
  114. func New(root common.Hash, db Database, snaps *snapshot.Tree) (*StateDB, error) {
  115. return newStateDB(root, db, snaps)
  116. }
  117. func newStateDB(root common.Hash, db Database, snaps *snapshot.Tree) (*StateDB, error) {
  118. sdb := &StateDB{
  119. db: db,
  120. originalRoot: root,
  121. snaps: snaps,
  122. stateObjects: make(map[common.Address]*StateObject, defaultNumOfSlots),
  123. stateObjectsPending: make(map[common.Address]struct{}, defaultNumOfSlots),
  124. stateObjectsDirty: make(map[common.Address]struct{}, defaultNumOfSlots),
  125. logs: make(map[common.Hash][]*types.Log, defaultNumOfSlots),
  126. preimages: make(map[common.Hash][]byte),
  127. journal: newJournal(),
  128. hasher: crypto.NewKeccakState(),
  129. }
  130. tr, err := db.OpenTrie(root)
  131. if err != nil {
  132. return nil, err
  133. }
  134. sdb.trie = tr
  135. if sdb.snaps != nil {
  136. if sdb.snap = sdb.snaps.Snapshot(root); sdb.snap != nil {
  137. sdb.snapDestructs = make(map[common.Hash]struct{})
  138. sdb.snapAccounts = make(map[common.Hash][]byte)
  139. sdb.snapStorage = make(map[common.Hash]map[common.Hash][]byte)
  140. }
  141. }
  142. return sdb, nil
  143. }
  144. // StartPrefetcher initializes a new trie prefetcher to pull in nodes from the
  145. // state trie concurrently while the state is mutated so that when we reach the
  146. // commit phase, most of the needed data is already hot.
  147. func (s *StateDB) StartPrefetcher(namespace string) {
  148. if s.prefetcher != nil {
  149. s.prefetcher.close()
  150. s.prefetcher = nil
  151. }
  152. if s.snap != nil {
  153. s.prefetcher = newTriePrefetcher(s.db, s.originalRoot, namespace)
  154. }
  155. }
  156. // StopPrefetcher terminates a running prefetcher and reports any leftover stats
  157. // from the gathered metrics.
  158. func (s *StateDB) StopPrefetcher() {
  159. if s.prefetcher != nil {
  160. s.prefetcher.close()
  161. s.prefetcher = nil
  162. }
  163. }
  164. // setError remembers the first non-nil error it is called with.
  165. func (s *StateDB) setError(err error) {
  166. if s.dbErr == nil {
  167. s.dbErr = err
  168. }
  169. }
  170. func (s *StateDB) Error() error {
  171. return s.dbErr
  172. }
  173. func (s *StateDB) AddLog(log *types.Log) {
  174. s.journal.append(addLogChange{txhash: s.thash})
  175. log.TxHash = s.thash
  176. log.BlockHash = s.bhash
  177. log.TxIndex = uint(s.txIndex)
  178. log.Index = s.logSize
  179. s.logs[s.thash] = append(s.logs[s.thash], log)
  180. s.logSize++
  181. }
  182. func (s *StateDB) GetLogs(hash common.Hash) []*types.Log {
  183. return s.logs[hash]
  184. }
  185. func (s *StateDB) Logs() []*types.Log {
  186. var logs []*types.Log
  187. for _, lgs := range s.logs {
  188. logs = append(logs, lgs...)
  189. }
  190. return logs
  191. }
  192. // AddPreimage records a SHA3 preimage seen by the VM.
  193. func (s *StateDB) AddPreimage(hash common.Hash, preimage []byte) {
  194. if _, ok := s.preimages[hash]; !ok {
  195. s.journal.append(addPreimageChange{hash: hash})
  196. pi := make([]byte, len(preimage))
  197. copy(pi, preimage)
  198. s.preimages[hash] = pi
  199. }
  200. }
  201. // Preimages returns a list of SHA3 preimages that have been submitted.
  202. func (s *StateDB) Preimages() map[common.Hash][]byte {
  203. return s.preimages
  204. }
  205. // AddRefund adds gas to the refund counter
  206. func (s *StateDB) AddRefund(gas uint64) {
  207. s.journal.append(refundChange{prev: s.refund})
  208. s.refund += gas
  209. }
  210. // SubRefund removes gas from the refund counter.
  211. // This method will panic if the refund counter goes below zero
  212. func (s *StateDB) SubRefund(gas uint64) {
  213. s.journal.append(refundChange{prev: s.refund})
  214. if gas > s.refund {
  215. panic(fmt.Sprintf("Refund counter below zero (gas: %d > refund: %d)", gas, s.refund))
  216. }
  217. s.refund -= gas
  218. }
  219. // Exist reports whether the given account address exists in the state.
  220. // Notably this also returns true for suicided accounts.
  221. func (s *StateDB) Exist(addr common.Address) bool {
  222. return s.getStateObject(addr) != nil
  223. }
  224. // Empty returns whether the state object is either non-existent
  225. // or empty according to the EIP161 specification (balance = nonce = code = 0)
  226. func (s *StateDB) Empty(addr common.Address) bool {
  227. so := s.getStateObject(addr)
  228. return so == nil || so.empty()
  229. }
  230. // GetBalance retrieves the balance from the given address or 0 if object not found
  231. func (s *StateDB) GetBalance(addr common.Address) *big.Int {
  232. stateObject := s.getStateObject(addr)
  233. if stateObject != nil {
  234. return stateObject.Balance()
  235. }
  236. return common.Big0
  237. }
  238. func (s *StateDB) GetNonce(addr common.Address) uint64 {
  239. stateObject := s.getStateObject(addr)
  240. if stateObject != nil {
  241. return stateObject.Nonce()
  242. }
  243. return 0
  244. }
  245. // TxIndex returns the current transaction index set by Prepare.
  246. func (s *StateDB) TxIndex() int {
  247. return s.txIndex
  248. }
  249. // BlockHash returns the current block hash set by Prepare.
  250. func (s *StateDB) BlockHash() common.Hash {
  251. return s.bhash
  252. }
  253. func (s *StateDB) GetCode(addr common.Address) []byte {
  254. stateObject := s.getStateObject(addr)
  255. if stateObject != nil {
  256. return stateObject.Code(s.db)
  257. }
  258. return nil
  259. }
  260. func (s *StateDB) GetCodeSize(addr common.Address) int {
  261. stateObject := s.getStateObject(addr)
  262. if stateObject != nil {
  263. return stateObject.CodeSize(s.db)
  264. }
  265. return 0
  266. }
  267. func (s *StateDB) GetCodeHash(addr common.Address) common.Hash {
  268. stateObject := s.getStateObject(addr)
  269. if stateObject == nil {
  270. return common.Hash{}
  271. }
  272. return common.BytesToHash(stateObject.CodeHash())
  273. }
  274. // GetState retrieves a value from the given account's storage trie.
  275. func (s *StateDB) GetState(addr common.Address, hash common.Hash) common.Hash {
  276. stateObject := s.getStateObject(addr)
  277. if stateObject != nil {
  278. return stateObject.GetState(s.db, hash)
  279. }
  280. return common.Hash{}
  281. }
  282. // GetProof returns the Merkle proof for a given account.
  283. func (s *StateDB) GetProof(addr common.Address) ([][]byte, error) {
  284. return s.GetProofByHash(crypto.Keccak256Hash(addr.Bytes()))
  285. }
  286. // GetProofByHash returns the Merkle proof for a given account.
  287. func (s *StateDB) GetProofByHash(addrHash common.Hash) ([][]byte, error) {
  288. var proof proofList
  289. err := s.trie.Prove(addrHash[:], 0, &proof)
  290. return proof, err
  291. }
  292. // GetStorageProof returns the Merkle proof for given storage slot.
  293. func (s *StateDB) GetStorageProof(a common.Address, key common.Hash) ([][]byte, error) {
  294. var proof proofList
  295. trie := s.StorageTrie(a)
  296. if trie == nil {
  297. return proof, errors.New("storage trie for requested address does not exist")
  298. }
  299. err := trie.Prove(crypto.Keccak256(key.Bytes()), 0, &proof)
  300. return proof, err
  301. }
  302. // GetStorageProofByHash returns the Merkle proof for given storage slot.
  303. func (s *StateDB) GetStorageProofByHash(a common.Address, key common.Hash) ([][]byte, error) {
  304. var proof proofList
  305. trie := s.StorageTrie(a)
  306. if trie == nil {
  307. return proof, errors.New("storage trie for requested address does not exist")
  308. }
  309. err := trie.Prove(crypto.Keccak256(key.Bytes()), 0, &proof)
  310. return proof, err
  311. }
  312. // GetCommittedState retrieves a value from the given account's committed storage trie.
  313. func (s *StateDB) GetCommittedState(addr common.Address, hash common.Hash) common.Hash {
  314. stateObject := s.getStateObject(addr)
  315. if stateObject != nil {
  316. return stateObject.GetCommittedState(s.db, hash)
  317. }
  318. return common.Hash{}
  319. }
  320. // Database retrieves the low level database supporting the lower level trie ops.
  321. func (s *StateDB) Database() Database {
  322. return s.db
  323. }
  324. // StorageTrie returns the storage trie of an account.
  325. // The return value is a copy and is nil for non-existent accounts.
  326. func (s *StateDB) StorageTrie(addr common.Address) Trie {
  327. stateObject := s.getStateObject(addr)
  328. if stateObject == nil {
  329. return nil
  330. }
  331. cpy := stateObject.deepCopy(s)
  332. cpy.updateTrie(s.db)
  333. return cpy.getTrie(s.db)
  334. }
  335. func (s *StateDB) HasSuicided(addr common.Address) bool {
  336. stateObject := s.getStateObject(addr)
  337. if stateObject != nil {
  338. return stateObject.suicided
  339. }
  340. return false
  341. }
  342. /*
  343. * SETTERS
  344. */
  345. // AddBalance adds amount to the account associated with addr.
  346. func (s *StateDB) AddBalance(addr common.Address, amount *big.Int) {
  347. stateObject := s.GetOrNewStateObject(addr)
  348. if stateObject != nil {
  349. stateObject.AddBalance(amount)
  350. }
  351. }
  352. // SubBalance subtracts amount from the account associated with addr.
  353. func (s *StateDB) SubBalance(addr common.Address, amount *big.Int) {
  354. stateObject := s.GetOrNewStateObject(addr)
  355. if stateObject != nil {
  356. stateObject.SubBalance(amount)
  357. }
  358. }
  359. func (s *StateDB) SetBalance(addr common.Address, amount *big.Int) {
  360. stateObject := s.GetOrNewStateObject(addr)
  361. if stateObject != nil {
  362. stateObject.SetBalance(amount)
  363. }
  364. }
  365. func (s *StateDB) SetNonce(addr common.Address, nonce uint64) {
  366. stateObject := s.GetOrNewStateObject(addr)
  367. if stateObject != nil {
  368. stateObject.SetNonce(nonce)
  369. }
  370. }
  371. func (s *StateDB) SetCode(addr common.Address, code []byte) {
  372. stateObject := s.GetOrNewStateObject(addr)
  373. if stateObject != nil {
  374. stateObject.SetCode(crypto.Keccak256Hash(code), code)
  375. }
  376. }
  377. func (s *StateDB) SetState(addr common.Address, key, value common.Hash) {
  378. stateObject := s.GetOrNewStateObject(addr)
  379. if stateObject != nil {
  380. stateObject.SetState(s.db, key, value)
  381. }
  382. }
  383. // SetStorage replaces the entire storage for the specified account with given
  384. // storage. This function should only be used for debugging.
  385. func (s *StateDB) SetStorage(addr common.Address, storage map[common.Hash]common.Hash) {
  386. stateObject := s.GetOrNewStateObject(addr)
  387. if stateObject != nil {
  388. stateObject.SetStorage(storage)
  389. }
  390. }
  391. // Suicide marks the given account as suicided.
  392. // This clears the account balance.
  393. //
  394. // The account's state object is still available until the state is committed,
  395. // getStateObject will return a non-nil account after Suicide.
  396. func (s *StateDB) Suicide(addr common.Address) bool {
  397. stateObject := s.getStateObject(addr)
  398. if stateObject == nil {
  399. return false
  400. }
  401. s.journal.append(suicideChange{
  402. account: &addr,
  403. prev: stateObject.suicided,
  404. prevbalance: new(big.Int).Set(stateObject.Balance()),
  405. })
  406. stateObject.markSuicided()
  407. stateObject.data.Balance = new(big.Int)
  408. return true
  409. }
  410. //
  411. // Setting, updating & deleting state object methods.
  412. //
  413. // updateStateObject writes the given object to the trie.
  414. func (s *StateDB) updateStateObject(obj *StateObject) {
  415. // Track the amount of time wasted on updating the account from the trie
  416. if metrics.EnabledExpensive {
  417. defer func(start time.Time) { s.AccountUpdates += time.Since(start) }(time.Now())
  418. }
  419. // Encode the account and update the account trie
  420. addr := obj.Address()
  421. data := obj.encodeData
  422. var err error
  423. if data == nil {
  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. }
  429. if err = s.trie.TryUpdate(addr[:], data); err != nil {
  430. s.setError(fmt.Errorf("updateStateObject (%x) error: %v", addr[:], err))
  431. }
  432. }
  433. // deleteStateObject removes the given object from the state trie.
  434. func (s *StateDB) deleteStateObject(obj *StateObject) {
  435. // Track the amount of time wasted on deleting the account from the trie
  436. if metrics.EnabledExpensive {
  437. defer func(start time.Time) { s.AccountUpdates += time.Since(start) }(time.Now())
  438. }
  439. // Delete the account from the trie
  440. addr := obj.Address()
  441. if err := s.trie.TryDelete(addr[:]); err != nil {
  442. s.setError(fmt.Errorf("deleteStateObject (%x) error: %v", addr[:], err))
  443. }
  444. }
  445. // getStateObject retrieves a state object given by the address, returning nil if
  446. // the object is not found or was deleted in this execution context. If you need
  447. // to differentiate between non-existent/just-deleted, use getDeletedStateObject.
  448. func (s *StateDB) getStateObject(addr common.Address) *StateObject {
  449. if obj := s.getDeletedStateObject(addr); obj != nil && !obj.deleted {
  450. return obj
  451. }
  452. return nil
  453. }
  454. func (s *StateDB) TryPreload(block *types.Block, signer types.Signer) {
  455. accounts := make(map[common.Address]bool, block.Transactions().Len())
  456. accountsSlice := make([]common.Address, 0, block.Transactions().Len())
  457. for _, tx := range block.Transactions() {
  458. from, err := types.Sender(signer, tx)
  459. if err != nil {
  460. break
  461. }
  462. accounts[from] = true
  463. if tx.To() != nil {
  464. accounts[*tx.To()] = true
  465. }
  466. }
  467. for account, _ := range accounts {
  468. accountsSlice = append(accountsSlice, account)
  469. }
  470. if len(accountsSlice) >= preLoadLimit && len(accountsSlice) > runtime.NumCPU() {
  471. objsChan := make(chan []*StateObject, runtime.NumCPU())
  472. for i := 0; i < runtime.NumCPU(); i++ {
  473. start := i * len(accountsSlice) / runtime.NumCPU()
  474. end := (i + 1) * len(accountsSlice) / runtime.NumCPU()
  475. if i+1 == runtime.NumCPU() {
  476. end = len(accountsSlice)
  477. }
  478. go func(start, end int) {
  479. objs := s.preloadStateObject(accountsSlice[start:end])
  480. objsChan <- objs
  481. }(start, end)
  482. }
  483. for i := 0; i < runtime.NumCPU(); i++ {
  484. objs := <-objsChan
  485. if objs != nil {
  486. for _, obj := range objs {
  487. s.SetStateObject(obj)
  488. }
  489. }
  490. }
  491. }
  492. }
  493. func (s *StateDB) preloadStateObject(address []common.Address) []*StateObject {
  494. // Prefer live objects if any is available
  495. if s.snap == nil {
  496. return nil
  497. }
  498. hasher := crypto.NewKeccakState()
  499. objs := make([]*StateObject, 0, len(address))
  500. for _, addr := range address {
  501. // If no live objects are available, attempt to use snapshots
  502. if acc, err := s.snap.Account(crypto.HashData(hasher, addr.Bytes())); err == nil {
  503. if acc == nil {
  504. continue
  505. }
  506. data := &Account{
  507. Nonce: acc.Nonce,
  508. Balance: acc.Balance,
  509. CodeHash: acc.CodeHash,
  510. Root: common.BytesToHash(acc.Root),
  511. }
  512. if len(data.CodeHash) == 0 {
  513. data.CodeHash = emptyCodeHash
  514. }
  515. if data.Root == (common.Hash{}) {
  516. data.Root = emptyRoot
  517. }
  518. // Insert into the live set
  519. obj := newObject(s, addr, *data)
  520. objs = append(objs, obj)
  521. }
  522. // Do not enable this feature when snapshot is not enabled.
  523. }
  524. return objs
  525. }
  526. // getDeletedStateObject is similar to getStateObject, but instead of returning
  527. // nil for a deleted state object, it returns the actual object with the deleted
  528. // flag set. This is needed by the state journal to revert to the correct s-
  529. // destructed object instead of wiping all knowledge about the state object.
  530. func (s *StateDB) getDeletedStateObject(addr common.Address) *StateObject {
  531. // Prefer live objects if any is available
  532. if obj := s.stateObjects[addr]; obj != nil {
  533. return obj
  534. }
  535. // If no live objects are available, attempt to use snapshots
  536. var (
  537. data *Account
  538. err error
  539. )
  540. if s.snap != nil {
  541. if metrics.EnabledExpensive {
  542. defer func(start time.Time) { s.SnapshotAccountReads += time.Since(start) }(time.Now())
  543. }
  544. var acc *snapshot.Account
  545. if acc, err = s.snap.Account(crypto.HashData(s.hasher, addr.Bytes())); err == nil {
  546. if acc == nil {
  547. return nil
  548. }
  549. data = &Account{
  550. Nonce: acc.Nonce,
  551. Balance: acc.Balance,
  552. CodeHash: acc.CodeHash,
  553. Root: common.BytesToHash(acc.Root),
  554. }
  555. if len(data.CodeHash) == 0 {
  556. data.CodeHash = emptyCodeHash
  557. }
  558. if data.Root == (common.Hash{}) {
  559. data.Root = emptyRoot
  560. }
  561. }
  562. }
  563. // If snapshot unavailable or reading from it failed, load from the database
  564. if s.snap == nil || err != nil {
  565. if s.trie == nil {
  566. tr, err := s.db.OpenTrie(s.originalRoot)
  567. if err != nil {
  568. s.setError(fmt.Errorf("failed to open trie tree"))
  569. return nil
  570. }
  571. s.trie = tr
  572. }
  573. if metrics.EnabledExpensive {
  574. defer func(start time.Time) { s.AccountReads += time.Since(start) }(time.Now())
  575. }
  576. enc, err := s.trie.TryGet(addr.Bytes())
  577. if err != nil {
  578. s.setError(fmt.Errorf("getDeleteStateObject (%x) error: %v", addr.Bytes(), err))
  579. return nil
  580. }
  581. if len(enc) == 0 {
  582. return nil
  583. }
  584. data = new(Account)
  585. if err := rlp.DecodeBytes(enc, data); err != nil {
  586. log.Error("Failed to decode state object", "addr", addr, "err", err)
  587. return nil
  588. }
  589. }
  590. // Insert into the live set
  591. obj := newObject(s, addr, *data)
  592. s.SetStateObject(obj)
  593. return obj
  594. }
  595. func (s *StateDB) SetStateObject(object *StateObject) {
  596. s.stateObjects[object.Address()] = object
  597. }
  598. // GetOrNewStateObject retrieves a state object or create a new state object if nil.
  599. func (s *StateDB) GetOrNewStateObject(addr common.Address) *StateObject {
  600. stateObject := s.getStateObject(addr)
  601. if stateObject == nil {
  602. stateObject, _ = s.createObject(addr)
  603. }
  604. return stateObject
  605. }
  606. // createObject creates a new state object. If there is an existing account with
  607. // the given address, it is overwritten and returned as the second return value.
  608. func (s *StateDB) createObject(addr common.Address) (newobj, prev *StateObject) {
  609. prev = s.getDeletedStateObject(addr) // Note, prev might have been deleted, we need that!
  610. var prevdestruct bool
  611. if s.snap != nil && prev != nil {
  612. _, prevdestruct = s.snapDestructs[prev.addrHash]
  613. if !prevdestruct {
  614. s.snapDestructs[prev.addrHash] = struct{}{}
  615. }
  616. }
  617. newobj = newObject(s, addr, Account{})
  618. newobj.setNonce(0) // sets the object to dirty
  619. if prev == nil {
  620. s.journal.append(createObjectChange{account: &addr})
  621. } else {
  622. s.journal.append(resetObjectChange{prev: prev, prevdestruct: prevdestruct})
  623. }
  624. s.SetStateObject(newobj)
  625. if prev != nil && !prev.deleted {
  626. return newobj, prev
  627. }
  628. return newobj, nil
  629. }
  630. // CreateAccount explicitly creates a state object. If a state object with the address
  631. // already exists the balance is carried over to the new account.
  632. //
  633. // CreateAccount is called during the EVM CREATE operation. The situation might arise that
  634. // a contract does the following:
  635. //
  636. // 1. sends funds to sha(account ++ (nonce + 1))
  637. // 2. tx_create(sha(account ++ nonce)) (note that this gets the address of 1)
  638. //
  639. // Carrying over the balance ensures that Ether doesn't disappear.
  640. func (s *StateDB) CreateAccount(addr common.Address) {
  641. newObj, prev := s.createObject(addr)
  642. if prev != nil {
  643. newObj.setBalance(prev.data.Balance)
  644. }
  645. }
  646. func (db *StateDB) ForEachStorage(addr common.Address, cb func(key, value common.Hash) bool) error {
  647. so := db.getStateObject(addr)
  648. if so == nil {
  649. return nil
  650. }
  651. it := trie.NewIterator(so.getTrie(db.db).NodeIterator(nil))
  652. for it.Next() {
  653. key := common.BytesToHash(db.trie.GetKey(it.Key))
  654. if value, dirty := so.dirtyStorage[key]; dirty {
  655. if !cb(key, value) {
  656. return nil
  657. }
  658. continue
  659. }
  660. if len(it.Value) > 0 {
  661. _, content, _, err := rlp.Split(it.Value)
  662. if err != nil {
  663. return err
  664. }
  665. if !cb(key, common.BytesToHash(content)) {
  666. return nil
  667. }
  668. }
  669. }
  670. return nil
  671. }
  672. // Copy creates a deep, independent copy of the state.
  673. // Snapshots of the copied state cannot be applied to the copy.
  674. func (s *StateDB) Copy() *StateDB {
  675. // Copy all the basic fields, initialize the memory ones
  676. state := &StateDB{
  677. db: s.db,
  678. trie: s.db.CopyTrie(s.trie),
  679. stateObjects: make(map[common.Address]*StateObject, len(s.journal.dirties)),
  680. stateObjectsPending: make(map[common.Address]struct{}, len(s.stateObjectsPending)),
  681. stateObjectsDirty: make(map[common.Address]struct{}, len(s.journal.dirties)),
  682. refund: s.refund,
  683. logs: make(map[common.Hash][]*types.Log, len(s.logs)),
  684. logSize: s.logSize,
  685. preimages: make(map[common.Hash][]byte, len(s.preimages)),
  686. journal: newJournal(),
  687. hasher: crypto.NewKeccakState(),
  688. }
  689. // Copy the dirty states, logs, and preimages
  690. for addr := range s.journal.dirties {
  691. // As documented [here](https://github.com/ethereum/go-ethereum/pull/16485#issuecomment-380438527),
  692. // and in the Finalise-method, there is a case where an object is in the journal but not
  693. // in the stateObjects: OOG after touch on ripeMD prior to Byzantium. Thus, we need to check for
  694. // nil
  695. if object, exist := s.stateObjects[addr]; exist {
  696. // Even though the original object is dirty, we are not copying the journal,
  697. // so we need to make sure that anyside effect the journal would have caused
  698. // during a commit (or similar op) is already applied to the copy.
  699. state.stateObjects[addr] = object.deepCopy(state)
  700. state.stateObjectsDirty[addr] = struct{}{} // Mark the copy dirty to force internal (code/state) commits
  701. state.stateObjectsPending[addr] = struct{}{} // Mark the copy pending to force external (account) commits
  702. }
  703. }
  704. // Above, we don't copy the actual journal. This means that if the copy is copied, the
  705. // loop above will be a no-op, since the copy's journal is empty.
  706. // Thus, here we iterate over stateObjects, to enable copies of copies
  707. for addr := range s.stateObjectsPending {
  708. if _, exist := state.stateObjects[addr]; !exist {
  709. state.stateObjects[addr] = s.stateObjects[addr].deepCopy(state)
  710. }
  711. state.stateObjectsPending[addr] = struct{}{}
  712. }
  713. for addr := range s.stateObjectsDirty {
  714. if _, exist := state.stateObjects[addr]; !exist {
  715. state.stateObjects[addr] = s.stateObjects[addr].deepCopy(state)
  716. }
  717. state.stateObjectsDirty[addr] = struct{}{}
  718. }
  719. for hash, logs := range s.logs {
  720. cpy := make([]*types.Log, len(logs))
  721. for i, l := range logs {
  722. cpy[i] = new(types.Log)
  723. *cpy[i] = *l
  724. }
  725. state.logs[hash] = cpy
  726. }
  727. for hash, preimage := range s.preimages {
  728. state.preimages[hash] = preimage
  729. }
  730. // Do we need to copy the access list? In practice: No. At the start of a
  731. // transaction, the access list is empty. In practice, we only ever copy state
  732. // _between_ transactions/blocks, never in the middle of a transaction.
  733. // However, it doesn't cost us much to copy an empty list, so we do it anyway
  734. // to not blow up if we ever decide copy it in the middle of a transaction
  735. if s.accessList != nil {
  736. state.accessList = s.accessList.Copy()
  737. }
  738. // If there's a prefetcher running, make an inactive copy of it that can
  739. // only access data but does not actively preload (since the user will not
  740. // know that they need to explicitly terminate an active copy).
  741. if s.prefetcher != nil {
  742. state.prefetcher = s.prefetcher.copy()
  743. }
  744. if s.snaps != nil {
  745. // In order for the miner to be able to use and make additions
  746. // to the snapshot tree, we need to copy that aswell.
  747. // Otherwise, any block mined by ourselves will cause gaps in the tree,
  748. // and force the miner to operate trie-backed only
  749. state.snaps = s.snaps
  750. state.snap = s.snap
  751. // deep copy needed
  752. state.snapDestructs = make(map[common.Hash]struct{})
  753. for k, v := range s.snapDestructs {
  754. state.snapDestructs[k] = v
  755. }
  756. state.snapAccounts = make(map[common.Hash][]byte)
  757. for k, v := range s.snapAccounts {
  758. state.snapAccounts[k] = v
  759. }
  760. state.snapStorage = make(map[common.Hash]map[common.Hash][]byte)
  761. for k, v := range s.snapStorage {
  762. temp := make(map[common.Hash][]byte)
  763. for kk, vv := range v {
  764. temp[kk] = vv
  765. }
  766. state.snapStorage[k] = temp
  767. }
  768. }
  769. return state
  770. }
  771. // Snapshot returns an identifier for the current revision of the state.
  772. func (s *StateDB) Snapshot() int {
  773. id := s.nextRevisionId
  774. s.nextRevisionId++
  775. s.validRevisions = append(s.validRevisions, revision{id, s.journal.length()})
  776. return id
  777. }
  778. // RevertToSnapshot reverts all state changes made since the given revision.
  779. func (s *StateDB) RevertToSnapshot(revid int) {
  780. // Find the snapshot in the stack of valid snapshots.
  781. idx := sort.Search(len(s.validRevisions), func(i int) bool {
  782. return s.validRevisions[i].id >= revid
  783. })
  784. if idx == len(s.validRevisions) || s.validRevisions[idx].id != revid {
  785. panic(fmt.Errorf("revision id %v cannot be reverted", revid))
  786. }
  787. snapshot := s.validRevisions[idx].journalIndex
  788. // Replay the journal to undo changes and remove invalidated snapshots
  789. s.journal.revert(s, snapshot)
  790. s.validRevisions = s.validRevisions[:idx]
  791. }
  792. // GetRefund returns the current value of the refund counter.
  793. func (s *StateDB) GetRefund() uint64 {
  794. return s.refund
  795. }
  796. // Finalise finalises the state by removing the s destructed objects and clears
  797. // the journal as well as the refunds. Finalise, however, will not push any updates
  798. // into the tries just yet. Only IntermediateRoot or Commit will do that.
  799. func (s *StateDB) Finalise(deleteEmptyObjects bool) {
  800. addressesToPrefetch := make([][]byte, 0, len(s.journal.dirties))
  801. for addr := range s.journal.dirties {
  802. obj, exist := s.stateObjects[addr]
  803. if !exist {
  804. // ripeMD is 'touched' at block 1714175, in tx 0x1237f737031e40bcde4a8b7e717b2d15e3ecadfe49bb1bbc71ee9deb09c6fcf2
  805. // That tx goes out of gas, and although the notion of 'touched' does not exist there, the
  806. // touch-event will still be recorded in the journal. Since ripeMD is a special snowflake,
  807. // it will persist in the journal even though the journal is reverted. In this special circumstance,
  808. // it may exist in `s.journal.dirties` but not in `s.stateObjects`.
  809. // Thus, we can safely ignore it here
  810. continue
  811. }
  812. if obj.suicided || (deleteEmptyObjects && obj.empty()) {
  813. obj.deleted = true
  814. // If state snapshotting is active, also mark the destruction there.
  815. // Note, we can't do this only at the end of a block because multiple
  816. // transactions within the same block might self destruct and then
  817. // ressurrect an account; but the snapshotter needs both events.
  818. if s.snap != nil {
  819. s.snapDestructs[obj.addrHash] = struct{}{} // We need to maintain account deletions explicitly (will remain set indefinitely)
  820. delete(s.snapAccounts, obj.addrHash) // Clear out any previously updated account data (may be recreated via a ressurrect)
  821. delete(s.snapStorage, obj.addrHash) // Clear out any previously updated storage data (may be recreated via a ressurrect)
  822. }
  823. } else {
  824. obj.finalise(true) // Prefetch slots in the background
  825. }
  826. if _, exist := s.stateObjectsPending[addr]; !exist {
  827. s.stateObjectsPending[addr] = struct{}{}
  828. }
  829. if _, exist := s.stateObjectsDirty[addr]; !exist {
  830. s.stateObjectsDirty[addr] = struct{}{}
  831. // At this point, also ship the address off to the precacher. The precacher
  832. // will start loading tries, and when the change is eventually committed,
  833. // the commit-phase will be a lot faster
  834. addressesToPrefetch = append(addressesToPrefetch, common.CopyBytes(addr[:])) // Copy needed for closure
  835. }
  836. }
  837. if s.prefetcher != nil && len(addressesToPrefetch) > 0 {
  838. s.prefetcher.prefetch(s.originalRoot, addressesToPrefetch, emptyAddr)
  839. }
  840. // Invalidate journal because reverting across transactions is not allowed.
  841. s.clearJournalAndRefund()
  842. }
  843. // IntermediateRoot computes the current root hash of the state trie.
  844. // It is called in between transactions to get the root hash that
  845. // goes into transaction receipts.
  846. func (s *StateDB) IntermediateRoot(deleteEmptyObjects bool) common.Hash {
  847. // Finalise all the dirty storage states and write them into the tries
  848. s.Finalise(deleteEmptyObjects)
  849. // If there was a trie prefetcher operating, it gets aborted and irrevocably
  850. // modified after we start retrieving tries. Remove it from the statedb after
  851. // this round of use.
  852. //
  853. // This is weird pre-byzantium since the first tx runs with a prefetcher and
  854. // the remainder without, but pre-byzantium even the initial prefetcher is
  855. // useless, so no sleep lost.
  856. prefetcher := s.prefetcher
  857. if s.prefetcher != nil {
  858. defer func() {
  859. s.prefetcher.close()
  860. s.prefetcher = nil
  861. }()
  862. }
  863. tasks := make(chan func())
  864. finishCh := make(chan struct{})
  865. defer close(finishCh)
  866. wg := sync.WaitGroup{}
  867. for i := 0; i < runtime.NumCPU(); i++ {
  868. go func() {
  869. for {
  870. select {
  871. case task := <-tasks:
  872. task()
  873. case <-finishCh:
  874. return
  875. }
  876. }
  877. }()
  878. }
  879. // Although naively it makes sense to retrieve the account trie and then do
  880. // the contract storage and account updates sequentially, that short circuits
  881. // the account prefetcher. Instead, let's process all the storage updates
  882. // first, giving the account prefeches just a few more milliseconds of time
  883. // to pull useful data from disk.
  884. for addr := range s.stateObjectsPending {
  885. if obj := s.stateObjects[addr]; !obj.deleted {
  886. wg.Add(1)
  887. tasks <- func() {
  888. obj.updateRoot(s.db)
  889. // If state snapshotting is active, cache the data til commit. Note, this
  890. // update mechanism is not symmetric to the deletion, because whereas it is
  891. // enough to track account updates at commit time, deletions need tracking
  892. // at transaction boundary level to ensure we capture state clearing.
  893. if s.snap != nil && !obj.deleted {
  894. s.snapMux.Lock()
  895. s.snapAccounts[obj.addrHash] = snapshot.SlimAccountRLP(obj.data.Nonce, obj.data.Balance, obj.data.Root, obj.data.CodeHash)
  896. s.snapMux.Unlock()
  897. }
  898. data, err := rlp.EncodeToBytes(obj)
  899. if err != nil {
  900. panic(fmt.Errorf("can't encode object at %x: %v", addr[:], err))
  901. }
  902. obj.encodeData = data
  903. wg.Done()
  904. }
  905. }
  906. }
  907. wg.Wait()
  908. // Now we're about to start to write changes to the trie. The trie is so far
  909. // _untouched_. We can check with the prefetcher, if it can give us a trie
  910. // which has the same root, but also has some content loaded into it.
  911. if prefetcher != nil {
  912. if trie := prefetcher.trie(s.originalRoot); trie != nil {
  913. s.trie = trie
  914. }
  915. }
  916. if s.trie == nil {
  917. tr, err := s.db.OpenTrie(s.originalRoot)
  918. if err != nil {
  919. panic(fmt.Sprintf("Failed to open trie tree"))
  920. }
  921. s.trie = tr
  922. }
  923. usedAddrs := make([][]byte, 0, len(s.stateObjectsPending))
  924. for addr := range s.stateObjectsPending {
  925. if obj := s.stateObjects[addr]; obj.deleted {
  926. s.deleteStateObject(obj)
  927. } else {
  928. s.updateStateObject(obj)
  929. }
  930. usedAddrs = append(usedAddrs, common.CopyBytes(addr[:])) // Copy needed for closure
  931. }
  932. if prefetcher != nil {
  933. prefetcher.used(s.originalRoot, usedAddrs)
  934. }
  935. if len(s.stateObjectsPending) > 0 {
  936. s.stateObjectsPending = make(map[common.Address]struct{})
  937. }
  938. // Track the amount of time wasted on hashing the account trie
  939. if metrics.EnabledExpensive {
  940. defer func(start time.Time) { s.AccountHashes += time.Since(start) }(time.Now())
  941. }
  942. root := s.trie.Hash()
  943. return root
  944. }
  945. // Prepare sets the current transaction hash and index and block hash which is
  946. // used when the EVM emits new state logs.
  947. func (s *StateDB) Prepare(thash, bhash common.Hash, ti int) {
  948. s.thash = thash
  949. s.bhash = bhash
  950. s.txIndex = ti
  951. s.accessList = nil
  952. }
  953. func (s *StateDB) clearJournalAndRefund() {
  954. if len(s.journal.entries) > 0 {
  955. s.journal = newJournal()
  956. s.refund = 0
  957. }
  958. s.validRevisions = s.validRevisions[:0] // Snapshots can be created without journal entires
  959. }
  960. // Commit writes the state to the underlying in-memory trie database.
  961. func (s *StateDB) Commit(deleteEmptyObjects bool) (common.Hash, error) {
  962. if s.dbErr != nil {
  963. return common.Hash{}, fmt.Errorf("commit aborted due to earlier error: %v", s.dbErr)
  964. }
  965. // Finalize any pending changes and merge everything into the tries
  966. root := s.IntermediateRoot(deleteEmptyObjects)
  967. commitFuncs := []func() error{
  968. func() error {
  969. // Commit objects to the trie, measuring the elapsed time
  970. tasks := make(chan func(batch ethdb.KeyValueWriter))
  971. taskResults := make(chan error, len(s.stateObjectsDirty))
  972. tasksNum := 0
  973. finishCh := make(chan struct{})
  974. defer close(finishCh)
  975. for i := 0; i < runtime.NumCPU(); i++ {
  976. go func() {
  977. codeWriter := s.db.TrieDB().DiskDB().NewBatch()
  978. for {
  979. select {
  980. case task := <-tasks:
  981. task(codeWriter)
  982. case <-finishCh:
  983. if codeWriter.ValueSize() > 0 {
  984. if err := codeWriter.Write(); err != nil {
  985. log.Crit("Failed to commit dirty codes", "error", err)
  986. }
  987. }
  988. return
  989. }
  990. }
  991. }()
  992. }
  993. for addr := range s.stateObjectsDirty {
  994. if obj := s.stateObjects[addr]; !obj.deleted {
  995. // Write any contract code associated with the state object
  996. tasks <- func(codeWriter ethdb.KeyValueWriter) {
  997. if obj.code != nil && obj.dirtyCode {
  998. rawdb.WriteCode(codeWriter, common.BytesToHash(obj.CodeHash()), obj.code)
  999. obj.dirtyCode = false
  1000. }
  1001. // Write any storage changes in the state object to its storage trie
  1002. if err := obj.CommitTrie(s.db); err != nil {
  1003. taskResults <- err
  1004. }
  1005. taskResults <- nil
  1006. }
  1007. tasksNum++
  1008. }
  1009. }
  1010. for i := 0; i < tasksNum; i++ {
  1011. err := <-taskResults
  1012. if err != nil {
  1013. return err
  1014. }
  1015. }
  1016. if len(s.stateObjectsDirty) > 0 {
  1017. s.stateObjectsDirty = make(map[common.Address]struct{}, len(s.stateObjectsDirty)/2)
  1018. }
  1019. // Write the account trie changes, measuing the amount of wasted time
  1020. var start time.Time
  1021. if metrics.EnabledExpensive {
  1022. start = time.Now()
  1023. }
  1024. // The onleaf func is called _serially_, so we can reuse the same account
  1025. // for unmarshalling every time.
  1026. var account Account
  1027. root, err := s.trie.Commit(func(_ [][]byte, _ []byte, leaf []byte, parent common.Hash) error {
  1028. if err := rlp.DecodeBytes(leaf, &account); err != nil {
  1029. return nil
  1030. }
  1031. if account.Root != emptyRoot {
  1032. s.db.TrieDB().Reference(account.Root, parent)
  1033. }
  1034. return nil
  1035. })
  1036. if err != nil {
  1037. return err
  1038. }
  1039. if metrics.EnabledExpensive {
  1040. s.AccountCommits += time.Since(start)
  1041. }
  1042. if root != emptyRoot {
  1043. s.db.CacheAccount(root, s.trie)
  1044. }
  1045. return nil
  1046. },
  1047. func() error {
  1048. // If snapshotting is enabled, update the snapshot tree with this new version
  1049. if s.snap != nil {
  1050. if metrics.EnabledExpensive {
  1051. defer func(start time.Time) { s.SnapshotCommits += time.Since(start) }(time.Now())
  1052. }
  1053. // Only update if there's a state transition (skip empty Clique blocks)
  1054. if parent := s.snap.Root(); parent != root {
  1055. if err := s.snaps.Update(root, parent, s.snapDestructs, s.snapAccounts, s.snapStorage); err != nil {
  1056. log.Warn("Failed to update snapshot tree", "from", parent, "to", root, "err", err)
  1057. }
  1058. // Keep n diff layers in the memory
  1059. // - head layer is paired with HEAD state
  1060. // - head-1 layer is paired with HEAD-1 state
  1061. // - head-(n-1) layer(bottom-most diff layer) is paired with HEAD-(n-1)state
  1062. if err := s.snaps.Cap(root, s.snaps.CapLimit()); err != nil {
  1063. log.Warn("Failed to cap snapshot tree", "root", root, "layers", s.snaps.CapLimit(), "err", err)
  1064. }
  1065. }
  1066. s.snap, s.snapDestructs, s.snapAccounts, s.snapStorage = nil, nil, nil, nil
  1067. }
  1068. return nil
  1069. },
  1070. }
  1071. commitRes := make(chan error, len(commitFuncs))
  1072. for _, f := range commitFuncs {
  1073. tmpFunc := f
  1074. go func() {
  1075. commitRes <- tmpFunc()
  1076. }()
  1077. }
  1078. for i := 0; i < len(commitFuncs); i++ {
  1079. r := <-commitRes
  1080. if r != nil {
  1081. return common.Hash{}, r
  1082. }
  1083. }
  1084. return root, nil
  1085. }
  1086. // PrepareAccessList handles the preparatory steps for executing a state transition with
  1087. // regards to both EIP-2929 and EIP-2930:
  1088. //
  1089. // - Add sender to access list (2929)
  1090. // - Add destination to access list (2929)
  1091. // - Add precompiles to access list (2929)
  1092. // - Add the contents of the optional tx access list (2930)
  1093. //
  1094. // This method should only be called if Yolov3/Berlin/2929+2930 is applicable at the current number.
  1095. func (s *StateDB) PrepareAccessList(sender common.Address, dst *common.Address, precompiles []common.Address, list types.AccessList) {
  1096. s.AddAddressToAccessList(sender)
  1097. if dst != nil {
  1098. s.AddAddressToAccessList(*dst)
  1099. // If it's a create-tx, the destination will be added inside evm.create
  1100. }
  1101. for _, addr := range precompiles {
  1102. s.AddAddressToAccessList(addr)
  1103. }
  1104. for _, el := range list {
  1105. s.AddAddressToAccessList(el.Address)
  1106. for _, key := range el.StorageKeys {
  1107. s.AddSlotToAccessList(el.Address, key)
  1108. }
  1109. }
  1110. }
  1111. // AddAddressToAccessList adds the given address to the access list
  1112. func (s *StateDB) AddAddressToAccessList(addr common.Address) {
  1113. if s.accessList == nil {
  1114. s.accessList = newAccessList()
  1115. }
  1116. if s.accessList.AddAddress(addr) {
  1117. s.journal.append(accessListAddAccountChange{&addr})
  1118. }
  1119. }
  1120. // AddSlotToAccessList adds the given (address, slot)-tuple to the access list
  1121. func (s *StateDB) AddSlotToAccessList(addr common.Address, slot common.Hash) {
  1122. if s.accessList == nil {
  1123. s.accessList = newAccessList()
  1124. }
  1125. addrMod, slotMod := s.accessList.AddSlot(addr, slot)
  1126. if addrMod {
  1127. // In practice, this should not happen, since there is no way to enter the
  1128. // scope of 'address' without having the 'address' become already added
  1129. // to the access list (via call-variant, create, etc).
  1130. // Better safe than sorry, though
  1131. s.journal.append(accessListAddAccountChange{&addr})
  1132. }
  1133. if slotMod {
  1134. s.journal.append(accessListAddSlotChange{
  1135. address: &addr,
  1136. slot: &slot,
  1137. })
  1138. }
  1139. }
  1140. // AddressInAccessList returns true if the given address is in the access list.
  1141. func (s *StateDB) AddressInAccessList(addr common.Address) bool {
  1142. if s.accessList == nil {
  1143. return false
  1144. }
  1145. return s.accessList.ContainsAddress(addr)
  1146. }
  1147. // SlotInAccessList returns true if the given (address, slot)-tuple is in the access list.
  1148. func (s *StateDB) SlotInAccessList(addr common.Address, slot common.Hash) (addressPresent bool, slotPresent bool) {
  1149. if s.accessList == nil {
  1150. return false, false
  1151. }
  1152. return s.accessList.Contains(addr, slot)
  1153. }