statedb.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629
  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. "fmt"
  20. "math/big"
  21. "sort"
  22. "sync"
  23. "github.com/ethereum/go-ethereum/common"
  24. "github.com/ethereum/go-ethereum/core/types"
  25. "github.com/ethereum/go-ethereum/crypto"
  26. "github.com/ethereum/go-ethereum/log"
  27. "github.com/ethereum/go-ethereum/rlp"
  28. "github.com/ethereum/go-ethereum/trie"
  29. )
  30. type revision struct {
  31. id int
  32. journalIndex int
  33. }
  34. var (
  35. // emptyState is the known hash of an empty state trie entry.
  36. emptyState = crypto.Keccak256Hash(nil)
  37. // emptyCode is the known hash of the empty EVM bytecode.
  38. emptyCode = crypto.Keccak256Hash(nil)
  39. )
  40. // StateDBs within the ethereum protocol are used to store anything
  41. // within the merkle trie. StateDBs take care of caching and storing
  42. // nested states. It's the general query interface to retrieve:
  43. // * Contracts
  44. // * Accounts
  45. type StateDB struct {
  46. db Database
  47. trie Trie
  48. // This map holds 'live' objects, which will get modified while processing a state transition.
  49. stateObjects map[common.Address]*stateObject
  50. stateObjectsDirty map[common.Address]struct{}
  51. // DB error.
  52. // State objects are used by the consensus core and VM which are
  53. // unable to deal with database-level errors. Any error that occurs
  54. // during a database read is memoized here and will eventually be returned
  55. // by StateDB.Commit.
  56. dbErr error
  57. // The refund counter, also used by state transitioning.
  58. refund uint64
  59. thash, bhash common.Hash
  60. txIndex int
  61. logs map[common.Hash][]*types.Log
  62. logSize uint
  63. preimages map[common.Hash][]byte
  64. // Journal of state modifications. This is the backbone of
  65. // Snapshot and RevertToSnapshot.
  66. journal *journal
  67. validRevisions []revision
  68. nextRevisionId int
  69. lock sync.Mutex
  70. }
  71. // Create a new state from a given trie.
  72. func New(root common.Hash, db Database) (*StateDB, error) {
  73. tr, err := db.OpenTrie(root)
  74. if err != nil {
  75. return nil, err
  76. }
  77. return &StateDB{
  78. db: db,
  79. trie: tr,
  80. stateObjects: make(map[common.Address]*stateObject),
  81. stateObjectsDirty: make(map[common.Address]struct{}),
  82. logs: make(map[common.Hash][]*types.Log),
  83. preimages: make(map[common.Hash][]byte),
  84. journal: newJournal(),
  85. }, nil
  86. }
  87. // setError remembers the first non-nil error it is called with.
  88. func (self *StateDB) setError(err error) {
  89. if self.dbErr == nil {
  90. self.dbErr = err
  91. }
  92. }
  93. func (self *StateDB) Error() error {
  94. return self.dbErr
  95. }
  96. // Reset clears out all ephemeral state objects from the state db, but keeps
  97. // the underlying state trie to avoid reloading data for the next operations.
  98. func (self *StateDB) Reset(root common.Hash) error {
  99. tr, err := self.db.OpenTrie(root)
  100. if err != nil {
  101. return err
  102. }
  103. self.trie = tr
  104. self.stateObjects = make(map[common.Address]*stateObject)
  105. self.stateObjectsDirty = make(map[common.Address]struct{})
  106. self.thash = common.Hash{}
  107. self.bhash = common.Hash{}
  108. self.txIndex = 0
  109. self.logs = make(map[common.Hash][]*types.Log)
  110. self.logSize = 0
  111. self.preimages = make(map[common.Hash][]byte)
  112. self.clearJournalAndRefund()
  113. return nil
  114. }
  115. func (self *StateDB) AddLog(log *types.Log) {
  116. self.journal.append(addLogChange{txhash: self.thash})
  117. log.TxHash = self.thash
  118. log.BlockHash = self.bhash
  119. log.TxIndex = uint(self.txIndex)
  120. log.Index = self.logSize
  121. self.logs[self.thash] = append(self.logs[self.thash], log)
  122. self.logSize++
  123. }
  124. func (self *StateDB) GetLogs(hash common.Hash) []*types.Log {
  125. return self.logs[hash]
  126. }
  127. func (self *StateDB) Logs() []*types.Log {
  128. var logs []*types.Log
  129. for _, lgs := range self.logs {
  130. logs = append(logs, lgs...)
  131. }
  132. return logs
  133. }
  134. // AddPreimage records a SHA3 preimage seen by the VM.
  135. func (self *StateDB) AddPreimage(hash common.Hash, preimage []byte) {
  136. if _, ok := self.preimages[hash]; !ok {
  137. self.journal.append(addPreimageChange{hash: hash})
  138. pi := make([]byte, len(preimage))
  139. copy(pi, preimage)
  140. self.preimages[hash] = pi
  141. }
  142. }
  143. // Preimages returns a list of SHA3 preimages that have been submitted.
  144. func (self *StateDB) Preimages() map[common.Hash][]byte {
  145. return self.preimages
  146. }
  147. func (self *StateDB) AddRefund(gas uint64) {
  148. self.journal.append(refundChange{prev: self.refund})
  149. self.refund += gas
  150. }
  151. // Exist reports whether the given account address exists in the state.
  152. // Notably this also returns true for suicided accounts.
  153. func (self *StateDB) Exist(addr common.Address) bool {
  154. return self.getStateObject(addr) != nil
  155. }
  156. // Empty returns whether the state object is either non-existent
  157. // or empty according to the EIP161 specification (balance = nonce = code = 0)
  158. func (self *StateDB) Empty(addr common.Address) bool {
  159. so := self.getStateObject(addr)
  160. return so == nil || so.empty()
  161. }
  162. // Retrieve the balance from the given address or 0 if object not found
  163. func (self *StateDB) GetBalance(addr common.Address) *big.Int {
  164. stateObject := self.getStateObject(addr)
  165. if stateObject != nil {
  166. return stateObject.Balance()
  167. }
  168. return common.Big0
  169. }
  170. func (self *StateDB) GetNonce(addr common.Address) uint64 {
  171. stateObject := self.getStateObject(addr)
  172. if stateObject != nil {
  173. return stateObject.Nonce()
  174. }
  175. return 0
  176. }
  177. func (self *StateDB) GetCode(addr common.Address) []byte {
  178. stateObject := self.getStateObject(addr)
  179. if stateObject != nil {
  180. return stateObject.Code(self.db)
  181. }
  182. return nil
  183. }
  184. func (self *StateDB) GetCodeSize(addr common.Address) int {
  185. stateObject := self.getStateObject(addr)
  186. if stateObject == nil {
  187. return 0
  188. }
  189. if stateObject.code != nil {
  190. return len(stateObject.code)
  191. }
  192. size, err := self.db.ContractCodeSize(stateObject.addrHash, common.BytesToHash(stateObject.CodeHash()))
  193. if err != nil {
  194. self.setError(err)
  195. }
  196. return size
  197. }
  198. func (self *StateDB) GetCodeHash(addr common.Address) common.Hash {
  199. stateObject := self.getStateObject(addr)
  200. if stateObject == nil {
  201. return common.Hash{}
  202. }
  203. return common.BytesToHash(stateObject.CodeHash())
  204. }
  205. func (self *StateDB) GetState(addr common.Address, bhash common.Hash) common.Hash {
  206. stateObject := self.getStateObject(addr)
  207. if stateObject != nil {
  208. return stateObject.GetState(self.db, bhash)
  209. }
  210. return common.Hash{}
  211. }
  212. // Database retrieves the low level database supporting the lower level trie ops.
  213. func (self *StateDB) Database() Database {
  214. return self.db
  215. }
  216. // StorageTrie returns the storage trie of an account.
  217. // The return value is a copy and is nil for non-existent accounts.
  218. func (self *StateDB) StorageTrie(addr common.Address) Trie {
  219. stateObject := self.getStateObject(addr)
  220. if stateObject == nil {
  221. return nil
  222. }
  223. cpy := stateObject.deepCopy(self)
  224. return cpy.updateTrie(self.db)
  225. }
  226. func (self *StateDB) HasSuicided(addr common.Address) bool {
  227. stateObject := self.getStateObject(addr)
  228. if stateObject != nil {
  229. return stateObject.suicided
  230. }
  231. return false
  232. }
  233. /*
  234. * SETTERS
  235. */
  236. // AddBalance adds amount to the account associated with addr.
  237. func (self *StateDB) AddBalance(addr common.Address, amount *big.Int) {
  238. stateObject := self.GetOrNewStateObject(addr)
  239. if stateObject != nil {
  240. stateObject.AddBalance(amount)
  241. }
  242. }
  243. // SubBalance subtracts amount from the account associated with addr.
  244. func (self *StateDB) SubBalance(addr common.Address, amount *big.Int) {
  245. stateObject := self.GetOrNewStateObject(addr)
  246. if stateObject != nil {
  247. stateObject.SubBalance(amount)
  248. }
  249. }
  250. func (self *StateDB) SetBalance(addr common.Address, amount *big.Int) {
  251. stateObject := self.GetOrNewStateObject(addr)
  252. if stateObject != nil {
  253. stateObject.SetBalance(amount)
  254. }
  255. }
  256. func (self *StateDB) SetNonce(addr common.Address, nonce uint64) {
  257. stateObject := self.GetOrNewStateObject(addr)
  258. if stateObject != nil {
  259. stateObject.SetNonce(nonce)
  260. }
  261. }
  262. func (self *StateDB) SetCode(addr common.Address, code []byte) {
  263. stateObject := self.GetOrNewStateObject(addr)
  264. if stateObject != nil {
  265. stateObject.SetCode(crypto.Keccak256Hash(code), code)
  266. }
  267. }
  268. func (self *StateDB) SetState(addr common.Address, key, value common.Hash) {
  269. stateObject := self.GetOrNewStateObject(addr)
  270. if stateObject != nil {
  271. stateObject.SetState(self.db, key, value)
  272. }
  273. }
  274. // Suicide marks the given account as suicided.
  275. // This clears the account balance.
  276. //
  277. // The account's state object is still available until the state is committed,
  278. // getStateObject will return a non-nil account after Suicide.
  279. func (self *StateDB) Suicide(addr common.Address) bool {
  280. stateObject := self.getStateObject(addr)
  281. if stateObject == nil {
  282. return false
  283. }
  284. self.journal.append(suicideChange{
  285. account: &addr,
  286. prev: stateObject.suicided,
  287. prevbalance: new(big.Int).Set(stateObject.Balance()),
  288. })
  289. stateObject.markSuicided()
  290. stateObject.data.Balance = new(big.Int)
  291. return true
  292. }
  293. //
  294. // Setting, updating & deleting state object methods.
  295. //
  296. // updateStateObject writes the given object to the trie.
  297. func (self *StateDB) updateStateObject(stateObject *stateObject) {
  298. addr := stateObject.Address()
  299. data, err := rlp.EncodeToBytes(stateObject)
  300. if err != nil {
  301. panic(fmt.Errorf("can't encode object at %x: %v", addr[:], err))
  302. }
  303. self.setError(self.trie.TryUpdate(addr[:], data))
  304. }
  305. // deleteStateObject removes the given object from the state trie.
  306. func (self *StateDB) deleteStateObject(stateObject *stateObject) {
  307. stateObject.deleted = true
  308. addr := stateObject.Address()
  309. self.setError(self.trie.TryDelete(addr[:]))
  310. }
  311. // Retrieve a state object given by the address. Returns nil if not found.
  312. func (self *StateDB) getStateObject(addr common.Address) (stateObject *stateObject) {
  313. // Prefer 'live' objects.
  314. if obj := self.stateObjects[addr]; obj != nil {
  315. if obj.deleted {
  316. return nil
  317. }
  318. return obj
  319. }
  320. // Load the object from the database.
  321. enc, err := self.trie.TryGet(addr[:])
  322. if len(enc) == 0 {
  323. self.setError(err)
  324. return nil
  325. }
  326. var data Account
  327. if err := rlp.DecodeBytes(enc, &data); err != nil {
  328. log.Error("Failed to decode state object", "addr", addr, "err", err)
  329. return nil
  330. }
  331. // Insert into the live set.
  332. obj := newObject(self, addr, data)
  333. self.setStateObject(obj)
  334. return obj
  335. }
  336. func (self *StateDB) setStateObject(object *stateObject) {
  337. self.stateObjects[object.Address()] = object
  338. }
  339. // Retrieve a state object or create a new state object if nil.
  340. func (self *StateDB) GetOrNewStateObject(addr common.Address) *stateObject {
  341. stateObject := self.getStateObject(addr)
  342. if stateObject == nil || stateObject.deleted {
  343. stateObject, _ = self.createObject(addr)
  344. }
  345. return stateObject
  346. }
  347. // createObject creates a new state object. If there is an existing account with
  348. // the given address, it is overwritten and returned as the second return value.
  349. func (self *StateDB) createObject(addr common.Address) (newobj, prev *stateObject) {
  350. prev = self.getStateObject(addr)
  351. newobj = newObject(self, addr, Account{})
  352. newobj.setNonce(0) // sets the object to dirty
  353. if prev == nil {
  354. self.journal.append(createObjectChange{account: &addr})
  355. } else {
  356. self.journal.append(resetObjectChange{prev: prev})
  357. }
  358. self.setStateObject(newobj)
  359. return newobj, prev
  360. }
  361. // CreateAccount explicitly creates a state object. If a state object with the address
  362. // already exists the balance is carried over to the new account.
  363. //
  364. // CreateAccount is called during the EVM CREATE operation. The situation might arise that
  365. // a contract does the following:
  366. //
  367. // 1. sends funds to sha(account ++ (nonce + 1))
  368. // 2. tx_create(sha(account ++ nonce)) (note that this gets the address of 1)
  369. //
  370. // Carrying over the balance ensures that Ether doesn't disappear.
  371. func (self *StateDB) CreateAccount(addr common.Address) {
  372. new, prev := self.createObject(addr)
  373. if prev != nil {
  374. new.setBalance(prev.data.Balance)
  375. }
  376. }
  377. func (db *StateDB) ForEachStorage(addr common.Address, cb func(key, value common.Hash) bool) {
  378. so := db.getStateObject(addr)
  379. if so == nil {
  380. return
  381. }
  382. // When iterating over the storage check the cache first
  383. for h, value := range so.cachedStorage {
  384. cb(h, value)
  385. }
  386. it := trie.NewIterator(so.getTrie(db.db).NodeIterator(nil))
  387. for it.Next() {
  388. // ignore cached values
  389. key := common.BytesToHash(db.trie.GetKey(it.Key))
  390. if _, ok := so.cachedStorage[key]; !ok {
  391. cb(key, common.BytesToHash(it.Value))
  392. }
  393. }
  394. }
  395. // Copy creates a deep, independent copy of the state.
  396. // Snapshots of the copied state cannot be applied to the copy.
  397. func (self *StateDB) Copy() *StateDB {
  398. self.lock.Lock()
  399. defer self.lock.Unlock()
  400. // Copy all the basic fields, initialize the memory ones
  401. state := &StateDB{
  402. db: self.db,
  403. trie: self.db.CopyTrie(self.trie),
  404. stateObjects: make(map[common.Address]*stateObject, len(self.journal.dirties)),
  405. stateObjectsDirty: make(map[common.Address]struct{}, len(self.journal.dirties)),
  406. refund: self.refund,
  407. logs: make(map[common.Hash][]*types.Log, len(self.logs)),
  408. logSize: self.logSize,
  409. preimages: make(map[common.Hash][]byte),
  410. journal: newJournal(),
  411. }
  412. // Copy the dirty states, logs, and preimages
  413. for addr := range self.journal.dirties {
  414. // As documented [here](https://github.com/ethereum/go-ethereum/pull/16485#issuecomment-380438527),
  415. // and in the Finalise-method, there is a case where an object is in the journal but not
  416. // in the stateObjects: OOG after touch on ripeMD prior to Byzantium. Thus, we need to check for
  417. // nil
  418. if object, exist := self.stateObjects[addr]; exist {
  419. state.stateObjects[addr] = object.deepCopy(state)
  420. state.stateObjectsDirty[addr] = struct{}{}
  421. }
  422. }
  423. // Above, we don't copy the actual journal. This means that if the copy is copied, the
  424. // loop above will be a no-op, since the copy's journal is empty.
  425. // Thus, here we iterate over stateObjects, to enable copies of copies
  426. for addr := range self.stateObjectsDirty {
  427. if _, exist := state.stateObjects[addr]; !exist {
  428. state.stateObjects[addr] = self.stateObjects[addr].deepCopy(state)
  429. state.stateObjectsDirty[addr] = struct{}{}
  430. }
  431. }
  432. for hash, logs := range self.logs {
  433. state.logs[hash] = make([]*types.Log, len(logs))
  434. copy(state.logs[hash], logs)
  435. }
  436. for hash, preimage := range self.preimages {
  437. state.preimages[hash] = preimage
  438. }
  439. return state
  440. }
  441. // Snapshot returns an identifier for the current revision of the state.
  442. func (self *StateDB) Snapshot() int {
  443. id := self.nextRevisionId
  444. self.nextRevisionId++
  445. self.validRevisions = append(self.validRevisions, revision{id, self.journal.length()})
  446. return id
  447. }
  448. // RevertToSnapshot reverts all state changes made since the given revision.
  449. func (self *StateDB) RevertToSnapshot(revid int) {
  450. // Find the snapshot in the stack of valid snapshots.
  451. idx := sort.Search(len(self.validRevisions), func(i int) bool {
  452. return self.validRevisions[i].id >= revid
  453. })
  454. if idx == len(self.validRevisions) || self.validRevisions[idx].id != revid {
  455. panic(fmt.Errorf("revision id %v cannot be reverted", revid))
  456. }
  457. snapshot := self.validRevisions[idx].journalIndex
  458. // Replay the journal to undo changes and remove invalidated snapshots
  459. self.journal.revert(self, snapshot)
  460. self.validRevisions = self.validRevisions[:idx]
  461. }
  462. // GetRefund returns the current value of the refund counter.
  463. func (self *StateDB) GetRefund() uint64 {
  464. return self.refund
  465. }
  466. // Finalise finalises the state by removing the self destructed objects
  467. // and clears the journal as well as the refunds.
  468. func (s *StateDB) Finalise(deleteEmptyObjects bool) {
  469. for addr := range s.journal.dirties {
  470. stateObject, exist := s.stateObjects[addr]
  471. if !exist {
  472. // ripeMD is 'touched' at block 1714175, in tx 0x1237f737031e40bcde4a8b7e717b2d15e3ecadfe49bb1bbc71ee9deb09c6fcf2
  473. // That tx goes out of gas, and although the notion of 'touched' does not exist there, the
  474. // touch-event will still be recorded in the journal. Since ripeMD is a special snowflake,
  475. // it will persist in the journal even though the journal is reverted. In this special circumstance,
  476. // it may exist in `s.journal.dirties` but not in `s.stateObjects`.
  477. // Thus, we can safely ignore it here
  478. continue
  479. }
  480. if stateObject.suicided || (deleteEmptyObjects && stateObject.empty()) {
  481. s.deleteStateObject(stateObject)
  482. } else {
  483. stateObject.updateRoot(s.db)
  484. s.updateStateObject(stateObject)
  485. }
  486. s.stateObjectsDirty[addr] = struct{}{}
  487. }
  488. // Invalidate journal because reverting across transactions is not allowed.
  489. s.clearJournalAndRefund()
  490. }
  491. // IntermediateRoot computes the current root hash of the state trie.
  492. // It is called in between transactions to get the root hash that
  493. // goes into transaction receipts.
  494. func (s *StateDB) IntermediateRoot(deleteEmptyObjects bool) common.Hash {
  495. s.Finalise(deleteEmptyObjects)
  496. return s.trie.Hash()
  497. }
  498. // Prepare sets the current transaction hash and index and block hash which is
  499. // used when the EVM emits new state logs.
  500. func (self *StateDB) Prepare(thash, bhash common.Hash, ti int) {
  501. self.thash = thash
  502. self.bhash = bhash
  503. self.txIndex = ti
  504. }
  505. func (s *StateDB) clearJournalAndRefund() {
  506. s.journal = newJournal()
  507. s.validRevisions = s.validRevisions[:0]
  508. s.refund = 0
  509. }
  510. // Commit writes the state to the underlying in-memory trie database.
  511. func (s *StateDB) Commit(deleteEmptyObjects bool) (root common.Hash, err error) {
  512. defer s.clearJournalAndRefund()
  513. for addr := range s.journal.dirties {
  514. s.stateObjectsDirty[addr] = struct{}{}
  515. }
  516. // Commit objects to the trie.
  517. for addr, stateObject := range s.stateObjects {
  518. _, isDirty := s.stateObjectsDirty[addr]
  519. switch {
  520. case stateObject.suicided || (isDirty && deleteEmptyObjects && stateObject.empty()):
  521. // If the object has been removed, don't bother syncing it
  522. // and just mark it for deletion in the trie.
  523. s.deleteStateObject(stateObject)
  524. case isDirty:
  525. // Write any contract code associated with the state object
  526. if stateObject.code != nil && stateObject.dirtyCode {
  527. s.db.TrieDB().Insert(common.BytesToHash(stateObject.CodeHash()), stateObject.code)
  528. stateObject.dirtyCode = false
  529. }
  530. // Write any storage changes in the state object to its storage trie.
  531. if err := stateObject.CommitTrie(s.db); err != nil {
  532. return common.Hash{}, err
  533. }
  534. // Update the object in the main account trie.
  535. s.updateStateObject(stateObject)
  536. }
  537. delete(s.stateObjectsDirty, addr)
  538. }
  539. // Write trie changes.
  540. root, err = s.trie.Commit(func(leaf []byte, parent common.Hash) error {
  541. var account Account
  542. if err := rlp.DecodeBytes(leaf, &account); err != nil {
  543. return nil
  544. }
  545. if account.Root != emptyState {
  546. s.db.TrieDB().Reference(account.Root, parent)
  547. }
  548. code := common.BytesToHash(account.CodeHash)
  549. if code != emptyCode {
  550. s.db.TrieDB().Reference(code, parent)
  551. }
  552. return nil
  553. })
  554. log.Debug("Trie cache stats after commit", "misses", trie.CacheMisses(), "unloads", trie.CacheUnloads())
  555. return root, err
  556. }