state_object.go 14 KB

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