statedb.go 30 KB

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