state_object.go 17 KB

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