state_object.go 16 KB

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