state_object.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  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
  17. import (
  18. "bytes"
  19. "fmt"
  20. "io"
  21. "math/big"
  22. "github.com/ethereum/go-ethereum/common"
  23. "github.com/ethereum/go-ethereum/crypto"
  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. var emptyCodeHash = crypto.Keccak256(nil)
  30. type Code []byte
  31. func (self Code) String() string {
  32. return string(self) //strings.Join(Disassemble(self), " ")
  33. }
  34. type Storage map[common.Hash]common.Hash
  35. func (self Storage) String() (str string) {
  36. for key, value := range self {
  37. str += fmt.Sprintf("%X : %X\n", key, value)
  38. }
  39. return
  40. }
  41. func (self Storage) Copy() Storage {
  42. cpy := make(Storage)
  43. for key, value := range self {
  44. cpy[key] = value
  45. }
  46. return cpy
  47. }
  48. // StateObject represents an Ethereum account which is being modified.
  49. //
  50. // The usage pattern is as follows:
  51. // First you need to obtain a state object.
  52. // Account values can be accessed and modified through the object.
  53. // Finally, call CommitTrie to write the modified storage trie into a database.
  54. type StateObject struct {
  55. address common.Address // Ethereum address of this account
  56. data Account
  57. // DB error.
  58. // State objects are used by the consensus core and VM which are
  59. // unable to deal with database-level errors. Any error that occurs
  60. // during a database read is memoized here and will eventually be returned
  61. // by StateDB.Commit.
  62. dbErr error
  63. // Write caches.
  64. trie *trie.SecureTrie // storage trie, which becomes non-nil on first access
  65. code Code // contract bytecode, which gets set when code is loaded
  66. cachedStorage Storage // Storage entry cache to avoid duplicate reads
  67. dirtyStorage Storage // Storage entries that need to be flushed to disk
  68. // Cache flags.
  69. // When an object is marked for deletion it will be delete from the trie
  70. // during the "update" phase of the state transition
  71. dirtyCode bool // true if the code was updated
  72. remove bool
  73. deleted bool
  74. onDirty func(addr common.Address) // Callback method to mark a state object newly dirty
  75. }
  76. // Account is the Ethereum consensus representation of accounts.
  77. // These objects are stored in the main account trie.
  78. type Account struct {
  79. Nonce uint64
  80. Balance *big.Int
  81. Root common.Hash // merkle root of the storage trie
  82. CodeHash []byte
  83. }
  84. // NewObject creates a state object.
  85. func NewObject(address common.Address, data Account, onDirty func(addr common.Address)) *StateObject {
  86. if data.Balance == nil {
  87. data.Balance = new(big.Int)
  88. }
  89. if data.CodeHash == nil {
  90. data.CodeHash = emptyCodeHash
  91. }
  92. return &StateObject{address: address, data: data, cachedStorage: make(Storage), dirtyStorage: make(Storage), onDirty: onDirty}
  93. }
  94. // EncodeRLP implements rlp.Encoder.
  95. func (c *StateObject) EncodeRLP(w io.Writer) error {
  96. return rlp.Encode(w, c.data)
  97. }
  98. // setError remembers the first non-nil error it is called with.
  99. func (self *StateObject) setError(err error) {
  100. if self.dbErr == nil {
  101. self.dbErr = err
  102. }
  103. }
  104. func (self *StateObject) MarkForDeletion() {
  105. self.remove = true
  106. if self.onDirty != nil {
  107. self.onDirty(self.Address())
  108. self.onDirty = nil
  109. }
  110. if glog.V(logger.Core) {
  111. glog.Infof("%x: #%d %v X\n", self.Address(), self.Nonce(), self.Balance())
  112. }
  113. }
  114. func (c *StateObject) getTrie(db trie.Database) *trie.SecureTrie {
  115. if c.trie == nil {
  116. var err error
  117. c.trie, err = trie.NewSecure(c.data.Root, db)
  118. if err != nil {
  119. c.trie, _ = trie.NewSecure(common.Hash{}, db)
  120. c.setError(fmt.Errorf("can't create storage trie: %v", err))
  121. }
  122. }
  123. return c.trie
  124. }
  125. // GetState returns a value in account storage.
  126. func (self *StateObject) GetState(db trie.Database, key common.Hash) common.Hash {
  127. value, exists := self.cachedStorage[key]
  128. if exists {
  129. return value
  130. }
  131. // Load from DB in case it is missing.
  132. tr := self.getTrie(db)
  133. var ret []byte
  134. rlp.DecodeBytes(tr.Get(key[:]), &ret)
  135. value = common.BytesToHash(ret)
  136. if (value != common.Hash{}) {
  137. self.cachedStorage[key] = value
  138. }
  139. return value
  140. }
  141. // SetState updates a value in account storage.
  142. func (self *StateObject) SetState(key, value common.Hash) {
  143. self.cachedStorage[key] = value
  144. self.dirtyStorage[key] = value
  145. if self.onDirty != nil {
  146. self.onDirty(self.Address())
  147. self.onDirty = nil
  148. }
  149. }
  150. // updateTrie writes cached storage modifications into the object's storage trie.
  151. func (self *StateObject) updateTrie(db trie.Database) {
  152. tr := self.getTrie(db)
  153. for key, value := range self.dirtyStorage {
  154. delete(self.dirtyStorage, key)
  155. if (value == common.Hash{}) {
  156. tr.Delete(key[:])
  157. continue
  158. }
  159. // Encoding []byte cannot fail, ok to ignore the error.
  160. v, _ := rlp.EncodeToBytes(bytes.TrimLeft(value[:], "\x00"))
  161. tr.Update(key[:], v)
  162. }
  163. }
  164. // UpdateRoot sets the trie root to the current root hash of
  165. func (self *StateObject) UpdateRoot(db trie.Database) {
  166. self.updateTrie(db)
  167. self.data.Root = self.trie.Hash()
  168. }
  169. // CommitTrie the storage trie of the object to dwb.
  170. // This updates the trie root.
  171. func (self *StateObject) CommitTrie(db trie.Database, dbw trie.DatabaseWriter) error {
  172. self.updateTrie(db)
  173. if self.dbErr != nil {
  174. fmt.Println("dbErr:", self.dbErr)
  175. return self.dbErr
  176. }
  177. root, err := self.trie.CommitTo(dbw)
  178. if err == nil {
  179. self.data.Root = root
  180. }
  181. return err
  182. }
  183. func (c *StateObject) AddBalance(amount *big.Int) {
  184. if amount.Cmp(common.Big0) == 0 {
  185. return
  186. }
  187. c.SetBalance(new(big.Int).Add(c.Balance(), amount))
  188. if glog.V(logger.Core) {
  189. glog.Infof("%x: #%d %v (+ %v)\n", c.Address(), c.Nonce(), c.Balance(), amount)
  190. }
  191. }
  192. func (c *StateObject) SubBalance(amount *big.Int) {
  193. if amount.Cmp(common.Big0) == 0 {
  194. return
  195. }
  196. c.SetBalance(new(big.Int).Sub(c.Balance(), amount))
  197. if glog.V(logger.Core) {
  198. glog.Infof("%x: #%d %v (- %v)\n", c.Address(), c.Nonce(), c.Balance(), amount)
  199. }
  200. }
  201. func (self *StateObject) SetBalance(amount *big.Int) {
  202. self.data.Balance = amount
  203. if self.onDirty != nil {
  204. self.onDirty(self.Address())
  205. self.onDirty = nil
  206. }
  207. }
  208. // Return the gas back to the origin. Used by the Virtual machine or Closures
  209. func (c *StateObject) ReturnGas(gas, price *big.Int) {}
  210. func (self *StateObject) Copy(db trie.Database, onDirty func(addr common.Address)) *StateObject {
  211. stateObject := NewObject(self.address, self.data, onDirty)
  212. stateObject.trie = self.trie
  213. stateObject.code = self.code
  214. stateObject.dirtyStorage = self.dirtyStorage.Copy()
  215. stateObject.cachedStorage = self.dirtyStorage.Copy()
  216. stateObject.remove = self.remove
  217. stateObject.dirtyCode = self.dirtyCode
  218. stateObject.deleted = self.deleted
  219. return stateObject
  220. }
  221. //
  222. // Attribute accessors
  223. //
  224. // Returns the address of the contract/account
  225. func (c *StateObject) Address() common.Address {
  226. return c.address
  227. }
  228. // Code returns the contract code associated with this object, if any.
  229. func (self *StateObject) Code(db trie.Database) []byte {
  230. if self.code != nil {
  231. return self.code
  232. }
  233. if bytes.Equal(self.CodeHash(), emptyCodeHash) {
  234. return nil
  235. }
  236. code, err := db.Get(self.CodeHash())
  237. if err != nil {
  238. self.setError(fmt.Errorf("can't load code hash %x: %v", self.CodeHash(), err))
  239. }
  240. self.code = code
  241. return code
  242. }
  243. func (self *StateObject) SetCode(codeHash common.Hash, code []byte) {
  244. self.code = code
  245. self.data.CodeHash = codeHash[:]
  246. self.dirtyCode = true
  247. if self.onDirty != nil {
  248. self.onDirty(self.Address())
  249. self.onDirty = nil
  250. }
  251. }
  252. func (self *StateObject) SetNonce(nonce uint64) {
  253. self.data.Nonce = nonce
  254. if self.onDirty != nil {
  255. self.onDirty(self.Address())
  256. self.onDirty = nil
  257. }
  258. }
  259. func (self *StateObject) CodeHash() []byte {
  260. return self.data.CodeHash
  261. }
  262. func (self *StateObject) Balance() *big.Int {
  263. return self.data.Balance
  264. }
  265. func (self *StateObject) Nonce() uint64 {
  266. return self.data.Nonce
  267. }
  268. // Never called, but must be present to allow StateObject to be used
  269. // as a vm.Account interface that also satisfies the vm.ContractRef
  270. // interface. Interfaces are awesome.
  271. func (self *StateObject) Value() *big.Int {
  272. panic("Value on StateObject should never be called")
  273. }
  274. func (self *StateObject) ForEachStorage(cb func(key, value common.Hash) bool) {
  275. // When iterating over the storage check the cache first
  276. for h, value := range self.cachedStorage {
  277. cb(h, value)
  278. }
  279. it := self.trie.Iterator()
  280. for it.Next() {
  281. // ignore cached values
  282. key := common.BytesToHash(self.trie.GetKey(it.Key))
  283. if _, ok := self.cachedStorage[key]; !ok {
  284. cb(key, common.BytesToHash(it.Value))
  285. }
  286. }
  287. }