statedb.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605
  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. maxTrieCacheLength = 8
  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]vm.Logs
  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)
  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]vm.Logs),
  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]vm.Logs),
  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]vm.Logs)
  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)
  139. }
  140. func (self *StateDB) pushTrie(t *trie.SecureTrie) {
  141. self.lock.Lock()
  142. defer self.lock.Unlock()
  143. if len(self.pastTries) >= maxTrieCacheLength {
  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 *vm.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) vm.Logs {
  165. return self.logs[hash]
  166. }
  167. func (self *StateDB) Logs() vm.Logs {
  168. var logs vm.Logs
  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. func (self *StateDB) GetAccount(addr common.Address) vm.Account {
  184. return self.GetStateObject(addr)
  185. }
  186. // Retrieve the balance from the given address or 0 if object not found
  187. func (self *StateDB) GetBalance(addr common.Address) *big.Int {
  188. stateObject := self.GetStateObject(addr)
  189. if stateObject != nil {
  190. return stateObject.Balance()
  191. }
  192. return common.Big0
  193. }
  194. func (self *StateDB) GetNonce(addr common.Address) uint64 {
  195. stateObject := self.GetStateObject(addr)
  196. if stateObject != nil {
  197. return stateObject.Nonce()
  198. }
  199. return StartingNonce
  200. }
  201. func (self *StateDB) GetCode(addr common.Address) []byte {
  202. stateObject := self.GetStateObject(addr)
  203. if stateObject != nil {
  204. code := stateObject.Code(self.db)
  205. key := common.BytesToHash(stateObject.CodeHash())
  206. self.codeSizeCache.Add(key, len(code))
  207. return code
  208. }
  209. return nil
  210. }
  211. func (self *StateDB) GetCodeSize(addr common.Address) int {
  212. stateObject := self.GetStateObject(addr)
  213. if stateObject == nil {
  214. return 0
  215. }
  216. key := common.BytesToHash(stateObject.CodeHash())
  217. if cached, ok := self.codeSizeCache.Get(key); ok {
  218. return cached.(int)
  219. }
  220. size := len(stateObject.Code(self.db))
  221. if stateObject.dbErr == nil {
  222. self.codeSizeCache.Add(key, size)
  223. }
  224. return size
  225. }
  226. func (self *StateDB) GetCodeHash(addr common.Address) common.Hash {
  227. stateObject := self.GetStateObject(addr)
  228. if stateObject == nil {
  229. return common.Hash{}
  230. }
  231. return common.BytesToHash(stateObject.CodeHash())
  232. }
  233. func (self *StateDB) GetState(a common.Address, b common.Hash) common.Hash {
  234. stateObject := self.GetStateObject(a)
  235. if stateObject != nil {
  236. return stateObject.GetState(self.db, b)
  237. }
  238. return common.Hash{}
  239. }
  240. func (self *StateDB) IsDeleted(addr common.Address) bool {
  241. stateObject := self.GetStateObject(addr)
  242. if stateObject != nil {
  243. return stateObject.remove
  244. }
  245. return false
  246. }
  247. /*
  248. * SETTERS
  249. */
  250. func (self *StateDB) AddBalance(addr common.Address, amount *big.Int) {
  251. stateObject := self.GetOrNewStateObject(addr)
  252. if stateObject != nil {
  253. stateObject.AddBalance(amount)
  254. }
  255. }
  256. func (self *StateDB) SetBalance(addr common.Address, amount *big.Int) {
  257. stateObject := self.GetOrNewStateObject(addr)
  258. if stateObject != nil {
  259. stateObject.SetBalance(amount)
  260. }
  261. }
  262. func (self *StateDB) SetNonce(addr common.Address, nonce uint64) {
  263. stateObject := self.GetOrNewStateObject(addr)
  264. if stateObject != nil {
  265. stateObject.SetNonce(nonce)
  266. }
  267. }
  268. func (self *StateDB) SetCode(addr common.Address, code []byte) {
  269. stateObject := self.GetOrNewStateObject(addr)
  270. if stateObject != nil {
  271. stateObject.SetCode(crypto.Keccak256Hash(code), code)
  272. }
  273. }
  274. func (self *StateDB) SetState(addr common.Address, key common.Hash, value common.Hash) {
  275. stateObject := self.GetOrNewStateObject(addr)
  276. if stateObject != nil {
  277. stateObject.SetState(self.db, key, value)
  278. }
  279. }
  280. // Delete marks the given account as suicided.
  281. // This clears the account balance.
  282. //
  283. // The account's state object is still available until the state is committed,
  284. // GetStateObject will return a non-nil account after Delete.
  285. func (self *StateDB) Delete(addr common.Address) bool {
  286. stateObject := self.GetStateObject(addr)
  287. if stateObject == nil {
  288. return false
  289. }
  290. self.journal = append(self.journal, deleteAccountChange{
  291. account: &addr,
  292. prev: stateObject.remove,
  293. prevbalance: new(big.Int).Set(stateObject.Balance()),
  294. })
  295. stateObject.markForDeletion()
  296. stateObject.data.Balance = new(big.Int)
  297. return true
  298. }
  299. //
  300. // Setting, updating & deleting state object methods
  301. //
  302. // updateStateObject writes the given object to the trie.
  303. func (self *StateDB) updateStateObject(stateObject *StateObject) {
  304. addr := stateObject.Address()
  305. data, err := rlp.EncodeToBytes(stateObject)
  306. if err != nil {
  307. panic(fmt.Errorf("can't encode object at %x: %v", addr[:], err))
  308. }
  309. self.trie.Update(addr[:], data)
  310. }
  311. // deleteStateObject removes the given object from the state trie.
  312. func (self *StateDB) deleteStateObject(stateObject *StateObject) {
  313. stateObject.deleted = true
  314. addr := stateObject.Address()
  315. self.trie.Delete(addr[:])
  316. }
  317. // Retrieve a state object given my the address. Returns nil if not found.
  318. func (self *StateDB) GetStateObject(addr common.Address) (stateObject *StateObject) {
  319. // Prefer 'live' objects.
  320. if obj := self.stateObjects[addr]; obj != nil {
  321. if obj.deleted {
  322. return nil
  323. }
  324. return obj
  325. }
  326. // Load the object from the database.
  327. enc := self.trie.Get(addr[:])
  328. if len(enc) == 0 {
  329. return nil
  330. }
  331. var data Account
  332. if err := rlp.DecodeBytes(enc, &data); err != nil {
  333. glog.Errorf("can't decode object at %x: %v", addr[:], err)
  334. return nil
  335. }
  336. // Insert into the live set.
  337. obj := newObject(self, addr, data, self.MarkStateObjectDirty)
  338. self.setStateObject(obj)
  339. return obj
  340. }
  341. func (self *StateDB) setStateObject(object *StateObject) {
  342. self.stateObjects[object.Address()] = object
  343. }
  344. // Retrieve a state object or create a new state object if nil
  345. func (self *StateDB) GetOrNewStateObject(addr common.Address) *StateObject {
  346. stateObject := self.GetStateObject(addr)
  347. if stateObject == nil || stateObject.deleted {
  348. stateObject, _ = self.createObject(addr)
  349. }
  350. return stateObject
  351. }
  352. // MarkStateObjectDirty adds the specified object to the dirty map to avoid costly
  353. // state object cache iteration to find a handful of modified ones.
  354. func (self *StateDB) MarkStateObjectDirty(addr common.Address) {
  355. self.stateObjectsDirty[addr] = struct{}{}
  356. }
  357. // createObject creates a new state object. If there is an existing account with
  358. // the given address, it is overwritten and returned as the second return value.
  359. func (self *StateDB) createObject(addr common.Address) (newobj, prev *StateObject) {
  360. prev = self.GetStateObject(addr)
  361. newobj = newObject(self, addr, Account{}, self.MarkStateObjectDirty)
  362. newobj.setNonce(StartingNonce) // sets the object to dirty
  363. if prev == nil {
  364. if glog.V(logger.Core) {
  365. glog.Infof("(+) %x\n", addr)
  366. }
  367. self.journal = append(self.journal, createObjectChange{account: &addr})
  368. } else {
  369. self.journal = append(self.journal, resetObjectChange{prev: prev})
  370. }
  371. self.setStateObject(newobj)
  372. return newobj, prev
  373. }
  374. // CreateAccount explicitly creates a state object. If a state object with the address
  375. // already exists the balance is carried over to the new account.
  376. //
  377. // CreateAccount is called during the EVM CREATE operation. The situation might arise that
  378. // a contract does the following:
  379. //
  380. // 1. sends funds to sha(account ++ (nonce + 1))
  381. // 2. tx_create(sha(account ++ nonce)) (note that this gets the address of 1)
  382. //
  383. // Carrying over the balance ensures that Ether doesn't disappear.
  384. func (self *StateDB) CreateAccount(addr common.Address) vm.Account {
  385. new, prev := self.createObject(addr)
  386. if prev != nil {
  387. new.setBalance(prev.data.Balance)
  388. }
  389. return new
  390. }
  391. // Copy creates a deep, independent copy of the state.
  392. // Snapshots of the copied state cannot be applied to the copy.
  393. func (self *StateDB) Copy() *StateDB {
  394. self.lock.Lock()
  395. defer self.lock.Unlock()
  396. // Copy all the basic fields, initialize the memory ones
  397. state := &StateDB{
  398. db: self.db,
  399. trie: self.trie,
  400. pastTries: self.pastTries,
  401. codeSizeCache: self.codeSizeCache,
  402. stateObjects: make(map[common.Address]*StateObject, len(self.stateObjectsDirty)),
  403. stateObjectsDirty: make(map[common.Address]struct{}, len(self.stateObjectsDirty)),
  404. refund: new(big.Int).Set(self.refund),
  405. logs: make(map[common.Hash]vm.Logs, len(self.logs)),
  406. logSize: self.logSize,
  407. }
  408. // Copy the dirty states and logs
  409. for addr, _ := range self.stateObjectsDirty {
  410. state.stateObjects[addr] = self.stateObjects[addr].deepCopy(state, state.MarkStateObjectDirty)
  411. state.stateObjectsDirty[addr] = struct{}{}
  412. }
  413. for hash, logs := range self.logs {
  414. state.logs[hash] = make(vm.Logs, len(logs))
  415. copy(state.logs[hash], logs)
  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. // The return value must not be modified by the caller and will become
  446. // invalid at the next call to AddRefund.
  447. func (self *StateDB) GetRefund() *big.Int {
  448. return self.refund
  449. }
  450. // IntermediateRoot computes the current root hash of the state trie.
  451. // It is called in between transactions to get the root hash that
  452. // goes into transaction receipts.
  453. func (s *StateDB) IntermediateRoot() common.Hash {
  454. for addr, _ := range s.stateObjectsDirty {
  455. stateObject := s.stateObjects[addr]
  456. if stateObject.remove {
  457. s.deleteStateObject(stateObject)
  458. } else {
  459. stateObject.updateRoot(s.db)
  460. s.updateStateObject(stateObject)
  461. }
  462. }
  463. // Invalidate journal because reverting across transactions is not allowed.
  464. s.clearJournalAndRefund()
  465. return s.trie.Hash()
  466. }
  467. // DeleteSuicides flags the suicided objects for deletion so that it
  468. // won't be referenced again when called / queried up on.
  469. //
  470. // DeleteSuicides should not be used for consensus related updates
  471. // under any circumstances.
  472. func (s *StateDB) DeleteSuicides() {
  473. // Reset refund so that any used-gas calculations can use this method.
  474. s.clearJournalAndRefund()
  475. for addr, _ := range s.stateObjectsDirty {
  476. stateObject := s.stateObjects[addr]
  477. // If the object has been removed by a suicide
  478. // flag the object as deleted.
  479. if stateObject.remove {
  480. stateObject.deleted = true
  481. }
  482. delete(s.stateObjectsDirty, addr)
  483. }
  484. }
  485. // Commit commits all state changes to the database.
  486. func (s *StateDB) Commit() (root common.Hash, err error) {
  487. root, batch := s.CommitBatch()
  488. return root, batch.Write()
  489. }
  490. // CommitBatch commits all state changes to a write batch but does not
  491. // execute the batch. It is used to validate state changes against
  492. // the root hash stored in a block.
  493. func (s *StateDB) CommitBatch() (root common.Hash, batch ethdb.Batch) {
  494. batch = s.db.NewBatch()
  495. root, _ = s.commit(batch)
  496. return root, batch
  497. }
  498. func (s *StateDB) clearJournalAndRefund() {
  499. s.journal = nil
  500. s.validRevisions = s.validRevisions[:0]
  501. s.refund = new(big.Int)
  502. }
  503. func (s *StateDB) commit(dbw trie.DatabaseWriter) (root common.Hash, err error) {
  504. defer s.clearJournalAndRefund()
  505. // Commit objects to the trie.
  506. for addr, stateObject := range s.stateObjects {
  507. if stateObject.remove {
  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. } else if _, ok := s.stateObjectsDirty[addr]; ok {
  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. if err == nil {
  531. s.pushTrie(s.trie)
  532. }
  533. return root, err
  534. }