statedb.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  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. "github.com/ethereum/go-ethereum/common"
  22. "github.com/ethereum/go-ethereum/core/vm"
  23. "github.com/ethereum/go-ethereum/ethdb"
  24. "github.com/ethereum/go-ethereum/logger"
  25. "github.com/ethereum/go-ethereum/logger/glog"
  26. "github.com/ethereum/go-ethereum/rlp"
  27. "github.com/ethereum/go-ethereum/trie"
  28. lru "github.com/hashicorp/golang-lru"
  29. )
  30. // The starting nonce determines the default nonce when new accounts are being
  31. // created.
  32. var StartingNonce uint64
  33. const (
  34. // Number of past tries to keep. The arbitrarily chosen value here
  35. // is max uncle depth + 1.
  36. maxJournalLength = 8
  37. // Number of codehash->size associations to keep.
  38. codeSizeCacheSize = 100000
  39. )
  40. // StateDBs within the ethereum protocol are used to store anything
  41. // within the merkle trie. StateDBs take care of caching and storing
  42. // nested states. It's the general query interface to retrieve:
  43. // * Contracts
  44. // * Accounts
  45. type StateDB struct {
  46. db ethdb.Database
  47. trie *trie.SecureTrie
  48. pastTries []*trie.SecureTrie
  49. codeSizeCache *lru.Cache
  50. // This map holds 'live' objects, which will get modified while processing a state transition.
  51. stateObjects map[common.Address]*StateObject
  52. stateObjectsDirty map[common.Address]struct{}
  53. // The refund counter, also used by state transitioning.
  54. refund *big.Int
  55. thash, bhash common.Hash
  56. txIndex int
  57. logs map[common.Hash]vm.Logs
  58. logSize uint
  59. }
  60. // Create a new state from a given trie
  61. func New(root common.Hash, db ethdb.Database) (*StateDB, error) {
  62. tr, err := trie.NewSecure(root, db)
  63. if err != nil {
  64. return nil, err
  65. }
  66. csc, _ := lru.New(codeSizeCacheSize)
  67. return &StateDB{
  68. db: db,
  69. trie: tr,
  70. codeSizeCache: csc,
  71. stateObjects: make(map[common.Address]*StateObject),
  72. stateObjectsDirty: make(map[common.Address]struct{}),
  73. refund: new(big.Int),
  74. logs: make(map[common.Hash]vm.Logs),
  75. }, nil
  76. }
  77. // Reset clears out all emphemeral state objects from the state db, but keeps
  78. // the underlying state trie to avoid reloading data for the next operations.
  79. func (self *StateDB) Reset(root common.Hash) error {
  80. tr, err := self.openTrie(root)
  81. if err != nil {
  82. return err
  83. }
  84. *self = StateDB{
  85. db: self.db,
  86. trie: tr,
  87. pastTries: self.pastTries,
  88. codeSizeCache: self.codeSizeCache,
  89. stateObjects: make(map[common.Address]*StateObject),
  90. stateObjectsDirty: make(map[common.Address]struct{}),
  91. refund: new(big.Int),
  92. logs: make(map[common.Hash]vm.Logs),
  93. }
  94. return nil
  95. }
  96. // openTrie creates a trie. It uses an existing trie if one is available
  97. // from the journal if available.
  98. func (self *StateDB) openTrie(root common.Hash) (*trie.SecureTrie, error) {
  99. if self.trie != nil && self.trie.Hash() == root {
  100. return self.trie, nil
  101. }
  102. for i := len(self.pastTries) - 1; i >= 0; i-- {
  103. if self.pastTries[i].Hash() == root {
  104. tr := *self.pastTries[i]
  105. return &tr, nil
  106. }
  107. }
  108. return trie.NewSecure(root, self.db)
  109. }
  110. func (self *StateDB) pushTrie(t *trie.SecureTrie) {
  111. if len(self.pastTries) >= maxJournalLength {
  112. copy(self.pastTries, self.pastTries[1:])
  113. self.pastTries[len(self.pastTries)-1] = t
  114. } else {
  115. self.pastTries = append(self.pastTries, t)
  116. }
  117. }
  118. func (self *StateDB) StartRecord(thash, bhash common.Hash, ti int) {
  119. self.thash = thash
  120. self.bhash = bhash
  121. self.txIndex = ti
  122. }
  123. func (self *StateDB) AddLog(log *vm.Log) {
  124. log.TxHash = self.thash
  125. log.BlockHash = self.bhash
  126. log.TxIndex = uint(self.txIndex)
  127. log.Index = self.logSize
  128. self.logs[self.thash] = append(self.logs[self.thash], log)
  129. self.logSize++
  130. }
  131. func (self *StateDB) GetLogs(hash common.Hash) vm.Logs {
  132. return self.logs[hash]
  133. }
  134. func (self *StateDB) Logs() vm.Logs {
  135. var logs vm.Logs
  136. for _, lgs := range self.logs {
  137. logs = append(logs, lgs...)
  138. }
  139. return logs
  140. }
  141. func (self *StateDB) AddRefund(gas *big.Int) {
  142. self.refund.Add(self.refund, gas)
  143. }
  144. func (self *StateDB) HasAccount(addr common.Address) bool {
  145. return self.GetStateObject(addr) != nil
  146. }
  147. func (self *StateDB) Exist(addr common.Address) bool {
  148. return self.GetStateObject(addr) != nil
  149. }
  150. func (self *StateDB) GetAccount(addr common.Address) vm.Account {
  151. return self.GetStateObject(addr)
  152. }
  153. // Retrieve the balance from the given address or 0 if object not found
  154. func (self *StateDB) GetBalance(addr common.Address) *big.Int {
  155. stateObject := self.GetStateObject(addr)
  156. if stateObject != nil {
  157. return stateObject.Balance()
  158. }
  159. return common.Big0
  160. }
  161. func (self *StateDB) GetNonce(addr common.Address) uint64 {
  162. stateObject := self.GetStateObject(addr)
  163. if stateObject != nil {
  164. return stateObject.Nonce()
  165. }
  166. return StartingNonce
  167. }
  168. func (self *StateDB) GetCode(addr common.Address) []byte {
  169. stateObject := self.GetStateObject(addr)
  170. if stateObject != nil {
  171. code := stateObject.Code(self.db)
  172. key := common.BytesToHash(stateObject.CodeHash())
  173. self.codeSizeCache.Add(key, len(code))
  174. return code
  175. }
  176. return nil
  177. }
  178. func (self *StateDB) GetCodeSize(addr common.Address) int {
  179. stateObject := self.GetStateObject(addr)
  180. if stateObject == nil {
  181. return 0
  182. }
  183. key := common.BytesToHash(stateObject.CodeHash())
  184. if cached, ok := self.codeSizeCache.Get(key); ok {
  185. return cached.(int)
  186. }
  187. size := len(stateObject.Code(self.db))
  188. if stateObject.dbErr == nil {
  189. self.codeSizeCache.Add(key, size)
  190. }
  191. return size
  192. }
  193. func (self *StateDB) GetState(a common.Address, b common.Hash) common.Hash {
  194. stateObject := self.GetStateObject(a)
  195. if stateObject != nil {
  196. return stateObject.GetState(self.db, b)
  197. }
  198. return common.Hash{}
  199. }
  200. func (self *StateDB) IsDeleted(addr common.Address) bool {
  201. stateObject := self.GetStateObject(addr)
  202. if stateObject != nil {
  203. return stateObject.remove
  204. }
  205. return false
  206. }
  207. /*
  208. * SETTERS
  209. */
  210. func (self *StateDB) AddBalance(addr common.Address, amount *big.Int) {
  211. stateObject := self.GetOrNewStateObject(addr)
  212. if stateObject != nil {
  213. stateObject.AddBalance(amount)
  214. }
  215. }
  216. func (self *StateDB) SetNonce(addr common.Address, nonce uint64) {
  217. stateObject := self.GetOrNewStateObject(addr)
  218. if stateObject != nil {
  219. stateObject.SetNonce(nonce)
  220. }
  221. }
  222. func (self *StateDB) SetCode(addr common.Address, code []byte) {
  223. stateObject := self.GetOrNewStateObject(addr)
  224. if stateObject != nil {
  225. stateObject.SetCode(code)
  226. }
  227. }
  228. func (self *StateDB) SetState(addr common.Address, key common.Hash, value common.Hash) {
  229. stateObject := self.GetOrNewStateObject(addr)
  230. if stateObject != nil {
  231. stateObject.SetState(key, value)
  232. }
  233. }
  234. func (self *StateDB) Delete(addr common.Address) bool {
  235. stateObject := self.GetStateObject(addr)
  236. if stateObject != nil {
  237. stateObject.MarkForDeletion()
  238. stateObject.data.Balance = new(big.Int)
  239. return true
  240. }
  241. return false
  242. }
  243. //
  244. // Setting, updating & deleting state object methods
  245. //
  246. // Update the given state object and apply it to state trie
  247. func (self *StateDB) UpdateStateObject(stateObject *StateObject) {
  248. addr := stateObject.Address()
  249. data, err := rlp.EncodeToBytes(stateObject)
  250. if err != nil {
  251. panic(fmt.Errorf("can't encode object at %x: %v", addr[:], err))
  252. }
  253. self.trie.Update(addr[:], data)
  254. }
  255. // Delete the given state object and delete it from the state trie
  256. func (self *StateDB) DeleteStateObject(stateObject *StateObject) {
  257. stateObject.deleted = true
  258. addr := stateObject.Address()
  259. self.trie.Delete(addr[:])
  260. }
  261. // Retrieve a state object given my the address. Returns nil if not found.
  262. func (self *StateDB) GetStateObject(addr common.Address) (stateObject *StateObject) {
  263. // Prefer 'live' objects.
  264. if obj := self.stateObjects[addr]; obj != nil {
  265. if obj.deleted {
  266. return nil
  267. }
  268. return obj
  269. }
  270. // Load the object from the database.
  271. enc := self.trie.Get(addr[:])
  272. if len(enc) == 0 {
  273. return nil
  274. }
  275. var data Account
  276. if err := rlp.DecodeBytes(enc, &data); err != nil {
  277. glog.Errorf("can't decode object at %x: %v", addr[:], err)
  278. return nil
  279. }
  280. // Insert into the live set.
  281. obj := NewObject(addr, data, self.MarkStateObjectDirty)
  282. self.SetStateObject(obj)
  283. return obj
  284. }
  285. func (self *StateDB) SetStateObject(object *StateObject) {
  286. self.stateObjects[object.Address()] = object
  287. }
  288. // Retrieve a state object or create a new state object if nil
  289. func (self *StateDB) GetOrNewStateObject(addr common.Address) *StateObject {
  290. stateObject := self.GetStateObject(addr)
  291. if stateObject == nil || stateObject.deleted {
  292. stateObject = self.CreateStateObject(addr)
  293. }
  294. return stateObject
  295. }
  296. // NewStateObject create a state object whether it exist in the trie or not
  297. func (self *StateDB) newStateObject(addr common.Address) *StateObject {
  298. if glog.V(logger.Core) {
  299. glog.Infof("(+) %x\n", addr)
  300. }
  301. obj := NewObject(addr, Account{}, self.MarkStateObjectDirty)
  302. obj.SetNonce(StartingNonce) // sets the object to dirty
  303. self.stateObjects[addr] = obj
  304. return obj
  305. }
  306. // MarkStateObjectDirty adds the specified object to the dirty map to avoid costly
  307. // state object cache iteration to find a handful of modified ones.
  308. func (self *StateDB) MarkStateObjectDirty(addr common.Address) {
  309. self.stateObjectsDirty[addr] = struct{}{}
  310. }
  311. // Creates creates a new state object and takes ownership.
  312. func (self *StateDB) CreateStateObject(addr common.Address) *StateObject {
  313. // Get previous (if any)
  314. so := self.GetStateObject(addr)
  315. // Create a new one
  316. newSo := self.newStateObject(addr)
  317. // If it existed set the balance to the new account
  318. if so != nil {
  319. newSo.data.Balance = so.data.Balance
  320. }
  321. return newSo
  322. }
  323. func (self *StateDB) CreateAccount(addr common.Address) vm.Account {
  324. return self.CreateStateObject(addr)
  325. }
  326. //
  327. // Setting, copying of the state methods
  328. //
  329. func (self *StateDB) Copy() *StateDB {
  330. // Copy all the basic fields, initialize the memory ones
  331. state := &StateDB{
  332. db: self.db,
  333. trie: self.trie,
  334. pastTries: self.pastTries,
  335. codeSizeCache: self.codeSizeCache,
  336. stateObjects: make(map[common.Address]*StateObject, len(self.stateObjectsDirty)),
  337. stateObjectsDirty: make(map[common.Address]struct{}, len(self.stateObjectsDirty)),
  338. refund: new(big.Int).Set(self.refund),
  339. logs: make(map[common.Hash]vm.Logs, len(self.logs)),
  340. logSize: self.logSize,
  341. }
  342. // Copy the dirty states and logs
  343. for addr, _ := range self.stateObjectsDirty {
  344. state.stateObjects[addr] = self.stateObjects[addr].Copy(self.db, state.MarkStateObjectDirty)
  345. state.stateObjectsDirty[addr] = struct{}{}
  346. }
  347. for hash, logs := range self.logs {
  348. state.logs[hash] = make(vm.Logs, len(logs))
  349. copy(state.logs[hash], logs)
  350. }
  351. return state
  352. }
  353. func (self *StateDB) Set(state *StateDB) {
  354. self.db = state.db
  355. self.trie = state.trie
  356. self.pastTries = state.pastTries
  357. self.stateObjects = state.stateObjects
  358. self.stateObjectsDirty = state.stateObjectsDirty
  359. self.codeSizeCache = state.codeSizeCache
  360. self.refund = state.refund
  361. self.logs = state.logs
  362. self.logSize = state.logSize
  363. }
  364. func (self *StateDB) GetRefund() *big.Int {
  365. return self.refund
  366. }
  367. // IntermediateRoot computes the current root hash of the state trie.
  368. // It is called in between transactions to get the root hash that
  369. // goes into transaction receipts.
  370. func (s *StateDB) IntermediateRoot() common.Hash {
  371. s.refund = new(big.Int)
  372. for addr, _ := range s.stateObjectsDirty {
  373. stateObject := s.stateObjects[addr]
  374. if stateObject.remove {
  375. s.DeleteStateObject(stateObject)
  376. } else {
  377. stateObject.UpdateRoot(s.db)
  378. s.UpdateStateObject(stateObject)
  379. }
  380. }
  381. return s.trie.Hash()
  382. }
  383. // DeleteSuicides flags the suicided objects for deletion so that it
  384. // won't be referenced again when called / queried up on.
  385. //
  386. // DeleteSuicides should not be used for consensus related updates
  387. // under any circumstances.
  388. func (s *StateDB) DeleteSuicides() {
  389. // Reset refund so that any used-gas calculations can use
  390. // this method.
  391. s.refund = new(big.Int)
  392. for addr, _ := range s.stateObjectsDirty {
  393. stateObject := s.stateObjects[addr]
  394. // If the object has been removed by a suicide
  395. // flag the object as deleted.
  396. if stateObject.remove {
  397. stateObject.deleted = true
  398. }
  399. delete(s.stateObjectsDirty, addr)
  400. }
  401. }
  402. // Commit commits all state changes to the database.
  403. func (s *StateDB) Commit() (root common.Hash, err error) {
  404. root, batch := s.CommitBatch()
  405. return root, batch.Write()
  406. }
  407. // CommitBatch commits all state changes to a write batch but does not
  408. // execute the batch. It is used to validate state changes against
  409. // the root hash stored in a block.
  410. func (s *StateDB) CommitBatch() (root common.Hash, batch ethdb.Batch) {
  411. batch = s.db.NewBatch()
  412. root, _ = s.commit(batch)
  413. return root, batch
  414. }
  415. func (s *StateDB) commit(dbw trie.DatabaseWriter) (root common.Hash, err error) {
  416. s.refund = new(big.Int)
  417. // Commit objects to the trie.
  418. for addr, stateObject := range s.stateObjects {
  419. if stateObject.remove {
  420. // If the object has been removed, don't bother syncing it
  421. // and just mark it for deletion in the trie.
  422. s.DeleteStateObject(stateObject)
  423. } else if _, ok := s.stateObjectsDirty[addr]; ok {
  424. // Write any contract code associated with the state object
  425. if stateObject.code != nil && stateObject.dirtyCode {
  426. if err := dbw.Put(stateObject.CodeHash(), stateObject.code); err != nil {
  427. return common.Hash{}, err
  428. }
  429. stateObject.dirtyCode = false
  430. }
  431. // Write any storage changes in the state object to its storage trie.
  432. if err := stateObject.CommitTrie(s.db, dbw); err != nil {
  433. return common.Hash{}, err
  434. }
  435. // Update the object in the main account trie.
  436. s.UpdateStateObject(stateObject)
  437. }
  438. delete(s.stateObjectsDirty, addr)
  439. }
  440. // Write trie changes.
  441. root, err = s.trie.CommitTo(dbw)
  442. if err == nil {
  443. s.pushTrie(s.trie)
  444. }
  445. return root, err
  446. }
  447. func (self *StateDB) Refunds() *big.Int {
  448. return self.refund
  449. }