state_object.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558
  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 (c Code) String() string {
  31. return string(c) //strings.Join(Disassemble(c), " ")
  32. }
  33. type Storage map[common.Hash]common.Hash
  34. func (s Storage) String() (str string) {
  35. for key, value := range s {
  36. str += fmt.Sprintf("%X : %X\n", key, value)
  37. }
  38. return
  39. }
  40. func (s Storage) Copy() Storage {
  41. cpy := make(Storage)
  42. for key, value := range s {
  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, reset for every transaction
  68. pendingStorage Storage // Storage entries that need to be flushed to disk, at the end of an entire block
  69. dirtyStorage Storage // Storage entries that have been modified in the current transaction execution
  70. fakeStorage Storage // Fake storage which constructed by caller for debugging purpose.
  71. // Cache flags.
  72. // When an object is marked suicided it will be delete from the trie
  73. // during the "update" phase of the state transition.
  74. dirtyCode bool // true if the code was updated
  75. suicided bool
  76. deleted bool
  77. }
  78. // empty returns whether the account is considered empty.
  79. func (s *stateObject) empty() bool {
  80. return s.data.Nonce == 0 && s.data.Balance.Sign() == 0 && bytes.Equal(s.data.CodeHash, emptyCodeHash)
  81. }
  82. // Account is the Ethereum consensus representation of accounts.
  83. // These objects are stored in the main account trie.
  84. type Account struct {
  85. Nonce uint64
  86. Balance *big.Int
  87. Root common.Hash // merkle root of the storage trie
  88. CodeHash []byte
  89. }
  90. // newObject creates a state object.
  91. func newObject(db *StateDB, address common.Address, data Account) *stateObject {
  92. if data.Balance == nil {
  93. data.Balance = new(big.Int)
  94. }
  95. if data.CodeHash == nil {
  96. data.CodeHash = emptyCodeHash
  97. }
  98. if data.Root == (common.Hash{}) {
  99. data.Root = emptyRoot
  100. }
  101. return &stateObject{
  102. db: db,
  103. address: address,
  104. addrHash: crypto.Keccak256Hash(address[:]),
  105. data: data,
  106. originStorage: make(Storage),
  107. pendingStorage: make(Storage),
  108. dirtyStorage: make(Storage),
  109. }
  110. }
  111. // EncodeRLP implements rlp.Encoder.
  112. func (s *stateObject) EncodeRLP(w io.Writer) error {
  113. return rlp.Encode(w, s.data)
  114. }
  115. // setError remembers the first non-nil error it is called with.
  116. func (s *stateObject) setError(err error) {
  117. if s.dbErr == nil {
  118. s.dbErr = err
  119. }
  120. }
  121. func (s *stateObject) markSuicided() {
  122. s.suicided = true
  123. }
  124. func (s *stateObject) touch() {
  125. s.db.journal.append(touchChange{
  126. account: &s.address,
  127. })
  128. if s.address == ripemd {
  129. // Explicitly put it in the dirty-cache, which is otherwise generated from
  130. // flattened journals.
  131. s.db.journal.dirty(s.address)
  132. }
  133. }
  134. func (s *stateObject) getTrie(db Database) Trie {
  135. if s.trie == nil {
  136. // Try fetching from prefetcher first
  137. // We don't prefetch empty tries
  138. if s.data.Root != emptyRoot && s.db.prefetcher != nil {
  139. // When the miner is creating the pending state, there is no
  140. // prefetcher
  141. s.trie = s.db.prefetcher.trie(s.data.Root)
  142. }
  143. if s.trie == nil {
  144. var err error
  145. s.trie, err = db.OpenStorageTrie(s.addrHash, s.data.Root)
  146. if err != nil {
  147. s.trie, _ = db.OpenStorageTrie(s.addrHash, common.Hash{})
  148. s.setError(fmt.Errorf("can't create storage trie: %v", err))
  149. }
  150. }
  151. }
  152. return s.trie
  153. }
  154. // GetState retrieves a value from the account storage trie.
  155. func (s *stateObject) GetState(db Database, key common.Hash) common.Hash {
  156. // If the fake storage is set, only lookup the state here(in the debugging mode)
  157. if s.fakeStorage != nil {
  158. return s.fakeStorage[key]
  159. }
  160. // If we have a dirty value for this state entry, return it
  161. value, dirty := s.dirtyStorage[key]
  162. if dirty {
  163. return value
  164. }
  165. // Otherwise return the entry's original value
  166. return s.GetCommittedState(db, key)
  167. }
  168. // GetCommittedState retrieves a value from the committed account storage trie.
  169. func (s *stateObject) GetCommittedState(db Database, key common.Hash) common.Hash {
  170. // If the fake storage is set, only lookup the state here(in the debugging mode)
  171. if s.fakeStorage != nil {
  172. return s.fakeStorage[key]
  173. }
  174. // If we have a pending write or clean cached, return that
  175. if value, pending := s.pendingStorage[key]; pending {
  176. return value
  177. }
  178. if value, cached := s.originStorage[key]; cached {
  179. return value
  180. }
  181. // If no live objects are available, attempt to use snapshots
  182. var (
  183. enc []byte
  184. err error
  185. meter *time.Duration
  186. )
  187. readStart := time.Now()
  188. if metrics.EnabledExpensive {
  189. // If the snap is 'under construction', the first lookup may fail. If that
  190. // happens, we don't want to double-count the time elapsed. Thus this
  191. // dance with the metering.
  192. defer func() {
  193. if meter != nil {
  194. *meter += time.Since(readStart)
  195. }
  196. }()
  197. }
  198. if s.db.snap != nil {
  199. if metrics.EnabledExpensive {
  200. meter = &s.db.SnapshotStorageReads
  201. }
  202. // If the object was destructed in *this* block (and potentially resurrected),
  203. // the storage has been cleared out, and we should *not* consult the previous
  204. // snapshot about any storage values. The only possible alternatives are:
  205. // 1) resurrect happened, and new slot values were set -- those should
  206. // have been handles via pendingStorage above.
  207. // 2) we don't have new values, and can deliver empty response back
  208. if _, destructed := s.db.snapDestructs[s.addrHash]; destructed {
  209. return common.Hash{}
  210. }
  211. enc, err = s.db.snap.Storage(s.addrHash, crypto.Keccak256Hash(key.Bytes()))
  212. }
  213. // If snapshot unavailable or reading from it failed, load from the database
  214. if s.db.snap == nil || err != nil {
  215. if meter != nil {
  216. // If we already spent time checking the snapshot, account for it
  217. // and reset the readStart
  218. *meter += time.Since(readStart)
  219. readStart = time.Now()
  220. }
  221. if metrics.EnabledExpensive {
  222. meter = &s.db.StorageReads
  223. }
  224. if enc, err = s.getTrie(db).TryGet(key.Bytes()); err != nil {
  225. s.setError(err)
  226. return common.Hash{}
  227. }
  228. }
  229. var value common.Hash
  230. if len(enc) > 0 {
  231. _, content, _, err := rlp.Split(enc)
  232. if err != nil {
  233. s.setError(err)
  234. }
  235. value.SetBytes(content)
  236. }
  237. s.originStorage[key] = value
  238. return value
  239. }
  240. // SetState updates a value in account storage.
  241. func (s *stateObject) SetState(db Database, key, value common.Hash) {
  242. // If the fake storage is set, put the temporary state update here.
  243. if s.fakeStorage != nil {
  244. s.fakeStorage[key] = value
  245. return
  246. }
  247. // If the new value is the same as old, don't set
  248. prev := s.GetState(db, key)
  249. if prev == value {
  250. return
  251. }
  252. // New value is different, update and journal the change
  253. s.db.journal.append(storageChange{
  254. account: &s.address,
  255. key: key,
  256. prevalue: prev,
  257. })
  258. s.setState(key, value)
  259. }
  260. // SetStorage replaces the entire state storage with the given one.
  261. //
  262. // After this function is called, all original state will be ignored and state
  263. // lookup only happens in the fake state storage.
  264. //
  265. // Note this function should only be used for debugging purpose.
  266. func (s *stateObject) SetStorage(storage map[common.Hash]common.Hash) {
  267. // Allocate fake storage if it's nil.
  268. if s.fakeStorage == nil {
  269. s.fakeStorage = make(Storage)
  270. }
  271. for key, value := range storage {
  272. s.fakeStorage[key] = value
  273. }
  274. // Don't bother journal since this function should only be used for
  275. // debugging and the `fake` storage won't be committed to database.
  276. }
  277. func (s *stateObject) setState(key, value common.Hash) {
  278. s.dirtyStorage[key] = value
  279. }
  280. // finalise moves all dirty storage slots into the pending area to be hashed or
  281. // committed later. It is invoked at the end of every transaction.
  282. func (s *stateObject) finalise(prefetch bool) {
  283. slotsToPrefetch := make([][]byte, 0, len(s.dirtyStorage))
  284. for key, value := range s.dirtyStorage {
  285. s.pendingStorage[key] = value
  286. if value != s.originStorage[key] {
  287. slotsToPrefetch = append(slotsToPrefetch, common.CopyBytes(key[:])) // Copy needed for closure
  288. }
  289. }
  290. if s.db.prefetcher != nil && prefetch && len(slotsToPrefetch) > 0 && s.data.Root != emptyRoot {
  291. s.db.prefetcher.prefetch(s.data.Root, slotsToPrefetch)
  292. }
  293. if len(s.dirtyStorage) > 0 {
  294. s.dirtyStorage = make(Storage)
  295. }
  296. }
  297. // updateTrie writes cached storage modifications into the object's storage trie.
  298. // It will return nil if the trie has not been loaded and no changes have been made
  299. func (s *stateObject) updateTrie(db Database) Trie {
  300. // Make sure all dirty slots are finalized into the pending storage area
  301. s.finalise(false) // Don't prefetch any more, pull directly if need be
  302. if len(s.pendingStorage) == 0 {
  303. return s.trie
  304. }
  305. // Track the amount of time wasted on updating the storage trie
  306. if metrics.EnabledExpensive {
  307. defer func(start time.Time) { s.db.StorageUpdates += time.Since(start) }(time.Now())
  308. }
  309. // The snapshot storage map for the object
  310. var storage map[common.Hash][]byte
  311. // Insert all the pending updates into the trie
  312. tr := s.getTrie(db)
  313. hasher := s.db.hasher
  314. usedStorage := make([][]byte, 0, len(s.pendingStorage))
  315. for key, value := range s.pendingStorage {
  316. // Skip noop changes, persist actual changes
  317. if value == s.originStorage[key] {
  318. continue
  319. }
  320. s.originStorage[key] = value
  321. var v []byte
  322. if (value == common.Hash{}) {
  323. s.setError(tr.TryDelete(key[:]))
  324. } else {
  325. // Encoding []byte cannot fail, ok to ignore the error.
  326. v, _ = rlp.EncodeToBytes(common.TrimLeftZeroes(value[:]))
  327. s.setError(tr.TryUpdate(key[:], v))
  328. }
  329. // If state snapshotting is active, cache the data til commit
  330. if s.db.snap != nil {
  331. if storage == nil {
  332. // Retrieve the old storage map, if available, create a new one otherwise
  333. if storage = s.db.snapStorage[s.addrHash]; storage == nil {
  334. storage = make(map[common.Hash][]byte)
  335. s.db.snapStorage[s.addrHash] = storage
  336. }
  337. }
  338. storage[crypto.HashData(hasher, key[:])] = v // v will be nil if value is 0x00
  339. }
  340. usedStorage = append(usedStorage, common.CopyBytes(key[:])) // Copy needed for closure
  341. }
  342. if s.db.prefetcher != nil {
  343. s.db.prefetcher.used(s.data.Root, usedStorage)
  344. }
  345. if len(s.pendingStorage) > 0 {
  346. s.pendingStorage = make(Storage)
  347. }
  348. return tr
  349. }
  350. // UpdateRoot sets the trie root to the current root hash of
  351. func (s *stateObject) updateRoot(db Database) {
  352. // If nothing changed, don't bother with hashing anything
  353. if s.updateTrie(db) == nil {
  354. return
  355. }
  356. // Track the amount of time wasted on hashing the storage trie
  357. if metrics.EnabledExpensive {
  358. defer func(start time.Time) { s.db.StorageHashes += time.Since(start) }(time.Now())
  359. }
  360. s.data.Root = s.trie.Hash()
  361. }
  362. // CommitTrie the storage trie of the object to db.
  363. // This updates the trie root.
  364. func (s *stateObject) CommitTrie(db Database) error {
  365. // If nothing changed, don't bother with hashing anything
  366. if s.updateTrie(db) == nil {
  367. return nil
  368. }
  369. if s.dbErr != nil {
  370. return s.dbErr
  371. }
  372. // Track the amount of time wasted on committing the storage trie
  373. if metrics.EnabledExpensive {
  374. defer func(start time.Time) { s.db.StorageCommits += time.Since(start) }(time.Now())
  375. }
  376. root, err := s.trie.Commit(nil)
  377. if err == nil {
  378. s.data.Root = root
  379. }
  380. return err
  381. }
  382. // AddBalance adds amount to s's balance.
  383. // It is used to add funds to the destination account of a transfer.
  384. func (s *stateObject) AddBalance(amount *big.Int) {
  385. // EIP161: We must check emptiness for the objects such that the account
  386. // clearing (0,0,0 objects) can take effect.
  387. if amount.Sign() == 0 {
  388. if s.empty() {
  389. s.touch()
  390. }
  391. return
  392. }
  393. s.SetBalance(new(big.Int).Add(s.Balance(), amount))
  394. }
  395. // SubBalance removes amount from s's balance.
  396. // It is used to remove funds from the origin account of a transfer.
  397. func (s *stateObject) SubBalance(amount *big.Int) {
  398. if amount.Sign() == 0 {
  399. return
  400. }
  401. s.SetBalance(new(big.Int).Sub(s.Balance(), amount))
  402. }
  403. func (s *stateObject) SetBalance(amount *big.Int) {
  404. s.db.journal.append(balanceChange{
  405. account: &s.address,
  406. prev: new(big.Int).Set(s.data.Balance),
  407. })
  408. s.setBalance(amount)
  409. }
  410. func (s *stateObject) setBalance(amount *big.Int) {
  411. s.data.Balance = amount
  412. }
  413. // Return the gas back to the origin. Used by the Virtual machine or Closures
  414. func (s *stateObject) ReturnGas(gas *big.Int) {}
  415. func (s *stateObject) deepCopy(db *StateDB) *stateObject {
  416. stateObject := newObject(db, s.address, s.data)
  417. if s.trie != nil {
  418. stateObject.trie = db.db.CopyTrie(s.trie)
  419. }
  420. stateObject.code = s.code
  421. stateObject.dirtyStorage = s.dirtyStorage.Copy()
  422. stateObject.originStorage = s.originStorage.Copy()
  423. stateObject.pendingStorage = s.pendingStorage.Copy()
  424. stateObject.suicided = s.suicided
  425. stateObject.dirtyCode = s.dirtyCode
  426. stateObject.deleted = s.deleted
  427. return stateObject
  428. }
  429. //
  430. // Attribute accessors
  431. //
  432. // Returns the address of the contract/account
  433. func (s *stateObject) Address() common.Address {
  434. return s.address
  435. }
  436. // Code returns the contract code associated with this object, if any.
  437. func (s *stateObject) Code(db Database) []byte {
  438. if s.code != nil {
  439. return s.code
  440. }
  441. if bytes.Equal(s.CodeHash(), emptyCodeHash) {
  442. return nil
  443. }
  444. code, err := db.ContractCode(s.addrHash, common.BytesToHash(s.CodeHash()))
  445. if err != nil {
  446. s.setError(fmt.Errorf("can't load code hash %x: %v", s.CodeHash(), err))
  447. }
  448. s.code = code
  449. return code
  450. }
  451. // CodeSize returns the size of the contract code associated with this object,
  452. // or zero if none. This method is an almost mirror of Code, but uses a cache
  453. // inside the database to avoid loading codes seen recently.
  454. func (s *stateObject) CodeSize(db Database) int {
  455. if s.code != nil {
  456. return len(s.code)
  457. }
  458. if bytes.Equal(s.CodeHash(), emptyCodeHash) {
  459. return 0
  460. }
  461. size, err := db.ContractCodeSize(s.addrHash, common.BytesToHash(s.CodeHash()))
  462. if err != nil {
  463. s.setError(fmt.Errorf("can't load code size %x: %v", s.CodeHash(), err))
  464. }
  465. return size
  466. }
  467. func (s *stateObject) SetCode(codeHash common.Hash, code []byte) {
  468. prevcode := s.Code(s.db.db)
  469. s.db.journal.append(codeChange{
  470. account: &s.address,
  471. prevhash: s.CodeHash(),
  472. prevcode: prevcode,
  473. })
  474. s.setCode(codeHash, code)
  475. }
  476. func (s *stateObject) setCode(codeHash common.Hash, code []byte) {
  477. s.code = code
  478. s.data.CodeHash = codeHash[:]
  479. s.dirtyCode = true
  480. }
  481. func (s *stateObject) SetNonce(nonce uint64) {
  482. s.db.journal.append(nonceChange{
  483. account: &s.address,
  484. prev: s.data.Nonce,
  485. })
  486. s.setNonce(nonce)
  487. }
  488. func (s *stateObject) setNonce(nonce uint64) {
  489. s.data.Nonce = nonce
  490. }
  491. func (s *stateObject) CodeHash() []byte {
  492. return s.data.CodeHash
  493. }
  494. func (s *stateObject) Balance() *big.Int {
  495. return s.data.Balance
  496. }
  497. func (s *stateObject) Nonce() uint64 {
  498. return s.data.Nonce
  499. }
  500. // Never called, but must be present to allow stateObject to be used
  501. // as a vm.Account interface that also satisfies the vm.ContractRef
  502. // interface. Interfaces are awesome.
  503. func (s *stateObject) Value() *big.Int {
  504. panic("Value on stateObject should never be called")
  505. }