state_object.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550
  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.GetTrie(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() {
  283. trieChanges := make([]common.Hash, 0, len(s.dirtyStorage))
  284. for key, value := range s.dirtyStorage {
  285. s.pendingStorage[key] = value
  286. trieChanges = append(trieChanges, key)
  287. }
  288. if len(trieChanges) > 0 && s.db.prefetcher != nil && s.data.Root != emptyRoot {
  289. s.db.prefetcher.PrefetchStorage(s.data.Root, trieChanges)
  290. }
  291. if len(s.dirtyStorage) > 0 {
  292. s.dirtyStorage = make(Storage)
  293. }
  294. }
  295. // updateTrie writes cached storage modifications into the object's storage trie.
  296. // It will return nil if the trie has not been loaded and no changes have been made
  297. func (s *stateObject) updateTrie(db Database) Trie {
  298. // Make sure all dirty slots are finalized into the pending storage area
  299. s.finalise()
  300. if len(s.pendingStorage) == 0 {
  301. return s.trie
  302. }
  303. // Track the amount of time wasted on updating the storage trie
  304. if metrics.EnabledExpensive {
  305. defer func(start time.Time) { s.db.StorageUpdates += time.Since(start) }(time.Now())
  306. }
  307. // The snapshot storage map for the object
  308. var storage map[common.Hash][]byte
  309. // Insert all the pending updates into the trie
  310. tr := s.getTrie(db)
  311. hasher := s.db.hasher
  312. for key, value := range s.pendingStorage {
  313. // Skip noop changes, persist actual changes
  314. if value == s.originStorage[key] {
  315. continue
  316. }
  317. s.originStorage[key] = value
  318. var v []byte
  319. if (value == common.Hash{}) {
  320. s.setError(tr.TryDelete(key[:]))
  321. } else {
  322. // Encoding []byte cannot fail, ok to ignore the error.
  323. v, _ = rlp.EncodeToBytes(common.TrimLeftZeroes(value[:]))
  324. s.setError(tr.TryUpdate(key[:], v))
  325. }
  326. // If state snapshotting is active, cache the data til commit
  327. if s.db.snap != nil {
  328. if storage == nil {
  329. // Retrieve the old storage map, if available, create a new one otherwise
  330. if storage = s.db.snapStorage[s.addrHash]; storage == nil {
  331. storage = make(map[common.Hash][]byte)
  332. s.db.snapStorage[s.addrHash] = storage
  333. }
  334. }
  335. storage[crypto.HashData(hasher, key[:])] = v // v will be nil if value is 0x00
  336. }
  337. }
  338. if len(s.pendingStorage) > 0 {
  339. s.pendingStorage = make(Storage)
  340. }
  341. return tr
  342. }
  343. // UpdateRoot sets the trie root to the current root hash of
  344. func (s *stateObject) updateRoot(db Database) {
  345. // If nothing changed, don't bother with hashing anything
  346. if s.updateTrie(db) == nil {
  347. return
  348. }
  349. // Track the amount of time wasted on hashing the storage trie
  350. if metrics.EnabledExpensive {
  351. defer func(start time.Time) { s.db.StorageHashes += time.Since(start) }(time.Now())
  352. }
  353. s.data.Root = s.trie.Hash()
  354. }
  355. // CommitTrie the storage trie of the object to db.
  356. // This updates the trie root.
  357. func (s *stateObject) CommitTrie(db Database) error {
  358. // If nothing changed, don't bother with hashing anything
  359. if s.updateTrie(db) == nil {
  360. return nil
  361. }
  362. if s.dbErr != nil {
  363. return s.dbErr
  364. }
  365. // Track the amount of time wasted on committing the storage trie
  366. if metrics.EnabledExpensive {
  367. defer func(start time.Time) { s.db.StorageCommits += time.Since(start) }(time.Now())
  368. }
  369. root, err := s.trie.Commit(nil)
  370. if err == nil {
  371. s.data.Root = root
  372. }
  373. return err
  374. }
  375. // AddBalance adds amount to s's balance.
  376. // It is used to add funds to the destination account of a transfer.
  377. func (s *stateObject) AddBalance(amount *big.Int) {
  378. // EIP161: We must check emptiness for the objects such that the account
  379. // clearing (0,0,0 objects) can take effect.
  380. if amount.Sign() == 0 {
  381. if s.empty() {
  382. s.touch()
  383. }
  384. return
  385. }
  386. s.SetBalance(new(big.Int).Add(s.Balance(), amount))
  387. }
  388. // SubBalance removes amount from s's balance.
  389. // It is used to remove funds from the origin account of a transfer.
  390. func (s *stateObject) SubBalance(amount *big.Int) {
  391. if amount.Sign() == 0 {
  392. return
  393. }
  394. s.SetBalance(new(big.Int).Sub(s.Balance(), amount))
  395. }
  396. func (s *stateObject) SetBalance(amount *big.Int) {
  397. s.db.journal.append(balanceChange{
  398. account: &s.address,
  399. prev: new(big.Int).Set(s.data.Balance),
  400. })
  401. s.setBalance(amount)
  402. }
  403. func (s *stateObject) setBalance(amount *big.Int) {
  404. s.data.Balance = amount
  405. }
  406. // Return the gas back to the origin. Used by the Virtual machine or Closures
  407. func (s *stateObject) ReturnGas(gas *big.Int) {}
  408. func (s *stateObject) deepCopy(db *StateDB) *stateObject {
  409. stateObject := newObject(db, s.address, s.data)
  410. if s.trie != nil {
  411. stateObject.trie = db.db.CopyTrie(s.trie)
  412. }
  413. stateObject.code = s.code
  414. stateObject.dirtyStorage = s.dirtyStorage.Copy()
  415. stateObject.originStorage = s.originStorage.Copy()
  416. stateObject.pendingStorage = s.pendingStorage.Copy()
  417. stateObject.suicided = s.suicided
  418. stateObject.dirtyCode = s.dirtyCode
  419. stateObject.deleted = s.deleted
  420. return stateObject
  421. }
  422. //
  423. // Attribute accessors
  424. //
  425. // Returns the address of the contract/account
  426. func (s *stateObject) Address() common.Address {
  427. return s.address
  428. }
  429. // Code returns the contract code associated with this object, if any.
  430. func (s *stateObject) Code(db Database) []byte {
  431. if s.code != nil {
  432. return s.code
  433. }
  434. if bytes.Equal(s.CodeHash(), emptyCodeHash) {
  435. return nil
  436. }
  437. code, err := db.ContractCode(s.addrHash, common.BytesToHash(s.CodeHash()))
  438. if err != nil {
  439. s.setError(fmt.Errorf("can't load code hash %x: %v", s.CodeHash(), err))
  440. }
  441. s.code = code
  442. return code
  443. }
  444. // CodeSize returns the size of the contract code associated with this object,
  445. // or zero if none. This method is an almost mirror of Code, but uses a cache
  446. // inside the database to avoid loading codes seen recently.
  447. func (s *stateObject) CodeSize(db Database) int {
  448. if s.code != nil {
  449. return len(s.code)
  450. }
  451. if bytes.Equal(s.CodeHash(), emptyCodeHash) {
  452. return 0
  453. }
  454. size, err := db.ContractCodeSize(s.addrHash, common.BytesToHash(s.CodeHash()))
  455. if err != nil {
  456. s.setError(fmt.Errorf("can't load code size %x: %v", s.CodeHash(), err))
  457. }
  458. return size
  459. }
  460. func (s *stateObject) SetCode(codeHash common.Hash, code []byte) {
  461. prevcode := s.Code(s.db.db)
  462. s.db.journal.append(codeChange{
  463. account: &s.address,
  464. prevhash: s.CodeHash(),
  465. prevcode: prevcode,
  466. })
  467. s.setCode(codeHash, code)
  468. }
  469. func (s *stateObject) setCode(codeHash common.Hash, code []byte) {
  470. s.code = code
  471. s.data.CodeHash = codeHash[:]
  472. s.dirtyCode = true
  473. }
  474. func (s *stateObject) SetNonce(nonce uint64) {
  475. s.db.journal.append(nonceChange{
  476. account: &s.address,
  477. prev: s.data.Nonce,
  478. })
  479. s.setNonce(nonce)
  480. }
  481. func (s *stateObject) setNonce(nonce uint64) {
  482. s.data.Nonce = nonce
  483. }
  484. func (s *stateObject) CodeHash() []byte {
  485. return s.data.CodeHash
  486. }
  487. func (s *stateObject) Balance() *big.Int {
  488. return s.data.Balance
  489. }
  490. func (s *stateObject) Nonce() uint64 {
  491. return s.data.Nonce
  492. }
  493. // Never called, but must be present to allow stateObject to be used
  494. // as a vm.Account interface that also satisfies the vm.ContractRef
  495. // interface. Interfaces are awesome.
  496. func (s *stateObject) Value() *big.Int {
  497. panic("Value on stateObject should never be called")
  498. }