statedb.go 19 KB

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