statedb.go 19 KB

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