statedb.go 18 KB

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