state_object.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518
  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. var err error
  137. s.trie, err = db.OpenStorageTrie(s.addrHash, s.data.Root)
  138. if err != nil {
  139. s.trie, _ = db.OpenStorageTrie(s.addrHash, common.Hash{})
  140. s.setError(fmt.Errorf("can't create storage trie: %v", err))
  141. }
  142. }
  143. return s.trie
  144. }
  145. // GetState retrieves a value from the account storage trie.
  146. func (s *stateObject) GetState(db Database, key common.Hash) common.Hash {
  147. // If the fake storage is set, only lookup the state here(in the debugging mode)
  148. if s.fakeStorage != nil {
  149. return s.fakeStorage[key]
  150. }
  151. // If we have a dirty value for this state entry, return it
  152. value, dirty := s.dirtyStorage[key]
  153. if dirty {
  154. return value
  155. }
  156. // Otherwise return the entry's original value
  157. return s.GetCommittedState(db, key)
  158. }
  159. // GetCommittedState retrieves a value from the committed account storage trie.
  160. func (s *stateObject) GetCommittedState(db Database, key common.Hash) common.Hash {
  161. // If the fake storage is set, only lookup the state here(in the debugging mode)
  162. if s.fakeStorage != nil {
  163. return s.fakeStorage[key]
  164. }
  165. // If we have a pending write or clean cached, return that
  166. if value, pending := s.pendingStorage[key]; pending {
  167. return value
  168. }
  169. if value, cached := s.originStorage[key]; cached {
  170. return value
  171. }
  172. // If no live objects are available, attempt to use snapshots
  173. var (
  174. enc []byte
  175. err error
  176. )
  177. if s.db.snap != nil {
  178. if metrics.EnabledExpensive {
  179. defer func(start time.Time) { s.db.SnapshotStorageReads += time.Since(start) }(time.Now())
  180. }
  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. enc, err = s.db.snap.Storage(s.addrHash, crypto.Keccak256Hash(key.Bytes()))
  191. }
  192. // If snapshot unavailable or reading from it failed, load from the database
  193. if s.db.snap == nil || err != nil {
  194. if metrics.EnabledExpensive {
  195. defer func(start time.Time) { s.db.StorageReads += time.Since(start) }(time.Now())
  196. }
  197. if enc, err = s.getTrie(db).TryGet(key.Bytes()); err != nil {
  198. s.setError(err)
  199. return common.Hash{}
  200. }
  201. }
  202. var value common.Hash
  203. if len(enc) > 0 {
  204. _, content, _, err := rlp.Split(enc)
  205. if err != nil {
  206. s.setError(err)
  207. }
  208. value.SetBytes(content)
  209. }
  210. s.originStorage[key] = value
  211. return value
  212. }
  213. // SetState updates a value in account storage.
  214. func (s *stateObject) SetState(db Database, key, value common.Hash) {
  215. // If the fake storage is set, put the temporary state update here.
  216. if s.fakeStorage != nil {
  217. s.fakeStorage[key] = value
  218. return
  219. }
  220. // If the new value is the same as old, don't set
  221. prev := s.GetState(db, key)
  222. if prev == value {
  223. return
  224. }
  225. // New value is different, update and journal the change
  226. s.db.journal.append(storageChange{
  227. account: &s.address,
  228. key: key,
  229. prevalue: prev,
  230. })
  231. s.setState(key, value)
  232. }
  233. // SetStorage replaces the entire state storage with the given one.
  234. //
  235. // After this function is called, all original state will be ignored and state
  236. // lookup only happens in the fake state storage.
  237. //
  238. // Note this function should only be used for debugging purpose.
  239. func (s *stateObject) SetStorage(storage map[common.Hash]common.Hash) {
  240. // Allocate fake storage if it's nil.
  241. if s.fakeStorage == nil {
  242. s.fakeStorage = make(Storage)
  243. }
  244. for key, value := range storage {
  245. s.fakeStorage[key] = value
  246. }
  247. // Don't bother journal since this function should only be used for
  248. // debugging and the `fake` storage won't be committed to database.
  249. }
  250. func (s *stateObject) setState(key, value common.Hash) {
  251. s.dirtyStorage[key] = value
  252. }
  253. // finalise moves all dirty storage slots into the pending area to be hashed or
  254. // committed later. It is invoked at the end of every transaction.
  255. func (s *stateObject) finalise() {
  256. for key, value := range s.dirtyStorage {
  257. s.pendingStorage[key] = value
  258. }
  259. if len(s.dirtyStorage) > 0 {
  260. s.dirtyStorage = make(Storage)
  261. }
  262. }
  263. // updateTrie writes cached storage modifications into the object's storage trie.
  264. // It will return nil if the trie has not been loaded and no changes have been made
  265. func (s *stateObject) updateTrie(db Database) Trie {
  266. // Make sure all dirty slots are finalized into the pending storage area
  267. s.finalise()
  268. if len(s.pendingStorage) == 0 {
  269. return s.trie
  270. }
  271. // Track the amount of time wasted on updating the storage trie
  272. if metrics.EnabledExpensive {
  273. defer func(start time.Time) { s.db.StorageUpdates += time.Since(start) }(time.Now())
  274. }
  275. // Retrieve the snapshot storage map for the object
  276. var storage map[common.Hash][]byte
  277. if s.db.snap != nil {
  278. // Retrieve the old storage map, if available, create a new one otherwise
  279. storage = s.db.snapStorage[s.addrHash]
  280. if storage == nil {
  281. storage = make(map[common.Hash][]byte)
  282. s.db.snapStorage[s.addrHash] = storage
  283. }
  284. }
  285. // Insert all the pending updates into the trie
  286. tr := s.getTrie(db)
  287. for key, value := range s.pendingStorage {
  288. // Skip noop changes, persist actual changes
  289. if value == s.originStorage[key] {
  290. continue
  291. }
  292. s.originStorage[key] = value
  293. var v []byte
  294. if (value == common.Hash{}) {
  295. s.setError(tr.TryDelete(key[:]))
  296. } else {
  297. // Encoding []byte cannot fail, ok to ignore the error.
  298. v, _ = rlp.EncodeToBytes(common.TrimLeftZeroes(value[:]))
  299. s.setError(tr.TryUpdate(key[:], v))
  300. }
  301. // If state snapshotting is active, cache the data til commit
  302. if storage != nil {
  303. storage[crypto.Keccak256Hash(key[:])] = v // v will be nil if value is 0x00
  304. }
  305. }
  306. if len(s.pendingStorage) > 0 {
  307. s.pendingStorage = make(Storage)
  308. }
  309. return tr
  310. }
  311. // UpdateRoot sets the trie root to the current root hash of
  312. func (s *stateObject) updateRoot(db Database) {
  313. // If nothing changed, don't bother with hashing anything
  314. if s.updateTrie(db) == nil {
  315. return
  316. }
  317. // Track the amount of time wasted on hashing the storage trie
  318. if metrics.EnabledExpensive {
  319. defer func(start time.Time) { s.db.StorageHashes += time.Since(start) }(time.Now())
  320. }
  321. s.data.Root = s.trie.Hash()
  322. }
  323. // CommitTrie the storage trie of the object to db.
  324. // This updates the trie root.
  325. func (s *stateObject) CommitTrie(db Database) error {
  326. // If nothing changed, don't bother with hashing anything
  327. if s.updateTrie(db) == nil {
  328. return nil
  329. }
  330. if s.dbErr != nil {
  331. return s.dbErr
  332. }
  333. // Track the amount of time wasted on committing the storage trie
  334. if metrics.EnabledExpensive {
  335. defer func(start time.Time) { s.db.StorageCommits += time.Since(start) }(time.Now())
  336. }
  337. root, err := s.trie.Commit(nil)
  338. if err == nil {
  339. s.data.Root = root
  340. }
  341. return err
  342. }
  343. // AddBalance adds amount to s's balance.
  344. // It is used to add funds to the destination account of a transfer.
  345. func (s *stateObject) AddBalance(amount *big.Int) {
  346. // EIP161: We must check emptiness for the objects such that the account
  347. // clearing (0,0,0 objects) can take effect.
  348. if amount.Sign() == 0 {
  349. if s.empty() {
  350. s.touch()
  351. }
  352. return
  353. }
  354. s.SetBalance(new(big.Int).Add(s.Balance(), amount))
  355. }
  356. // SubBalance removes amount from s's balance.
  357. // It is used to remove funds from the origin account of a transfer.
  358. func (s *stateObject) SubBalance(amount *big.Int) {
  359. if amount.Sign() == 0 {
  360. return
  361. }
  362. s.SetBalance(new(big.Int).Sub(s.Balance(), amount))
  363. }
  364. func (s *stateObject) SetBalance(amount *big.Int) {
  365. s.db.journal.append(balanceChange{
  366. account: &s.address,
  367. prev: new(big.Int).Set(s.data.Balance),
  368. })
  369. s.setBalance(amount)
  370. }
  371. func (s *stateObject) setBalance(amount *big.Int) {
  372. s.data.Balance = amount
  373. }
  374. // Return the gas back to the origin. Used by the Virtual machine or Closures
  375. func (s *stateObject) ReturnGas(gas *big.Int) {}
  376. func (s *stateObject) deepCopy(db *StateDB) *stateObject {
  377. stateObject := newObject(db, s.address, s.data)
  378. if s.trie != nil {
  379. stateObject.trie = db.db.CopyTrie(s.trie)
  380. }
  381. stateObject.code = s.code
  382. stateObject.dirtyStorage = s.dirtyStorage.Copy()
  383. stateObject.originStorage = s.originStorage.Copy()
  384. stateObject.pendingStorage = s.pendingStorage.Copy()
  385. stateObject.suicided = s.suicided
  386. stateObject.dirtyCode = s.dirtyCode
  387. stateObject.deleted = s.deleted
  388. return stateObject
  389. }
  390. //
  391. // Attribute accessors
  392. //
  393. // Returns the address of the contract/account
  394. func (s *stateObject) Address() common.Address {
  395. return s.address
  396. }
  397. // Code returns the contract code associated with this object, if any.
  398. func (s *stateObject) Code(db Database) []byte {
  399. if s.code != nil {
  400. return s.code
  401. }
  402. if bytes.Equal(s.CodeHash(), emptyCodeHash) {
  403. return nil
  404. }
  405. code, err := db.ContractCode(s.addrHash, common.BytesToHash(s.CodeHash()))
  406. if err != nil {
  407. s.setError(fmt.Errorf("can't load code hash %x: %v", s.CodeHash(), err))
  408. }
  409. s.code = code
  410. return code
  411. }
  412. // CodeSize returns the size of the contract code associated with this object,
  413. // or zero if none. This method is an almost mirror of Code, but uses a cache
  414. // inside the database to avoid loading codes seen recently.
  415. func (s *stateObject) CodeSize(db Database) int {
  416. if s.code != nil {
  417. return len(s.code)
  418. }
  419. if bytes.Equal(s.CodeHash(), emptyCodeHash) {
  420. return 0
  421. }
  422. size, err := db.ContractCodeSize(s.addrHash, common.BytesToHash(s.CodeHash()))
  423. if err != nil {
  424. s.setError(fmt.Errorf("can't load code size %x: %v", s.CodeHash(), err))
  425. }
  426. return size
  427. }
  428. func (s *stateObject) SetCode(codeHash common.Hash, code []byte) {
  429. prevcode := s.Code(s.db.db)
  430. s.db.journal.append(codeChange{
  431. account: &s.address,
  432. prevhash: s.CodeHash(),
  433. prevcode: prevcode,
  434. })
  435. s.setCode(codeHash, code)
  436. }
  437. func (s *stateObject) setCode(codeHash common.Hash, code []byte) {
  438. s.code = code
  439. s.data.CodeHash = codeHash[:]
  440. s.dirtyCode = true
  441. }
  442. func (s *stateObject) SetNonce(nonce uint64) {
  443. s.db.journal.append(nonceChange{
  444. account: &s.address,
  445. prev: s.data.Nonce,
  446. })
  447. s.setNonce(nonce)
  448. }
  449. func (s *stateObject) setNonce(nonce uint64) {
  450. s.data.Nonce = nonce
  451. }
  452. func (s *stateObject) CodeHash() []byte {
  453. return s.data.CodeHash
  454. }
  455. func (s *stateObject) Balance() *big.Int {
  456. return s.data.Balance
  457. }
  458. func (s *stateObject) Nonce() uint64 {
  459. return s.data.Nonce
  460. }
  461. // Never called, but must be present to allow stateObject to be used
  462. // as a vm.Account interface that also satisfies the vm.ContractRef
  463. // interface. Interfaces are awesome.
  464. func (s *stateObject) Value() *big.Int {
  465. panic("Value on stateObject should never be called")
  466. }