statedb.go 14 KB

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