statedb.go 18 KB

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