state_object.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  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, err = s.db.snap.Storage(s.addrHash, crypto.Keccak256Hash(key[:]))
  182. }
  183. // If snapshot unavailable or reading from it failed, load from the database
  184. if s.db.snap == nil || err != nil {
  185. if metrics.EnabledExpensive {
  186. defer func(start time.Time) { s.db.StorageReads += time.Since(start) }(time.Now())
  187. }
  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, create a new one otherwise
  270. storage = s.db.snapStorage[s.addrHash]
  271. if storage == nil {
  272. storage = make(map[common.Hash][]byte)
  273. s.db.snapStorage[s.addrHash] = storage
  274. }
  275. }
  276. // Insert all the pending updates into the trie
  277. tr := s.getTrie(db)
  278. for key, value := range s.pendingStorage {
  279. // Skip noop changes, persist actual changes
  280. if value == s.originStorage[key] {
  281. continue
  282. }
  283. s.originStorage[key] = value
  284. var v []byte
  285. if (value == common.Hash{}) {
  286. s.setError(tr.TryDelete(key[:]))
  287. } else {
  288. // Encoding []byte cannot fail, ok to ignore the error.
  289. v, _ = rlp.EncodeToBytes(common.TrimLeftZeroes(value[:]))
  290. s.setError(tr.TryUpdate(key[:], v))
  291. }
  292. // If state snapshotting is active, cache the data til commit
  293. if storage != nil {
  294. storage[crypto.Keccak256Hash(key[:])] = v // v will be nil if value is 0x00
  295. }
  296. }
  297. if len(s.pendingStorage) > 0 {
  298. s.pendingStorage = make(Storage)
  299. }
  300. return tr
  301. }
  302. // UpdateRoot sets the trie root to the current root hash of
  303. func (s *stateObject) updateRoot(db Database) {
  304. // If nothing changed, don't bother with hashing anything
  305. if s.updateTrie(db) == nil {
  306. return
  307. }
  308. // Track the amount of time wasted on hashing the storge trie
  309. if metrics.EnabledExpensive {
  310. defer func(start time.Time) { s.db.StorageHashes += time.Since(start) }(time.Now())
  311. }
  312. s.data.Root = s.trie.Hash()
  313. }
  314. // CommitTrie the storage trie of the object to db.
  315. // This updates the trie root.
  316. func (s *stateObject) CommitTrie(db Database) error {
  317. // If nothing changed, don't bother with hashing anything
  318. if s.updateTrie(db) == nil {
  319. return nil
  320. }
  321. if s.dbErr != nil {
  322. return s.dbErr
  323. }
  324. // Track the amount of time wasted on committing the storge trie
  325. if metrics.EnabledExpensive {
  326. defer func(start time.Time) { s.db.StorageCommits += time.Since(start) }(time.Now())
  327. }
  328. root, err := s.trie.Commit(nil)
  329. if err == nil {
  330. s.data.Root = root
  331. }
  332. return err
  333. }
  334. // AddBalance removes amount from c's balance.
  335. // It is used to add funds to the destination account of a transfer.
  336. func (s *stateObject) AddBalance(amount *big.Int) {
  337. // EIP158: We must check emptiness for the objects such that the account
  338. // clearing (0,0,0 objects) can take effect.
  339. if amount.Sign() == 0 {
  340. if s.empty() {
  341. s.touch()
  342. }
  343. return
  344. }
  345. s.SetBalance(new(big.Int).Add(s.Balance(), amount))
  346. }
  347. // SubBalance removes amount from c's balance.
  348. // It is used to remove funds from the origin account of a transfer.
  349. func (s *stateObject) SubBalance(amount *big.Int) {
  350. if amount.Sign() == 0 {
  351. return
  352. }
  353. s.SetBalance(new(big.Int).Sub(s.Balance(), amount))
  354. }
  355. func (s *stateObject) SetBalance(amount *big.Int) {
  356. s.db.journal.append(balanceChange{
  357. account: &s.address,
  358. prev: new(big.Int).Set(s.data.Balance),
  359. })
  360. s.setBalance(amount)
  361. }
  362. func (s *stateObject) setBalance(amount *big.Int) {
  363. s.data.Balance = amount
  364. }
  365. // Return the gas back to the origin. Used by the Virtual machine or Closures
  366. func (s *stateObject) ReturnGas(gas *big.Int) {}
  367. func (s *stateObject) deepCopy(db *StateDB) *stateObject {
  368. stateObject := newObject(db, s.address, s.data)
  369. if s.trie != nil {
  370. stateObject.trie = db.db.CopyTrie(s.trie)
  371. }
  372. stateObject.code = s.code
  373. stateObject.dirtyStorage = s.dirtyStorage.Copy()
  374. stateObject.originStorage = s.originStorage.Copy()
  375. stateObject.pendingStorage = s.pendingStorage.Copy()
  376. stateObject.suicided = s.suicided
  377. stateObject.dirtyCode = s.dirtyCode
  378. stateObject.deleted = s.deleted
  379. return stateObject
  380. }
  381. //
  382. // Attribute accessors
  383. //
  384. // Returns the address of the contract/account
  385. func (s *stateObject) Address() common.Address {
  386. return s.address
  387. }
  388. // Code returns the contract code associated with this object, if any.
  389. func (s *stateObject) Code(db Database) []byte {
  390. if s.code != nil {
  391. return s.code
  392. }
  393. if bytes.Equal(s.CodeHash(), emptyCodeHash) {
  394. return nil
  395. }
  396. code, err := db.ContractCode(s.addrHash, common.BytesToHash(s.CodeHash()))
  397. if err != nil {
  398. s.setError(fmt.Errorf("can't load code hash %x: %v", s.CodeHash(), err))
  399. }
  400. s.code = code
  401. return code
  402. }
  403. func (s *stateObject) SetCode(codeHash common.Hash, code []byte) {
  404. prevcode := s.Code(s.db.db)
  405. s.db.journal.append(codeChange{
  406. account: &s.address,
  407. prevhash: s.CodeHash(),
  408. prevcode: prevcode,
  409. })
  410. s.setCode(codeHash, code)
  411. }
  412. func (s *stateObject) setCode(codeHash common.Hash, code []byte) {
  413. s.code = code
  414. s.data.CodeHash = codeHash[:]
  415. s.dirtyCode = true
  416. }
  417. func (s *stateObject) SetNonce(nonce uint64) {
  418. s.db.journal.append(nonceChange{
  419. account: &s.address,
  420. prev: s.data.Nonce,
  421. })
  422. s.setNonce(nonce)
  423. }
  424. func (s *stateObject) setNonce(nonce uint64) {
  425. s.data.Nonce = nonce
  426. }
  427. func (s *stateObject) CodeHash() []byte {
  428. return s.data.CodeHash
  429. }
  430. func (s *stateObject) Balance() *big.Int {
  431. return s.data.Balance
  432. }
  433. func (s *stateObject) Nonce() uint64 {
  434. return s.data.Nonce
  435. }
  436. // Never called, but must be present to allow stateObject to be used
  437. // as a vm.Account interface that also satisfies the vm.ContractRef
  438. // interface. Interfaces are awesome.
  439. func (s *stateObject) Value() *big.Int {
  440. panic("Value on stateObject should never be called")
  441. }