state_object.go 10 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/log"
  25. "github.com/ethereum/go-ethereum/rlp"
  26. "github.com/ethereum/go-ethereum/trie"
  27. )
  28. var emptyCodeHash = crypto.Keccak256(nil)
  29. type Code []byte
  30. func (self Code) String() string {
  31. return string(self) //strings.Join(Disassemble(self), " ")
  32. }
  33. type Storage map[common.Hash]common.Hash
  34. func (self Storage) String() (str string) {
  35. for key, value := range self {
  36. str += fmt.Sprintf("%X : %X\n", key, value)
  37. }
  38. return
  39. }
  40. func (self Storage) Copy() Storage {
  41. cpy := make(Storage)
  42. for key, value := range self {
  43. cpy[key] = value
  44. }
  45. return cpy
  46. }
  47. // stateObject represents an Ethereum account which is being modified.
  48. //
  49. // The usage pattern is as follows:
  50. // First you need to obtain a state object.
  51. // Account values can be accessed and modified through the object.
  52. // Finally, call CommitTrie to write the modified storage trie into a database.
  53. type stateObject struct {
  54. address common.Address // Ethereum address of this account
  55. data Account
  56. db *StateDB
  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 suicided 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. suicided bool
  73. touched 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. log.Debug("", "msg", log.Lazy{Fn: func() string {
  116. return fmt.Sprintf("%x: #%d %v X\n", self.Address(), self.Nonce(), self.Balance())
  117. }})
  118. }
  119. func (c *stateObject) touch() {
  120. c.db.journal = append(c.db.journal, touchChange{
  121. account: &c.address,
  122. prev: c.touched,
  123. })
  124. if c.onDirty != nil {
  125. c.onDirty(c.Address())
  126. c.onDirty = nil
  127. }
  128. c.touched = true
  129. }
  130. func (c *stateObject) getTrie(db trie.Database) *trie.SecureTrie {
  131. if c.trie == nil {
  132. var err error
  133. c.trie, err = trie.NewSecure(c.data.Root, db, 0)
  134. if err != nil {
  135. c.trie, _ = trie.NewSecure(common.Hash{}, db, 0)
  136. c.setError(fmt.Errorf("can't create storage trie: %v", err))
  137. }
  138. }
  139. return c.trie
  140. }
  141. // GetState returns a value in account storage.
  142. func (self *stateObject) GetState(db trie.Database, key common.Hash) common.Hash {
  143. value, exists := self.cachedStorage[key]
  144. if exists {
  145. return value
  146. }
  147. // Load from DB in case it is missing.
  148. if enc := self.getTrie(db).Get(key[:]); len(enc) > 0 {
  149. _, content, _, err := rlp.Split(enc)
  150. if err != nil {
  151. self.setError(err)
  152. }
  153. value.SetBytes(content)
  154. }
  155. if (value != common.Hash{}) {
  156. self.cachedStorage[key] = value
  157. }
  158. return value
  159. }
  160. // SetState updates a value in account storage.
  161. func (self *stateObject) SetState(db trie.Database, key, value common.Hash) {
  162. self.db.journal = append(self.db.journal, storageChange{
  163. account: &self.address,
  164. key: key,
  165. prevalue: self.GetState(db, key),
  166. })
  167. self.setState(key, value)
  168. }
  169. func (self *stateObject) setState(key, value common.Hash) {
  170. self.cachedStorage[key] = value
  171. self.dirtyStorage[key] = value
  172. if self.onDirty != nil {
  173. self.onDirty(self.Address())
  174. self.onDirty = nil
  175. }
  176. }
  177. // updateTrie writes cached storage modifications into the object's storage trie.
  178. func (self *stateObject) updateTrie(db trie.Database) {
  179. tr := self.getTrie(db)
  180. for key, value := range self.dirtyStorage {
  181. delete(self.dirtyStorage, key)
  182. if (value == common.Hash{}) {
  183. tr.Delete(key[:])
  184. continue
  185. }
  186. // Encoding []byte cannot fail, ok to ignore the error.
  187. v, _ := rlp.EncodeToBytes(bytes.TrimLeft(value[:], "\x00"))
  188. tr.Update(key[:], v)
  189. }
  190. }
  191. // UpdateRoot sets the trie root to the current root hash of
  192. func (self *stateObject) updateRoot(db trie.Database) {
  193. self.updateTrie(db)
  194. self.data.Root = self.trie.Hash()
  195. }
  196. // CommitTrie the storage trie of the object to dwb.
  197. // This updates the trie root.
  198. func (self *stateObject) CommitTrie(db trie.Database, dbw trie.DatabaseWriter) error {
  199. self.updateTrie(db)
  200. if self.dbErr != nil {
  201. return self.dbErr
  202. }
  203. root, err := self.trie.CommitTo(dbw)
  204. if err == nil {
  205. self.data.Root = root
  206. }
  207. return err
  208. }
  209. // AddBalance removes amount from c's balance.
  210. // It is used to add funds to the destination account of a transfer.
  211. func (c *stateObject) AddBalance(amount *big.Int) {
  212. // EIP158: We must check emptiness for the objects such that the account
  213. // clearing (0,0,0 objects) can take effect.
  214. if amount.Cmp(common.Big0) == 0 {
  215. if c.empty() {
  216. c.touch()
  217. }
  218. return
  219. }
  220. c.SetBalance(new(big.Int).Add(c.Balance(), amount))
  221. log.Debug("", "msg", log.Lazy{Fn: func() string {
  222. return fmt.Sprintf("%x: #%d %v (+ %v)\n", c.Address(), c.Nonce(), c.Balance(), amount)
  223. }})
  224. }
  225. // SubBalance removes amount from c's balance.
  226. // It is used to remove funds from the origin account of a transfer.
  227. func (c *stateObject) SubBalance(amount *big.Int) {
  228. if amount.Cmp(common.Big0) == 0 {
  229. return
  230. }
  231. c.SetBalance(new(big.Int).Sub(c.Balance(), amount))
  232. log.Debug("", "msg", log.Lazy{Fn: func() string {
  233. return fmt.Sprintf("%x: #%d %v (- %v)\n", c.Address(), c.Nonce(), c.Balance(), amount)
  234. }})
  235. }
  236. func (self *stateObject) SetBalance(amount *big.Int) {
  237. self.db.journal = append(self.db.journal, balanceChange{
  238. account: &self.address,
  239. prev: new(big.Int).Set(self.data.Balance),
  240. })
  241. self.setBalance(amount)
  242. }
  243. func (self *stateObject) setBalance(amount *big.Int) {
  244. self.data.Balance = amount
  245. if self.onDirty != nil {
  246. self.onDirty(self.Address())
  247. self.onDirty = nil
  248. }
  249. }
  250. // Return the gas back to the origin. Used by the Virtual machine or Closures
  251. func (c *stateObject) ReturnGas(gas *big.Int) {}
  252. func (self *stateObject) deepCopy(db *StateDB, onDirty func(addr common.Address)) *stateObject {
  253. stateObject := newObject(db, self.address, self.data, onDirty)
  254. stateObject.trie = self.trie
  255. stateObject.code = self.code
  256. stateObject.dirtyStorage = self.dirtyStorage.Copy()
  257. stateObject.cachedStorage = self.dirtyStorage.Copy()
  258. stateObject.suicided = self.suicided
  259. stateObject.dirtyCode = self.dirtyCode
  260. stateObject.deleted = self.deleted
  261. return stateObject
  262. }
  263. //
  264. // Attribute accessors
  265. //
  266. // Returns the address of the contract/account
  267. func (c *stateObject) Address() common.Address {
  268. return c.address
  269. }
  270. // Code returns the contract code associated with this object, if any.
  271. func (self *stateObject) Code(db trie.Database) []byte {
  272. if self.code != nil {
  273. return self.code
  274. }
  275. if bytes.Equal(self.CodeHash(), emptyCodeHash) {
  276. return nil
  277. }
  278. code, err := db.Get(self.CodeHash())
  279. if err != nil {
  280. self.setError(fmt.Errorf("can't load code hash %x: %v", self.CodeHash(), err))
  281. }
  282. self.code = code
  283. return code
  284. }
  285. func (self *stateObject) SetCode(codeHash common.Hash, code []byte) {
  286. prevcode := self.Code(self.db.db)
  287. self.db.journal = append(self.db.journal, codeChange{
  288. account: &self.address,
  289. prevhash: self.CodeHash(),
  290. prevcode: prevcode,
  291. })
  292. self.setCode(codeHash, code)
  293. }
  294. func (self *stateObject) setCode(codeHash common.Hash, code []byte) {
  295. self.code = code
  296. self.data.CodeHash = codeHash[:]
  297. self.dirtyCode = true
  298. if self.onDirty != nil {
  299. self.onDirty(self.Address())
  300. self.onDirty = nil
  301. }
  302. }
  303. func (self *stateObject) SetNonce(nonce uint64) {
  304. self.db.journal = append(self.db.journal, nonceChange{
  305. account: &self.address,
  306. prev: self.data.Nonce,
  307. })
  308. self.setNonce(nonce)
  309. }
  310. func (self *stateObject) setNonce(nonce uint64) {
  311. self.data.Nonce = nonce
  312. if self.onDirty != nil {
  313. self.onDirty(self.Address())
  314. self.onDirty = nil
  315. }
  316. }
  317. func (self *stateObject) CodeHash() []byte {
  318. return self.data.CodeHash
  319. }
  320. func (self *stateObject) Balance() *big.Int {
  321. return self.data.Balance
  322. }
  323. func (self *stateObject) Nonce() uint64 {
  324. return self.data.Nonce
  325. }
  326. // Never called, but must be present to allow stateObject to be used
  327. // as a vm.Account interface that also satisfies the vm.ContractRef
  328. // interface. Interfaces are awesome.
  329. func (self *stateObject) Value() *big.Int {
  330. panic("Value on stateObject should never be called")
  331. }