state_object.go 8.8 KB

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