statedb.go 10 KB

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