state_object.go 10 KB

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