statedb.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  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. stateObjects map[string]*StateObject
  41. refund *big.Int
  42. thash, bhash common.Hash
  43. txIndex int
  44. logs map[common.Hash]vm.Logs
  45. logSize uint
  46. }
  47. // Create a new state from a given trie
  48. func New(root common.Hash, db ethdb.Database) (*StateDB, error) {
  49. tr, err := trie.NewSecure(root, db)
  50. if err != nil {
  51. return nil, 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. }, nil
  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. data, err := rlp.EncodeToBytes(stateObject)
  175. if err != nil {
  176. panic(fmt.Errorf("can't encode object at %x: %v", addr[:], err))
  177. }
  178. self.trie.Update(addr[:], data)
  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, err := DecodeObject(addr, self.db, data)
  201. if err != nil {
  202. glog.Errorf("can't decode object at %x: %v", addr[:], err)
  203. return nil
  204. }
  205. self.SetStateObject(stateObject)
  206. return stateObject
  207. }
  208. func (self *StateDB) SetStateObject(object *StateObject) {
  209. self.stateObjects[object.Address().Str()] = object
  210. }
  211. // Retrieve a state object or create a new state object if nil
  212. func (self *StateDB) GetOrNewStateObject(addr common.Address) *StateObject {
  213. stateObject := self.GetStateObject(addr)
  214. if stateObject == nil || stateObject.deleted {
  215. stateObject = self.CreateStateObject(addr)
  216. }
  217. return stateObject
  218. }
  219. // NewStateObject create a state object whether it exist in the trie or not
  220. func (self *StateDB) newStateObject(addr common.Address) *StateObject {
  221. if glog.V(logger.Core) {
  222. glog.Infof("(+) %x\n", addr)
  223. }
  224. stateObject := NewStateObject(addr, self.db)
  225. stateObject.SetNonce(StartingNonce)
  226. self.stateObjects[addr.Str()] = stateObject
  227. return stateObject
  228. }
  229. // Creates creates a new state object and takes ownership. This is different from "NewStateObject"
  230. func (self *StateDB) CreateStateObject(addr common.Address) *StateObject {
  231. // Get previous (if any)
  232. so := self.GetStateObject(addr)
  233. // Create a new one
  234. newSo := self.newStateObject(addr)
  235. // If it existed set the balance to the new account
  236. if so != nil {
  237. newSo.balance = so.balance
  238. }
  239. return newSo
  240. }
  241. func (self *StateDB) CreateAccount(addr common.Address) vm.Account {
  242. return self.CreateStateObject(addr)
  243. }
  244. //
  245. // Setting, copying of the state methods
  246. //
  247. func (self *StateDB) Copy() *StateDB {
  248. // ignore error - we assume state-to-be-copied always exists
  249. state, _ := New(common.Hash{}, self.db)
  250. state.trie = self.trie
  251. for k, stateObject := range self.stateObjects {
  252. state.stateObjects[k] = stateObject.Copy()
  253. }
  254. state.refund.Set(self.refund)
  255. for hash, logs := range self.logs {
  256. state.logs[hash] = make(vm.Logs, len(logs))
  257. copy(state.logs[hash], logs)
  258. }
  259. state.logSize = self.logSize
  260. return state
  261. }
  262. func (self *StateDB) Set(state *StateDB) {
  263. self.trie = state.trie
  264. self.stateObjects = state.stateObjects
  265. self.refund = state.refund
  266. self.logs = state.logs
  267. self.logSize = state.logSize
  268. }
  269. func (self *StateDB) GetRefund() *big.Int {
  270. return self.refund
  271. }
  272. // IntermediateRoot computes the current root hash of the state trie.
  273. // It is called in between transactions to get the root hash that
  274. // goes into transaction receipts.
  275. func (s *StateDB) IntermediateRoot() common.Hash {
  276. s.refund = new(big.Int)
  277. for _, stateObject := range s.stateObjects {
  278. if stateObject.dirty {
  279. if stateObject.remove {
  280. s.DeleteStateObject(stateObject)
  281. } else {
  282. stateObject.Update()
  283. s.UpdateStateObject(stateObject)
  284. }
  285. stateObject.dirty = false
  286. }
  287. }
  288. return s.trie.Hash()
  289. }
  290. // Commit commits all state changes to the database.
  291. func (s *StateDB) Commit() (root common.Hash, err error) {
  292. root, batch := s.CommitBatch()
  293. return root, batch.Write()
  294. }
  295. // CommitBatch commits all state changes to a write batch but does not
  296. // execute the batch. It is used to validate state changes against
  297. // the root hash stored in a block.
  298. func (s *StateDB) CommitBatch() (root common.Hash, batch ethdb.Batch) {
  299. batch = s.db.NewBatch()
  300. root, _ = s.commit(batch)
  301. return root, batch
  302. }
  303. func (s *StateDB) commit(db trie.DatabaseWriter) (common.Hash, error) {
  304. s.refund = new(big.Int)
  305. for _, stateObject := range s.stateObjects {
  306. if stateObject.remove {
  307. // If the object has been removed, don't bother syncing it
  308. // and just mark it for deletion in the trie.
  309. s.DeleteStateObject(stateObject)
  310. } else {
  311. // Write any contract code associated with the state object
  312. if len(stateObject.code) > 0 {
  313. if err := db.Put(stateObject.codeHash, stateObject.code); err != nil {
  314. return common.Hash{}, err
  315. }
  316. }
  317. // Write any storage changes in the state object to its trie.
  318. stateObject.Update()
  319. // Commit the trie of the object to the batch.
  320. // This updates the trie root internally, so
  321. // getting the root hash of the storage trie
  322. // through UpdateStateObject is fast.
  323. if _, err := stateObject.trie.CommitTo(db); err != nil {
  324. return common.Hash{}, err
  325. }
  326. // Update the object in the account trie.
  327. s.UpdateStateObject(stateObject)
  328. }
  329. stateObject.dirty = false
  330. }
  331. return s.trie.CommitTo(db)
  332. }
  333. func (self *StateDB) Refunds() *big.Int {
  334. return self.refund
  335. }
  336. // Debug stuff
  337. func (self *StateDB) CreateOutputForDiff() {
  338. for _, stateObject := range self.stateObjects {
  339. stateObject.CreateOutputForDiff()
  340. }
  341. }