statedb.go 15 KB

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