statedb.go 19 KB

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