state_object.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  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
  68. dirtyStorage Storage // Storage entries that need to be flushed to disk
  69. fakeStorage Storage // Fake storage which constructed by caller for debugging purpose.
  70. // Cache flags.
  71. // When an object is marked suicided it will be delete from the trie
  72. // during the "update" phase of the state transition.
  73. dirtyCode bool // true if the code was updated
  74. suicided bool
  75. deleted bool
  76. }
  77. // empty returns whether the account is considered empty.
  78. func (s *stateObject) empty() bool {
  79. return s.data.Nonce == 0 && s.data.Balance.Sign() == 0 && bytes.Equal(s.data.CodeHash, emptyCodeHash)
  80. }
  81. // Account is the Ethereum consensus representation of accounts.
  82. // These objects are stored in the main account trie.
  83. type Account struct {
  84. Nonce uint64
  85. Balance *big.Int
  86. Root common.Hash // merkle root of the storage trie
  87. CodeHash []byte
  88. }
  89. // newObject creates a state object.
  90. func newObject(db *StateDB, address common.Address, data Account) *stateObject {
  91. if data.Balance == nil {
  92. data.Balance = new(big.Int)
  93. }
  94. if data.CodeHash == nil {
  95. data.CodeHash = emptyCodeHash
  96. }
  97. return &stateObject{
  98. db: db,
  99. address: address,
  100. addrHash: crypto.Keccak256Hash(address[:]),
  101. data: data,
  102. originStorage: make(Storage),
  103. dirtyStorage: make(Storage),
  104. }
  105. }
  106. // EncodeRLP implements rlp.Encoder.
  107. func (s *stateObject) EncodeRLP(w io.Writer) error {
  108. return rlp.Encode(w, s.data)
  109. }
  110. // setError remembers the first non-nil error it is called with.
  111. func (s *stateObject) setError(err error) {
  112. if s.dbErr == nil {
  113. s.dbErr = err
  114. }
  115. }
  116. func (s *stateObject) markSuicided() {
  117. s.suicided = true
  118. }
  119. func (s *stateObject) touch() {
  120. s.db.journal.append(touchChange{
  121. account: &s.address,
  122. })
  123. if s.address == ripemd {
  124. // Explicitly put it in the dirty-cache, which is otherwise generated from
  125. // flattened journals.
  126. s.db.journal.dirty(s.address)
  127. }
  128. }
  129. func (s *stateObject) getTrie(db Database) Trie {
  130. if s.trie == nil {
  131. var err error
  132. s.trie, err = db.OpenStorageTrie(s.addrHash, s.data.Root)
  133. if err != nil {
  134. s.trie, _ = db.OpenStorageTrie(s.addrHash, common.Hash{})
  135. s.setError(fmt.Errorf("can't create storage trie: %v", err))
  136. }
  137. }
  138. return s.trie
  139. }
  140. // GetState retrieves a value from the account storage trie.
  141. func (s *stateObject) GetState(db Database, key common.Hash) common.Hash {
  142. // If the fake storage is set, only lookup the state here(in the debugging mode)
  143. if s.fakeStorage != nil {
  144. return s.fakeStorage[key]
  145. }
  146. // If we have a dirty value for this state entry, return it
  147. value, dirty := s.dirtyStorage[key]
  148. if dirty {
  149. return value
  150. }
  151. // Otherwise return the entry's original value
  152. return s.GetCommittedState(db, key)
  153. }
  154. // GetCommittedState retrieves a value from the committed account storage trie.
  155. func (s *stateObject) GetCommittedState(db Database, key common.Hash) common.Hash {
  156. // If the fake storage is set, only lookup the state here(in the debugging mode)
  157. if s.fakeStorage != nil {
  158. return s.fakeStorage[key]
  159. }
  160. // If we have the original value cached, return that
  161. value, cached := s.originStorage[key]
  162. if cached {
  163. return value
  164. }
  165. // Track the amount of time wasted on reading the storage trie
  166. if metrics.EnabledExpensive {
  167. defer func(start time.Time) { s.db.StorageReads += time.Since(start) }(time.Now())
  168. }
  169. // Otherwise load the value from the database
  170. enc, err := s.getTrie(db).TryGet(key[:])
  171. if err != nil {
  172. s.setError(err)
  173. return common.Hash{}
  174. }
  175. if len(enc) > 0 {
  176. _, content, _, err := rlp.Split(enc)
  177. if err != nil {
  178. s.setError(err)
  179. }
  180. value.SetBytes(content)
  181. }
  182. s.originStorage[key] = value
  183. return value
  184. }
  185. // SetState updates a value in account storage.
  186. func (s *stateObject) SetState(db Database, key, value common.Hash) {
  187. // If the fake storage is set, put the temporary state update here.
  188. if s.fakeStorage != nil {
  189. s.fakeStorage[key] = value
  190. return
  191. }
  192. // If the new value is the same as old, don't set
  193. prev := s.GetState(db, key)
  194. if prev == value {
  195. return
  196. }
  197. // New value is different, update and journal the change
  198. s.db.journal.append(storageChange{
  199. account: &s.address,
  200. key: key,
  201. prevalue: prev,
  202. })
  203. s.setState(key, value)
  204. }
  205. // SetStorage replaces the entire state storage with the given one.
  206. //
  207. // After this function is called, all original state will be ignored and state
  208. // lookup only happens in the fake state storage.
  209. //
  210. // Note this function should only be used for debugging purpose.
  211. func (s *stateObject) SetStorage(storage map[common.Hash]common.Hash) {
  212. // Allocate fake storage if it's nil.
  213. if s.fakeStorage == nil {
  214. s.fakeStorage = make(Storage)
  215. }
  216. for key, value := range storage {
  217. s.fakeStorage[key] = value
  218. }
  219. // Don't bother journal since this function should only be used for
  220. // debugging and the `fake` storage won't be committed to database.
  221. }
  222. func (s *stateObject) setState(key, value common.Hash) {
  223. s.dirtyStorage[key] = value
  224. }
  225. // updateTrie writes cached storage modifications into the object's storage trie.
  226. func (s *stateObject) updateTrie(db Database) Trie {
  227. // Track the amount of time wasted on updating the storge trie
  228. if metrics.EnabledExpensive {
  229. defer func(start time.Time) { s.db.StorageUpdates += time.Since(start) }(time.Now())
  230. }
  231. // Update all the dirty slots in the trie
  232. tr := s.getTrie(db)
  233. for key, value := range s.dirtyStorage {
  234. delete(s.dirtyStorage, key)
  235. // Skip noop changes, persist actual changes
  236. if value == s.originStorage[key] {
  237. continue
  238. }
  239. s.originStorage[key] = value
  240. if (value == common.Hash{}) {
  241. s.setError(tr.TryDelete(key[:]))
  242. continue
  243. }
  244. // Encoding []byte cannot fail, ok to ignore the error.
  245. v, _ := rlp.EncodeToBytes(common.TrimLeftZeroes(value[:]))
  246. s.setError(tr.TryUpdate(key[:], v))
  247. }
  248. return tr
  249. }
  250. // UpdateRoot sets the trie root to the current root hash of
  251. func (s *stateObject) updateRoot(db Database) {
  252. s.updateTrie(db)
  253. // Track the amount of time wasted on hashing the storge trie
  254. if metrics.EnabledExpensive {
  255. defer func(start time.Time) { s.db.StorageHashes += time.Since(start) }(time.Now())
  256. }
  257. s.data.Root = s.trie.Hash()
  258. }
  259. // CommitTrie the storage trie of the object to db.
  260. // This updates the trie root.
  261. func (s *stateObject) CommitTrie(db Database) error {
  262. s.updateTrie(db)
  263. if s.dbErr != nil {
  264. return s.dbErr
  265. }
  266. // Track the amount of time wasted on committing the storge trie
  267. if metrics.EnabledExpensive {
  268. defer func(start time.Time) { s.db.StorageCommits += time.Since(start) }(time.Now())
  269. }
  270. root, err := s.trie.Commit(nil)
  271. if err == nil {
  272. s.data.Root = root
  273. }
  274. return err
  275. }
  276. // AddBalance removes amount from c's balance.
  277. // It is used to add funds to the destination account of a transfer.
  278. func (s *stateObject) AddBalance(amount *big.Int) {
  279. // EIP158: We must check emptiness for the objects such that the account
  280. // clearing (0,0,0 objects) can take effect.
  281. if amount.Sign() == 0 {
  282. if s.empty() {
  283. s.touch()
  284. }
  285. return
  286. }
  287. s.SetBalance(new(big.Int).Add(s.Balance(), amount))
  288. }
  289. // SubBalance removes amount from c's balance.
  290. // It is used to remove funds from the origin account of a transfer.
  291. func (s *stateObject) SubBalance(amount *big.Int) {
  292. if amount.Sign() == 0 {
  293. return
  294. }
  295. s.SetBalance(new(big.Int).Sub(s.Balance(), amount))
  296. }
  297. func (s *stateObject) SetBalance(amount *big.Int) {
  298. s.db.journal.append(balanceChange{
  299. account: &s.address,
  300. prev: new(big.Int).Set(s.data.Balance),
  301. })
  302. s.setBalance(amount)
  303. }
  304. func (s *stateObject) setBalance(amount *big.Int) {
  305. s.data.Balance = amount
  306. }
  307. // Return the gas back to the origin. Used by the Virtual machine or Closures
  308. func (s *stateObject) ReturnGas(gas *big.Int) {}
  309. func (s *stateObject) deepCopy(db *StateDB) *stateObject {
  310. stateObject := newObject(db, s.address, s.data)
  311. if s.trie != nil {
  312. stateObject.trie = db.db.CopyTrie(s.trie)
  313. }
  314. stateObject.code = s.code
  315. stateObject.dirtyStorage = s.dirtyStorage.Copy()
  316. stateObject.originStorage = s.originStorage.Copy()
  317. stateObject.suicided = s.suicided
  318. stateObject.dirtyCode = s.dirtyCode
  319. stateObject.deleted = s.deleted
  320. return stateObject
  321. }
  322. //
  323. // Attribute accessors
  324. //
  325. // Returns the address of the contract/account
  326. func (s *stateObject) Address() common.Address {
  327. return s.address
  328. }
  329. // Code returns the contract code associated with this object, if any.
  330. func (s *stateObject) Code(db Database) []byte {
  331. if s.code != nil {
  332. return s.code
  333. }
  334. if bytes.Equal(s.CodeHash(), emptyCodeHash) {
  335. return nil
  336. }
  337. code, err := db.ContractCode(s.addrHash, common.BytesToHash(s.CodeHash()))
  338. if err != nil {
  339. s.setError(fmt.Errorf("can't load code hash %x: %v", s.CodeHash(), err))
  340. }
  341. s.code = code
  342. return code
  343. }
  344. func (s *stateObject) SetCode(codeHash common.Hash, code []byte) {
  345. prevcode := s.Code(s.db.db)
  346. s.db.journal.append(codeChange{
  347. account: &s.address,
  348. prevhash: s.CodeHash(),
  349. prevcode: prevcode,
  350. })
  351. s.setCode(codeHash, code)
  352. }
  353. func (s *stateObject) setCode(codeHash common.Hash, code []byte) {
  354. s.code = code
  355. s.data.CodeHash = codeHash[:]
  356. s.dirtyCode = true
  357. }
  358. func (s *stateObject) SetNonce(nonce uint64) {
  359. s.db.journal.append(nonceChange{
  360. account: &s.address,
  361. prev: s.data.Nonce,
  362. })
  363. s.setNonce(nonce)
  364. }
  365. func (s *stateObject) setNonce(nonce uint64) {
  366. s.data.Nonce = nonce
  367. }
  368. func (s *stateObject) CodeHash() []byte {
  369. return s.data.CodeHash
  370. }
  371. func (s *stateObject) Balance() *big.Int {
  372. return s.data.Balance
  373. }
  374. func (s *stateObject) Nonce() uint64 {
  375. return s.data.Nonce
  376. }
  377. // Never called, but must be present to allow stateObject to be used
  378. // as a vm.Account interface that also satisfies the vm.ContractRef
  379. // interface. Interfaces are awesome.
  380. func (s *stateObject) Value() *big.Int {
  381. panic("Value on stateObject should never be called")
  382. }