statedb.go 15 KB

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