state_object.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  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 *StateDB
  58. // DB error.
  59. // State objects are used by the consensus core and VM which are
  60. // unable to deal with database-level errors. Any error that occurs
  61. // during a database read is memoized here and will eventually be returned
  62. // by StateDB.Commit.
  63. dbErr error
  64. // Write caches.
  65. trie *trie.SecureTrie // storage trie, which becomes non-nil on first access
  66. code Code // contract bytecode, which gets set when code is loaded
  67. cachedStorage Storage // Storage entry cache to avoid duplicate reads
  68. dirtyStorage Storage // Storage entries that need to be flushed to disk
  69. // Cache flags.
  70. // When an object is marked suicided it will be delete from the trie
  71. // during the "update" phase of the state transition.
  72. dirtyCode bool // true if the code was updated
  73. suicided bool
  74. deleted bool
  75. onDirty func(addr common.Address) // Callback method to mark a state object newly dirty
  76. }
  77. // empty returns whether the account is considered empty.
  78. func (s *StateObject) empty() bool {
  79. return s.data.Nonce == 0 && s.data.Balance.BitLen() == 0 && bytes.Equal(s.data.CodeHash, emptyCodeHash)
  80. }
  81. // Account is the Ethereum consensus representation of accounts.
  82. // These objects are stored in the main account trie.
  83. type Account struct {
  84. Nonce uint64
  85. Balance *big.Int
  86. Root common.Hash // merkle root of the storage trie
  87. CodeHash []byte
  88. }
  89. // newObject creates a state object.
  90. func newObject(db *StateDB, address common.Address, data Account, onDirty func(addr common.Address)) *StateObject {
  91. if data.Balance == nil {
  92. data.Balance = new(big.Int)
  93. }
  94. if data.CodeHash == nil {
  95. data.CodeHash = emptyCodeHash
  96. }
  97. return &StateObject{db: db, address: address, data: data, cachedStorage: make(Storage), dirtyStorage: make(Storage), onDirty: onDirty}
  98. }
  99. // EncodeRLP implements rlp.Encoder.
  100. func (c *StateObject) EncodeRLP(w io.Writer) error {
  101. return rlp.Encode(w, c.data)
  102. }
  103. // setError remembers the first non-nil error it is called with.
  104. func (self *StateObject) setError(err error) {
  105. if self.dbErr == nil {
  106. self.dbErr = err
  107. }
  108. }
  109. func (self *StateObject) markSuicided() {
  110. self.suicided = true
  111. if self.onDirty != nil {
  112. self.onDirty(self.Address())
  113. self.onDirty = nil
  114. }
  115. if glog.V(logger.Core) {
  116. glog.Infof("%x: #%d %v X\n", self.Address(), self.Nonce(), self.Balance())
  117. }
  118. }
  119. func (c *StateObject) getTrie(db trie.Database) *trie.SecureTrie {
  120. if c.trie == nil {
  121. var err error
  122. c.trie, err = trie.NewSecure(c.data.Root, db, 0)
  123. if err != nil {
  124. c.trie, _ = trie.NewSecure(common.Hash{}, db, 0)
  125. c.setError(fmt.Errorf("can't create storage trie: %v", err))
  126. }
  127. }
  128. return c.trie
  129. }
  130. // GetState returns a value in account storage.
  131. func (self *StateObject) GetState(db trie.Database, key common.Hash) common.Hash {
  132. value, exists := self.cachedStorage[key]
  133. if exists {
  134. return value
  135. }
  136. // Load from DB in case it is missing.
  137. if enc := self.getTrie(db).Get(key[:]); len(enc) > 0 {
  138. _, content, _, err := rlp.Split(enc)
  139. if err != nil {
  140. self.setError(err)
  141. }
  142. value.SetBytes(content)
  143. }
  144. if (value != common.Hash{}) {
  145. self.cachedStorage[key] = value
  146. }
  147. return value
  148. }
  149. // SetState updates a value in account storage.
  150. func (self *StateObject) SetState(db trie.Database, key, value common.Hash) {
  151. self.db.journal = append(self.db.journal, storageChange{
  152. account: &self.address,
  153. key: key,
  154. prevalue: self.GetState(db, key),
  155. })
  156. self.setState(key, value)
  157. }
  158. func (self *StateObject) setState(key, value common.Hash) {
  159. self.cachedStorage[key] = value
  160. self.dirtyStorage[key] = value
  161. if self.onDirty != nil {
  162. self.onDirty(self.Address())
  163. self.onDirty = nil
  164. }
  165. }
  166. // updateTrie writes cached storage modifications into the object's storage trie.
  167. func (self *StateObject) updateTrie(db trie.Database) {
  168. tr := self.getTrie(db)
  169. for key, value := range self.dirtyStorage {
  170. delete(self.dirtyStorage, key)
  171. if (value == common.Hash{}) {
  172. tr.Delete(key[:])
  173. continue
  174. }
  175. // Encoding []byte cannot fail, ok to ignore the error.
  176. v, _ := rlp.EncodeToBytes(bytes.TrimLeft(value[:], "\x00"))
  177. tr.Update(key[:], v)
  178. }
  179. }
  180. // UpdateRoot sets the trie root to the current root hash of
  181. func (self *StateObject) updateRoot(db trie.Database) {
  182. self.updateTrie(db)
  183. self.data.Root = self.trie.Hash()
  184. }
  185. // CommitTrie the storage trie of the object to dwb.
  186. // This updates the trie root.
  187. func (self *StateObject) CommitTrie(db trie.Database, dbw trie.DatabaseWriter) error {
  188. self.updateTrie(db)
  189. if self.dbErr != nil {
  190. return self.dbErr
  191. }
  192. root, err := self.trie.CommitTo(dbw)
  193. if err == nil {
  194. self.data.Root = root
  195. }
  196. return err
  197. }
  198. // AddBalance removes amount from c's balance.
  199. // It is used to add funds to the destination account of a transfer.
  200. func (c *StateObject) AddBalance(amount *big.Int) {
  201. // EIP158: We must check emptiness for the objects such that the account
  202. // clearing (0,0,0 objects) can take effect.
  203. if amount.Cmp(common.Big0) == 0 && !c.empty() {
  204. return
  205. }
  206. c.SetBalance(new(big.Int).Add(c.Balance(), amount))
  207. if glog.V(logger.Core) {
  208. glog.Infof("%x: #%d %v (+ %v)\n", c.Address(), c.Nonce(), c.Balance(), amount)
  209. }
  210. }
  211. // SubBalance removes amount from c's balance.
  212. // It is used to remove funds from the origin account of a transfer.
  213. func (c *StateObject) SubBalance(amount *big.Int) {
  214. if amount.Cmp(common.Big0) == 0 {
  215. return
  216. }
  217. c.SetBalance(new(big.Int).Sub(c.Balance(), amount))
  218. if glog.V(logger.Core) {
  219. glog.Infof("%x: #%d %v (- %v)\n", c.Address(), c.Nonce(), c.Balance(), amount)
  220. }
  221. }
  222. func (self *StateObject) SetBalance(amount *big.Int) {
  223. self.db.journal = append(self.db.journal, balanceChange{
  224. account: &self.address,
  225. prev: new(big.Int).Set(self.data.Balance),
  226. })
  227. self.setBalance(amount)
  228. }
  229. func (self *StateObject) setBalance(amount *big.Int) {
  230. self.data.Balance = amount
  231. if self.onDirty != nil {
  232. self.onDirty(self.Address())
  233. self.onDirty = nil
  234. }
  235. }
  236. // Return the gas back to the origin. Used by the Virtual machine or Closures
  237. func (c *StateObject) ReturnGas(gas, price *big.Int) {}
  238. func (self *StateObject) deepCopy(db *StateDB, onDirty func(addr common.Address)) *StateObject {
  239. stateObject := newObject(db, self.address, self.data, onDirty)
  240. stateObject.trie = self.trie
  241. stateObject.code = self.code
  242. stateObject.dirtyStorage = self.dirtyStorage.Copy()
  243. stateObject.cachedStorage = self.dirtyStorage.Copy()
  244. stateObject.suicided = self.suicided
  245. stateObject.dirtyCode = self.dirtyCode
  246. stateObject.deleted = self.deleted
  247. return stateObject
  248. }
  249. //
  250. // Attribute accessors
  251. //
  252. // Returns the address of the contract/account
  253. func (c *StateObject) Address() common.Address {
  254. return c.address
  255. }
  256. // Code returns the contract code associated with this object, if any.
  257. func (self *StateObject) Code(db trie.Database) []byte {
  258. if self.code != nil {
  259. return self.code
  260. }
  261. if bytes.Equal(self.CodeHash(), emptyCodeHash) {
  262. return nil
  263. }
  264. code, err := db.Get(self.CodeHash())
  265. if err != nil {
  266. self.setError(fmt.Errorf("can't load code hash %x: %v", self.CodeHash(), err))
  267. }
  268. self.code = code
  269. return code
  270. }
  271. func (self *StateObject) SetCode(codeHash common.Hash, code []byte) {
  272. prevcode := self.Code(self.db.db)
  273. self.db.journal = append(self.db.journal, codeChange{
  274. account: &self.address,
  275. prevhash: self.CodeHash(),
  276. prevcode: prevcode,
  277. })
  278. self.setCode(codeHash, code)
  279. }
  280. func (self *StateObject) setCode(codeHash common.Hash, code []byte) {
  281. self.code = code
  282. self.data.CodeHash = codeHash[:]
  283. self.dirtyCode = true
  284. if self.onDirty != nil {
  285. self.onDirty(self.Address())
  286. self.onDirty = nil
  287. }
  288. }
  289. func (self *StateObject) SetNonce(nonce uint64) {
  290. self.db.journal = append(self.db.journal, nonceChange{
  291. account: &self.address,
  292. prev: self.data.Nonce,
  293. })
  294. self.setNonce(nonce)
  295. }
  296. func (self *StateObject) setNonce(nonce uint64) {
  297. self.data.Nonce = nonce
  298. if self.onDirty != nil {
  299. self.onDirty(self.Address())
  300. self.onDirty = nil
  301. }
  302. }
  303. func (self *StateObject) CodeHash() []byte {
  304. return self.data.CodeHash
  305. }
  306. func (self *StateObject) Balance() *big.Int {
  307. return self.data.Balance
  308. }
  309. func (self *StateObject) Nonce() uint64 {
  310. return self.data.Nonce
  311. }
  312. // Never called, but must be present to allow StateObject to be used
  313. // as a vm.Account interface that also satisfies the vm.ContractRef
  314. // interface. Interfaces are awesome.
  315. func (self *StateObject) Value() *big.Int {
  316. panic("Value on StateObject should never be called")
  317. }
  318. func (self *StateObject) ForEachStorage(cb func(key, value common.Hash) bool) {
  319. // When iterating over the storage check the cache first
  320. for h, value := range self.cachedStorage {
  321. cb(h, value)
  322. }
  323. it := self.getTrie(self.db.db).Iterator()
  324. for it.Next() {
  325. // ignore cached values
  326. key := common.BytesToHash(self.trie.GetKey(it.Key))
  327. if _, ok := self.cachedStorage[key]; !ok {
  328. cb(key, common.BytesToHash(it.Value))
  329. }
  330. }
  331. }