state_object.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  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. "time"
  23. "github.com/ethereum/go-ethereum/common"
  24. "github.com/ethereum/go-ethereum/crypto"
  25. "github.com/ethereum/go-ethereum/metrics"
  26. "github.com/ethereum/go-ethereum/rlp"
  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
  55. addrHash common.Hash // hash of ethereum address of the 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 // storage trie, which becomes non-nil on first access
  66. code Code // contract bytecode, which gets set when code is loaded
  67. originStorage Storage // Storage cache of original entries to dedup rewrites
  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. }
  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) *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{
  97. db: db,
  98. address: address,
  99. addrHash: crypto.Keccak256Hash(address[:]),
  100. data: data,
  101. originStorage: make(Storage),
  102. dirtyStorage: make(Storage),
  103. }
  104. }
  105. // EncodeRLP implements rlp.Encoder.
  106. func (c *stateObject) EncodeRLP(w io.Writer) error {
  107. return rlp.Encode(w, c.data)
  108. }
  109. // setError remembers the first non-nil error it is called with.
  110. func (self *stateObject) setError(err error) {
  111. if self.dbErr == nil {
  112. self.dbErr = err
  113. }
  114. }
  115. func (self *stateObject) markSuicided() {
  116. self.suicided = true
  117. }
  118. func (c *stateObject) touch() {
  119. c.db.journal.append(touchChange{
  120. account: &c.address,
  121. })
  122. if c.address == ripemd {
  123. // Explicitly put it in the dirty-cache, which is otherwise generated from
  124. // flattened journals.
  125. c.db.journal.dirty(c.address)
  126. }
  127. }
  128. func (c *stateObject) getTrie(db Database) Trie {
  129. if c.trie == nil {
  130. var err error
  131. c.trie, err = db.OpenStorageTrie(c.addrHash, c.data.Root)
  132. if err != nil {
  133. c.trie, _ = db.OpenStorageTrie(c.addrHash, common.Hash{})
  134. c.setError(fmt.Errorf("can't create storage trie: %v", err))
  135. }
  136. }
  137. return c.trie
  138. }
  139. // GetState retrieves a value from the account storage trie.
  140. func (self *stateObject) GetState(db Database, key common.Hash) common.Hash {
  141. // If we have a dirty value for this state entry, return it
  142. value, dirty := self.dirtyStorage[key]
  143. if dirty {
  144. return value
  145. }
  146. // Otherwise return the entry's original value
  147. return self.GetCommittedState(db, key)
  148. }
  149. // GetCommittedState retrieves a value from the committed account storage trie.
  150. func (self *stateObject) GetCommittedState(db Database, key common.Hash) common.Hash {
  151. // If we have the original value cached, return that
  152. value, cached := self.originStorage[key]
  153. if cached {
  154. return value
  155. }
  156. // Track the amount of time wasted on reading the storge trie
  157. if metrics.EnabledExpensive {
  158. defer func(start time.Time) { self.db.StorageReads += time.Since(start) }(time.Now())
  159. }
  160. // Otherwise load the value from the database
  161. enc, err := self.getTrie(db).TryGet(key[:])
  162. if err != nil {
  163. self.setError(err)
  164. return common.Hash{}
  165. }
  166. if len(enc) > 0 {
  167. _, content, _, err := rlp.Split(enc)
  168. if err != nil {
  169. self.setError(err)
  170. }
  171. value.SetBytes(content)
  172. }
  173. self.originStorage[key] = value
  174. return value
  175. }
  176. // SetState updates a value in account storage.
  177. func (self *stateObject) SetState(db Database, key, value common.Hash) {
  178. // If the new value is the same as old, don't set
  179. prev := self.GetState(db, key)
  180. if prev == value {
  181. return
  182. }
  183. // New value is different, update and journal the change
  184. self.db.journal.append(storageChange{
  185. account: &self.address,
  186. key: key,
  187. prevalue: prev,
  188. })
  189. self.setState(key, value)
  190. }
  191. func (self *stateObject) setState(key, value common.Hash) {
  192. self.dirtyStorage[key] = value
  193. }
  194. // updateTrie writes cached storage modifications into the object's storage trie.
  195. func (self *stateObject) updateTrie(db Database) Trie {
  196. // Track the amount of time wasted on updating the storge trie
  197. if metrics.EnabledExpensive {
  198. defer func(start time.Time) { self.db.StorageUpdates += time.Since(start) }(time.Now())
  199. }
  200. // Update all the dirty slots in the trie
  201. tr := self.getTrie(db)
  202. for key, value := range self.dirtyStorage {
  203. delete(self.dirtyStorage, key)
  204. // Skip noop changes, persist actual changes
  205. if value == self.originStorage[key] {
  206. continue
  207. }
  208. self.originStorage[key] = value
  209. if (value == common.Hash{}) {
  210. self.setError(tr.TryDelete(key[:]))
  211. continue
  212. }
  213. // Encoding []byte cannot fail, ok to ignore the error.
  214. v, _ := rlp.EncodeToBytes(bytes.TrimLeft(value[:], "\x00"))
  215. self.setError(tr.TryUpdate(key[:], v))
  216. }
  217. return tr
  218. }
  219. // UpdateRoot sets the trie root to the current root hash of
  220. func (self *stateObject) updateRoot(db Database) {
  221. self.updateTrie(db)
  222. // Track the amount of time wasted on hashing the storge trie
  223. if metrics.EnabledExpensive {
  224. defer func(start time.Time) { self.db.StorageHashes += time.Since(start) }(time.Now())
  225. }
  226. self.data.Root = self.trie.Hash()
  227. }
  228. // CommitTrie the storage trie of the object to db.
  229. // This updates the trie root.
  230. func (self *stateObject) CommitTrie(db Database) error {
  231. self.updateTrie(db)
  232. if self.dbErr != nil {
  233. return self.dbErr
  234. }
  235. // Track the amount of time wasted on committing the storge trie
  236. if metrics.EnabledExpensive {
  237. defer func(start time.Time) { self.db.StorageCommits += time.Since(start) }(time.Now())
  238. }
  239. root, err := self.trie.Commit(nil)
  240. if err == nil {
  241. self.data.Root = root
  242. }
  243. return err
  244. }
  245. // AddBalance removes amount from c's balance.
  246. // It is used to add funds to the destination account of a transfer.
  247. func (c *stateObject) AddBalance(amount *big.Int) {
  248. // EIP158: We must check emptiness for the objects such that the account
  249. // clearing (0,0,0 objects) can take effect.
  250. if amount.Sign() == 0 {
  251. if c.empty() {
  252. c.touch()
  253. }
  254. return
  255. }
  256. c.SetBalance(new(big.Int).Add(c.Balance(), amount))
  257. }
  258. // SubBalance removes amount from c's balance.
  259. // It is used to remove funds from the origin account of a transfer.
  260. func (c *stateObject) SubBalance(amount *big.Int) {
  261. if amount.Sign() == 0 {
  262. return
  263. }
  264. c.SetBalance(new(big.Int).Sub(c.Balance(), amount))
  265. }
  266. func (self *stateObject) SetBalance(amount *big.Int) {
  267. self.db.journal.append(balanceChange{
  268. account: &self.address,
  269. prev: new(big.Int).Set(self.data.Balance),
  270. })
  271. self.setBalance(amount)
  272. }
  273. func (self *stateObject) setBalance(amount *big.Int) {
  274. self.data.Balance = amount
  275. }
  276. // Return the gas back to the origin. Used by the Virtual machine or Closures
  277. func (c *stateObject) ReturnGas(gas *big.Int) {}
  278. func (self *stateObject) deepCopy(db *StateDB) *stateObject {
  279. stateObject := newObject(db, self.address, self.data)
  280. if self.trie != nil {
  281. stateObject.trie = db.db.CopyTrie(self.trie)
  282. }
  283. stateObject.code = self.code
  284. stateObject.dirtyStorage = self.dirtyStorage.Copy()
  285. stateObject.originStorage = self.originStorage.Copy()
  286. stateObject.suicided = self.suicided
  287. stateObject.dirtyCode = self.dirtyCode
  288. stateObject.deleted = self.deleted
  289. return stateObject
  290. }
  291. //
  292. // Attribute accessors
  293. //
  294. // Returns the address of the contract/account
  295. func (c *stateObject) Address() common.Address {
  296. return c.address
  297. }
  298. // Code returns the contract code associated with this object, if any.
  299. func (self *stateObject) Code(db Database) []byte {
  300. if self.code != nil {
  301. return self.code
  302. }
  303. if bytes.Equal(self.CodeHash(), emptyCodeHash) {
  304. return nil
  305. }
  306. code, err := db.ContractCode(self.addrHash, common.BytesToHash(self.CodeHash()))
  307. if err != nil {
  308. self.setError(fmt.Errorf("can't load code hash %x: %v", self.CodeHash(), err))
  309. }
  310. self.code = code
  311. return code
  312. }
  313. func (self *stateObject) SetCode(codeHash common.Hash, code []byte) {
  314. prevcode := self.Code(self.db.db)
  315. self.db.journal.append(codeChange{
  316. account: &self.address,
  317. prevhash: self.CodeHash(),
  318. prevcode: prevcode,
  319. })
  320. self.setCode(codeHash, code)
  321. }
  322. func (self *stateObject) setCode(codeHash common.Hash, code []byte) {
  323. self.code = code
  324. self.data.CodeHash = codeHash[:]
  325. self.dirtyCode = true
  326. }
  327. func (self *stateObject) SetNonce(nonce uint64) {
  328. self.db.journal.append(nonceChange{
  329. account: &self.address,
  330. prev: self.data.Nonce,
  331. })
  332. self.setNonce(nonce)
  333. }
  334. func (self *stateObject) setNonce(nonce uint64) {
  335. self.data.Nonce = nonce
  336. }
  337. func (self *stateObject) CodeHash() []byte {
  338. return self.data.CodeHash
  339. }
  340. func (self *stateObject) Balance() *big.Int {
  341. return self.data.Balance
  342. }
  343. func (self *stateObject) Nonce() uint64 {
  344. return self.data.Nonce
  345. }
  346. // Never called, but must be present to allow stateObject to be used
  347. // as a vm.Account interface that also satisfies the vm.ContractRef
  348. // interface. Interfaces are awesome.
  349. func (self *stateObject) Value() *big.Int {
  350. panic("Value on stateObject should never be called")
  351. }