state_object.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  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. // It will return nil if the trie has not been loaded and no changes have been made
  245. func (s *stateObject) updateTrie(db Database) Trie {
  246. // Make sure all dirty slots are finalized into the pending storage area
  247. s.finalise()
  248. if len(s.pendingStorage) == 0 {
  249. return s.trie
  250. }
  251. // Track the amount of time wasted on updating the storge trie
  252. if metrics.EnabledExpensive {
  253. defer func(start time.Time) { s.db.StorageUpdates += time.Since(start) }(time.Now())
  254. }
  255. // Insert all the pending updates into the trie
  256. tr := s.getTrie(db)
  257. for key, value := range s.pendingStorage {
  258. // Skip noop changes, persist actual changes
  259. if value == s.originStorage[key] {
  260. continue
  261. }
  262. s.originStorage[key] = value
  263. if (value == common.Hash{}) {
  264. s.setError(tr.TryDelete(key[:]))
  265. continue
  266. }
  267. // Encoding []byte cannot fail, ok to ignore the error.
  268. v, _ := rlp.EncodeToBytes(common.TrimLeftZeroes(value[:]))
  269. s.setError(tr.TryUpdate(key[:], v))
  270. }
  271. if len(s.pendingStorage) > 0 {
  272. s.pendingStorage = make(Storage)
  273. }
  274. return tr
  275. }
  276. // UpdateRoot sets the trie root to the current root hash of
  277. func (s *stateObject) updateRoot(db Database) {
  278. // If nothing changed, don't bother with hashing anything
  279. if s.updateTrie(db) == nil {
  280. return
  281. }
  282. // Track the amount of time wasted on hashing the storge trie
  283. if metrics.EnabledExpensive {
  284. defer func(start time.Time) { s.db.StorageHashes += time.Since(start) }(time.Now())
  285. }
  286. s.data.Root = s.trie.Hash()
  287. }
  288. // CommitTrie the storage trie of the object to db.
  289. // This updates the trie root.
  290. func (s *stateObject) CommitTrie(db Database) error {
  291. // If nothing changed, don't bother with hashing anything
  292. if s.updateTrie(db) == nil {
  293. return nil
  294. }
  295. if s.dbErr != nil {
  296. return s.dbErr
  297. }
  298. // Track the amount of time wasted on committing the storge trie
  299. if metrics.EnabledExpensive {
  300. defer func(start time.Time) { s.db.StorageCommits += time.Since(start) }(time.Now())
  301. }
  302. root, err := s.trie.Commit(nil)
  303. if err == nil {
  304. s.data.Root = root
  305. }
  306. return err
  307. }
  308. // AddBalance removes amount from c's balance.
  309. // It is used to add funds to the destination account of a transfer.
  310. func (s *stateObject) AddBalance(amount *big.Int) {
  311. // EIP158: We must check emptiness for the objects such that the account
  312. // clearing (0,0,0 objects) can take effect.
  313. if amount.Sign() == 0 {
  314. if s.empty() {
  315. s.touch()
  316. }
  317. return
  318. }
  319. s.SetBalance(new(big.Int).Add(s.Balance(), amount))
  320. }
  321. // SubBalance removes amount from c's balance.
  322. // It is used to remove funds from the origin account of a transfer.
  323. func (s *stateObject) SubBalance(amount *big.Int) {
  324. if amount.Sign() == 0 {
  325. return
  326. }
  327. s.SetBalance(new(big.Int).Sub(s.Balance(), amount))
  328. }
  329. func (s *stateObject) SetBalance(amount *big.Int) {
  330. s.db.journal.append(balanceChange{
  331. account: &s.address,
  332. prev: new(big.Int).Set(s.data.Balance),
  333. })
  334. s.setBalance(amount)
  335. }
  336. func (s *stateObject) setBalance(amount *big.Int) {
  337. s.data.Balance = amount
  338. }
  339. // Return the gas back to the origin. Used by the Virtual machine or Closures
  340. func (s *stateObject) ReturnGas(gas *big.Int) {}
  341. func (s *stateObject) deepCopy(db *StateDB) *stateObject {
  342. stateObject := newObject(db, s.address, s.data)
  343. if s.trie != nil {
  344. stateObject.trie = db.db.CopyTrie(s.trie)
  345. }
  346. stateObject.code = s.code
  347. stateObject.dirtyStorage = s.dirtyStorage.Copy()
  348. stateObject.originStorage = s.originStorage.Copy()
  349. stateObject.pendingStorage = s.pendingStorage.Copy()
  350. stateObject.suicided = s.suicided
  351. stateObject.dirtyCode = s.dirtyCode
  352. stateObject.deleted = s.deleted
  353. return stateObject
  354. }
  355. //
  356. // Attribute accessors
  357. //
  358. // Returns the address of the contract/account
  359. func (s *stateObject) Address() common.Address {
  360. return s.address
  361. }
  362. // Code returns the contract code associated with this object, if any.
  363. func (s *stateObject) Code(db Database) []byte {
  364. if s.code != nil {
  365. return s.code
  366. }
  367. if bytes.Equal(s.CodeHash(), emptyCodeHash) {
  368. return nil
  369. }
  370. code, err := db.ContractCode(s.addrHash, common.BytesToHash(s.CodeHash()))
  371. if err != nil {
  372. s.setError(fmt.Errorf("can't load code hash %x: %v", s.CodeHash(), err))
  373. }
  374. s.code = code
  375. return code
  376. }
  377. func (s *stateObject) SetCode(codeHash common.Hash, code []byte) {
  378. prevcode := s.Code(s.db.db)
  379. s.db.journal.append(codeChange{
  380. account: &s.address,
  381. prevhash: s.CodeHash(),
  382. prevcode: prevcode,
  383. })
  384. s.setCode(codeHash, code)
  385. }
  386. func (s *stateObject) setCode(codeHash common.Hash, code []byte) {
  387. s.code = code
  388. s.data.CodeHash = codeHash[:]
  389. s.dirtyCode = true
  390. }
  391. func (s *stateObject) SetNonce(nonce uint64) {
  392. s.db.journal.append(nonceChange{
  393. account: &s.address,
  394. prev: s.data.Nonce,
  395. })
  396. s.setNonce(nonce)
  397. }
  398. func (s *stateObject) setNonce(nonce uint64) {
  399. s.data.Nonce = nonce
  400. }
  401. func (s *stateObject) CodeHash() []byte {
  402. return s.data.CodeHash
  403. }
  404. func (s *stateObject) Balance() *big.Int {
  405. return s.data.Balance
  406. }
  407. func (s *stateObject) Nonce() uint64 {
  408. return s.data.Nonce
  409. }
  410. // Never called, but must be present to allow stateObject to be used
  411. // as a vm.Account interface that also satisfies the vm.ContractRef
  412. // interface. Interfaces are awesome.
  413. func (s *stateObject) Value() *big.Int {
  414. panic("Value on stateObject should never be called")
  415. }