state_object.go 13 KB

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