statedb.go 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  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. "math/big"
  20. "github.com/ethereum/go-ethereum/common"
  21. "github.com/ethereum/go-ethereum/core/vm"
  22. "github.com/ethereum/go-ethereum/ethdb"
  23. "github.com/ethereum/go-ethereum/logger"
  24. "github.com/ethereum/go-ethereum/logger/glog"
  25. "github.com/ethereum/go-ethereum/trie"
  26. )
  27. // StateDBs within the ethereum protocol are used to store anything
  28. // within the merkle trie. StateDBs take care of caching and storing
  29. // nested states. It's the general query interface to retrieve:
  30. // * Contracts
  31. // * Accounts
  32. type StateDB struct {
  33. db ethdb.Database
  34. trie *trie.SecureTrie
  35. stateObjects map[string]*StateObject
  36. refund *big.Int
  37. thash, bhash common.Hash
  38. txIndex int
  39. logs map[common.Hash]vm.Logs
  40. logSize uint
  41. }
  42. // Create a new state from a given trie
  43. func New(root common.Hash, db ethdb.Database) *StateDB {
  44. tr, err := trie.NewSecure(root, db)
  45. if err != nil {
  46. // TODO: bubble this up
  47. tr, _ = trie.NewSecure(common.Hash{}, db)
  48. glog.Errorf("can't create state trie with root %x: %v", root[:], err)
  49. }
  50. return &StateDB{
  51. db: db,
  52. trie: tr,
  53. stateObjects: make(map[string]*StateObject),
  54. refund: new(big.Int),
  55. logs: make(map[common.Hash]vm.Logs),
  56. }
  57. }
  58. func (self *StateDB) StartRecord(thash, bhash common.Hash, ti int) {
  59. self.thash = thash
  60. self.bhash = bhash
  61. self.txIndex = ti
  62. }
  63. func (self *StateDB) AddLog(log *vm.Log) {
  64. log.TxHash = self.thash
  65. log.BlockHash = self.bhash
  66. log.TxIndex = uint(self.txIndex)
  67. log.Index = self.logSize
  68. self.logs[self.thash] = append(self.logs[self.thash], log)
  69. self.logSize++
  70. }
  71. func (self *StateDB) GetLogs(hash common.Hash) vm.Logs {
  72. return self.logs[hash]
  73. }
  74. func (self *StateDB) Logs() vm.Logs {
  75. var logs vm.Logs
  76. for _, lgs := range self.logs {
  77. logs = append(logs, lgs...)
  78. }
  79. return logs
  80. }
  81. func (self *StateDB) AddRefund(gas *big.Int) {
  82. self.refund.Add(self.refund, gas)
  83. }
  84. func (self *StateDB) HasAccount(addr common.Address) bool {
  85. return self.GetStateObject(addr) != nil
  86. }
  87. func (self *StateDB) Exist(addr common.Address) bool {
  88. return self.GetStateObject(addr) != nil
  89. }
  90. func (self *StateDB) GetAccount(addr common.Address) vm.Account {
  91. return self.GetStateObject(addr)
  92. }
  93. // Retrieve the balance from the given address or 0 if object not found
  94. func (self *StateDB) GetBalance(addr common.Address) *big.Int {
  95. stateObject := self.GetStateObject(addr)
  96. if stateObject != nil {
  97. return stateObject.balance
  98. }
  99. return common.Big0
  100. }
  101. func (self *StateDB) GetNonce(addr common.Address) uint64 {
  102. stateObject := self.GetStateObject(addr)
  103. if stateObject != nil {
  104. return stateObject.nonce
  105. }
  106. return 0
  107. }
  108. func (self *StateDB) GetCode(addr common.Address) []byte {
  109. stateObject := self.GetStateObject(addr)
  110. if stateObject != nil {
  111. return stateObject.code
  112. }
  113. return nil
  114. }
  115. func (self *StateDB) GetState(a common.Address, b common.Hash) common.Hash {
  116. stateObject := self.GetStateObject(a)
  117. if stateObject != nil {
  118. return stateObject.GetState(b)
  119. }
  120. return common.Hash{}
  121. }
  122. func (self *StateDB) IsDeleted(addr common.Address) bool {
  123. stateObject := self.GetStateObject(addr)
  124. if stateObject != nil {
  125. return stateObject.remove
  126. }
  127. return false
  128. }
  129. /*
  130. * SETTERS
  131. */
  132. func (self *StateDB) AddBalance(addr common.Address, amount *big.Int) {
  133. stateObject := self.GetOrNewStateObject(addr)
  134. if stateObject != nil {
  135. stateObject.AddBalance(amount)
  136. }
  137. }
  138. func (self *StateDB) SetNonce(addr common.Address, nonce uint64) {
  139. stateObject := self.GetOrNewStateObject(addr)
  140. if stateObject != nil {
  141. stateObject.SetNonce(nonce)
  142. }
  143. }
  144. func (self *StateDB) SetCode(addr common.Address, code []byte) {
  145. stateObject := self.GetOrNewStateObject(addr)
  146. if stateObject != nil {
  147. stateObject.SetCode(code)
  148. }
  149. }
  150. func (self *StateDB) SetState(addr common.Address, key common.Hash, value common.Hash) {
  151. stateObject := self.GetOrNewStateObject(addr)
  152. if stateObject != nil {
  153. stateObject.SetState(key, value)
  154. }
  155. }
  156. func (self *StateDB) Delete(addr common.Address) bool {
  157. stateObject := self.GetStateObject(addr)
  158. if stateObject != nil {
  159. stateObject.MarkForDeletion()
  160. stateObject.balance = new(big.Int)
  161. return true
  162. }
  163. return false
  164. }
  165. //
  166. // Setting, updating & deleting state object methods
  167. //
  168. // Update the given state object and apply it to state trie
  169. func (self *StateDB) UpdateStateObject(stateObject *StateObject) {
  170. //addr := stateObject.Address()
  171. if len(stateObject.CodeHash()) > 0 {
  172. self.db.Put(stateObject.CodeHash(), stateObject.code)
  173. }
  174. addr := stateObject.Address()
  175. self.trie.Update(addr[:], stateObject.RlpEncode())
  176. }
  177. // Delete the given state object and delete it from the state trie
  178. func (self *StateDB) DeleteStateObject(stateObject *StateObject) {
  179. stateObject.deleted = true
  180. addr := stateObject.Address()
  181. self.trie.Delete(addr[:])
  182. //delete(self.stateObjects, addr.Str())
  183. }
  184. // Retrieve a state object given my the address. Nil if not found
  185. func (self *StateDB) GetStateObject(addr common.Address) (stateObject *StateObject) {
  186. stateObject = self.stateObjects[addr.Str()]
  187. if stateObject != nil {
  188. if stateObject.deleted {
  189. stateObject = nil
  190. }
  191. return stateObject
  192. }
  193. data := self.trie.Get(addr[:])
  194. if len(data) == 0 {
  195. return nil
  196. }
  197. stateObject = NewStateObjectFromBytes(addr, []byte(data), self.db)
  198. self.SetStateObject(stateObject)
  199. return stateObject
  200. }
  201. func (self *StateDB) SetStateObject(object *StateObject) {
  202. self.stateObjects[object.Address().Str()] = object
  203. }
  204. // Retrieve a state object or create a new state object if nil
  205. func (self *StateDB) GetOrNewStateObject(addr common.Address) *StateObject {
  206. stateObject := self.GetStateObject(addr)
  207. if stateObject == nil || stateObject.deleted {
  208. stateObject = self.CreateStateObject(addr)
  209. }
  210. return stateObject
  211. }
  212. // NewStateObject create a state object whether it exist in the trie or not
  213. func (self *StateDB) newStateObject(addr common.Address) *StateObject {
  214. if glog.V(logger.Core) {
  215. glog.Infof("(+) %x\n", addr)
  216. }
  217. stateObject := NewStateObject(addr, self.db)
  218. self.stateObjects[addr.Str()] = stateObject
  219. return stateObject
  220. }
  221. // Creates creates a new state object and takes ownership. This is different from "NewStateObject"
  222. func (self *StateDB) CreateStateObject(addr common.Address) *StateObject {
  223. // Get previous (if any)
  224. so := self.GetStateObject(addr)
  225. // Create a new one
  226. newSo := self.newStateObject(addr)
  227. // If it existed set the balance to the new account
  228. if so != nil {
  229. newSo.balance = so.balance
  230. }
  231. return newSo
  232. }
  233. func (self *StateDB) CreateAccount(addr common.Address) vm.Account {
  234. return self.CreateStateObject(addr)
  235. }
  236. //
  237. // Setting, copying of the state methods
  238. //
  239. func (self *StateDB) Copy() *StateDB {
  240. state := New(common.Hash{}, self.db)
  241. state.trie = self.trie
  242. for k, stateObject := range self.stateObjects {
  243. state.stateObjects[k] = stateObject.Copy()
  244. }
  245. state.refund.Set(self.refund)
  246. for hash, logs := range self.logs {
  247. state.logs[hash] = make(vm.Logs, len(logs))
  248. copy(state.logs[hash], logs)
  249. }
  250. state.logSize = self.logSize
  251. return state
  252. }
  253. func (self *StateDB) Set(state *StateDB) {
  254. self.trie = state.trie
  255. self.stateObjects = state.stateObjects
  256. self.refund = state.refund
  257. self.logs = state.logs
  258. self.logSize = state.logSize
  259. }
  260. func (self *StateDB) GetRefund() *big.Int {
  261. return self.refund
  262. }
  263. // IntermediateRoot computes the current root hash of the state trie.
  264. // It is called in between transactions to get the root hash that
  265. // goes into transaction receipts.
  266. func (s *StateDB) IntermediateRoot() common.Hash {
  267. s.refund = new(big.Int)
  268. for _, stateObject := range s.stateObjects {
  269. if stateObject.dirty {
  270. if stateObject.remove {
  271. s.DeleteStateObject(stateObject)
  272. } else {
  273. stateObject.Update()
  274. s.UpdateStateObject(stateObject)
  275. }
  276. stateObject.dirty = false
  277. }
  278. }
  279. return s.trie.Hash()
  280. }
  281. // Commit commits all state changes to the database.
  282. func (s *StateDB) Commit() (root common.Hash, err error) {
  283. return s.commit(s.db)
  284. }
  285. // CommitBatch commits all state changes to a write batch but does not
  286. // execute the batch. It is used to validate state changes against
  287. // the root hash stored in a block.
  288. func (s *StateDB) CommitBatch() (root common.Hash, batch ethdb.Batch) {
  289. batch = s.db.NewBatch()
  290. root, _ = s.commit(batch)
  291. return root, batch
  292. }
  293. func (s *StateDB) commit(db trie.DatabaseWriter) (common.Hash, error) {
  294. s.refund = new(big.Int)
  295. for _, stateObject := range s.stateObjects {
  296. if stateObject.remove {
  297. // If the object has been removed, don't bother syncing it
  298. // and just mark it for deletion in the trie.
  299. s.DeleteStateObject(stateObject)
  300. } else {
  301. // Write any storage changes in the state object to its trie.
  302. stateObject.Update()
  303. // Commit the trie of the object to the batch.
  304. // This updates the trie root internally, so
  305. // getting the root hash of the storage trie
  306. // through UpdateStateObject is fast.
  307. if _, err := stateObject.trie.CommitTo(db); err != nil {
  308. return common.Hash{}, err
  309. }
  310. // Update the object in the account trie.
  311. s.UpdateStateObject(stateObject)
  312. }
  313. stateObject.dirty = false
  314. }
  315. return s.trie.CommitTo(db)
  316. }
  317. func (self *StateDB) Refunds() *big.Int {
  318. return self.refund
  319. }
  320. // Debug stuff
  321. func (self *StateDB) CreateOutputForDiff() {
  322. for _, stateObject := range self.stateObjects {
  323. stateObject.CreateOutputForDiff()
  324. }
  325. }