statedb.go 18 KB

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