state_object.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  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. "github.com/ethereum/go-ethereum/common"
  23. "github.com/ethereum/go-ethereum/crypto"
  24. "github.com/ethereum/go-ethereum/rlp"
  25. )
  26. var emptyCodeHash = crypto.Keccak256(nil)
  27. type Code []byte
  28. func (self Code) String() string {
  29. return string(self) //strings.Join(Disassemble(self), " ")
  30. }
  31. type Storage map[common.Hash]common.Hash
  32. func (self Storage) String() (str string) {
  33. for key, value := range self {
  34. str += fmt.Sprintf("%X : %X\n", key, value)
  35. }
  36. return
  37. }
  38. func (self Storage) Copy() Storage {
  39. cpy := make(Storage)
  40. for key, value := range self {
  41. cpy[key] = value
  42. }
  43. return cpy
  44. }
  45. // stateObject represents an Ethereum account which is being modified.
  46. //
  47. // The usage pattern is as follows:
  48. // First you need to obtain a state object.
  49. // Account values can be accessed and modified through the object.
  50. // Finally, call CommitTrie to write the modified storage trie into a database.
  51. type stateObject struct {
  52. address common.Address
  53. addrHash common.Hash // hash of ethereum address of the account
  54. data Account
  55. db *StateDB
  56. // DB error.
  57. // State objects are used by the consensus core and VM which are
  58. // unable to deal with database-level errors. Any error that occurs
  59. // during a database read is memoized here and will eventually be returned
  60. // by StateDB.Commit.
  61. dbErr error
  62. // Write caches.
  63. trie Trie // storage trie, which becomes non-nil on first access
  64. code Code // contract bytecode, which gets set when code is loaded
  65. originStorage Storage // Storage cache of original entries to dedup rewrites
  66. dirtyStorage Storage // Storage entries that need to be flushed to disk
  67. // Cache flags.
  68. // When an object is marked suicided it will be delete from the trie
  69. // during the "update" phase of the state transition.
  70. dirtyCode bool // true if the code was updated
  71. suicided bool
  72. deleted bool
  73. }
  74. // empty returns whether the account is considered empty.
  75. func (s *stateObject) empty() bool {
  76. return s.data.Nonce == 0 && s.data.Balance.Sign() == 0 && bytes.Equal(s.data.CodeHash, emptyCodeHash)
  77. }
  78. // Account is the Ethereum consensus representation of accounts.
  79. // These objects are stored in the main account trie.
  80. type Account struct {
  81. Nonce uint64
  82. Balance *big.Int
  83. Root common.Hash // merkle root of the storage trie
  84. CodeHash []byte
  85. }
  86. // newObject creates a state object.
  87. func newObject(db *StateDB, address common.Address, data Account) *stateObject {
  88. if data.Balance == nil {
  89. data.Balance = new(big.Int)
  90. }
  91. if data.CodeHash == nil {
  92. data.CodeHash = emptyCodeHash
  93. }
  94. return &stateObject{
  95. db: db,
  96. address: address,
  97. addrHash: crypto.Keccak256Hash(address[:]),
  98. data: data,
  99. originStorage: make(Storage),
  100. dirtyStorage: make(Storage),
  101. }
  102. }
  103. // EncodeRLP implements rlp.Encoder.
  104. func (c *stateObject) EncodeRLP(w io.Writer) error {
  105. return rlp.Encode(w, c.data)
  106. }
  107. // setError remembers the first non-nil error it is called with.
  108. func (self *stateObject) setError(err error) {
  109. if self.dbErr == nil {
  110. self.dbErr = err
  111. }
  112. }
  113. func (self *stateObject) markSuicided() {
  114. self.suicided = true
  115. }
  116. func (c *stateObject) touch() {
  117. c.db.journal.append(touchChange{
  118. account: &c.address,
  119. })
  120. if c.address == ripemd {
  121. // Explicitly put it in the dirty-cache, which is otherwise generated from
  122. // flattened journals.
  123. c.db.journal.dirty(c.address)
  124. }
  125. }
  126. func (c *stateObject) getTrie(db Database) Trie {
  127. if c.trie == nil {
  128. var err error
  129. c.trie, err = db.OpenStorageTrie(c.addrHash, c.data.Root)
  130. if err != nil {
  131. c.trie, _ = db.OpenStorageTrie(c.addrHash, common.Hash{})
  132. c.setError(fmt.Errorf("can't create storage trie: %v", err))
  133. }
  134. }
  135. return c.trie
  136. }
  137. // GetState retrieves a value from the account storage trie.
  138. func (self *stateObject) GetState(db Database, key common.Hash) common.Hash {
  139. // If we have a dirty value for this state entry, return it
  140. value, dirty := self.dirtyStorage[key]
  141. if dirty {
  142. return value
  143. }
  144. // Otherwise return the entry's original value
  145. return self.GetCommittedState(db, key)
  146. }
  147. // GetCommittedState retrieves a value from the committed account storage trie.
  148. func (self *stateObject) GetCommittedState(db Database, key common.Hash) common.Hash {
  149. // If we have the original value cached, return that
  150. value, cached := self.originStorage[key]
  151. if cached {
  152. return value
  153. }
  154. // Otherwise load the value from the database
  155. enc, err := self.getTrie(db).TryGet(key[:])
  156. if err != nil {
  157. self.setError(err)
  158. return common.Hash{}
  159. }
  160. if len(enc) > 0 {
  161. _, content, _, err := rlp.Split(enc)
  162. if err != nil {
  163. self.setError(err)
  164. }
  165. value.SetBytes(content)
  166. }
  167. self.originStorage[key] = value
  168. return value
  169. }
  170. // SetState updates a value in account storage.
  171. func (self *stateObject) SetState(db Database, key, value common.Hash) {
  172. // If the new value is the same as old, don't set
  173. prev := self.GetState(db, key)
  174. if prev == value {
  175. return
  176. }
  177. // New value is different, update and journal the change
  178. self.db.journal.append(storageChange{
  179. account: &self.address,
  180. key: key,
  181. prevalue: prev,
  182. })
  183. self.setState(key, value)
  184. }
  185. func (self *stateObject) setState(key, value common.Hash) {
  186. self.dirtyStorage[key] = value
  187. }
  188. // updateTrie writes cached storage modifications into the object's storage trie.
  189. func (self *stateObject) updateTrie(db Database) Trie {
  190. tr := self.getTrie(db)
  191. for key, value := range self.dirtyStorage {
  192. delete(self.dirtyStorage, key)
  193. // Skip noop changes, persist actual changes
  194. if value == self.originStorage[key] {
  195. continue
  196. }
  197. self.originStorage[key] = value
  198. if (value == common.Hash{}) {
  199. self.setError(tr.TryDelete(key[:]))
  200. continue
  201. }
  202. // Encoding []byte cannot fail, ok to ignore the error.
  203. v, _ := rlp.EncodeToBytes(bytes.TrimLeft(value[:], "\x00"))
  204. self.setError(tr.TryUpdate(key[:], v))
  205. }
  206. return tr
  207. }
  208. // UpdateRoot sets the trie root to the current root hash of
  209. func (self *stateObject) updateRoot(db Database) {
  210. self.updateTrie(db)
  211. self.data.Root = self.trie.Hash()
  212. }
  213. // CommitTrie the storage trie of the object to db.
  214. // This updates the trie root.
  215. func (self *stateObject) CommitTrie(db Database) error {
  216. self.updateTrie(db)
  217. if self.dbErr != nil {
  218. return self.dbErr
  219. }
  220. root, err := self.trie.Commit(nil)
  221. if err == nil {
  222. self.data.Root = root
  223. }
  224. return err
  225. }
  226. // AddBalance removes amount from c's balance.
  227. // It is used to add funds to the destination account of a transfer.
  228. func (c *stateObject) AddBalance(amount *big.Int) {
  229. // EIP158: We must check emptiness for the objects such that the account
  230. // clearing (0,0,0 objects) can take effect.
  231. if amount.Sign() == 0 {
  232. if c.empty() {
  233. c.touch()
  234. }
  235. return
  236. }
  237. c.SetBalance(new(big.Int).Add(c.Balance(), amount))
  238. }
  239. // SubBalance removes amount from c's balance.
  240. // It is used to remove funds from the origin account of a transfer.
  241. func (c *stateObject) SubBalance(amount *big.Int) {
  242. if amount.Sign() == 0 {
  243. return
  244. }
  245. c.SetBalance(new(big.Int).Sub(c.Balance(), amount))
  246. }
  247. func (self *stateObject) SetBalance(amount *big.Int) {
  248. self.db.journal.append(balanceChange{
  249. account: &self.address,
  250. prev: new(big.Int).Set(self.data.Balance),
  251. })
  252. self.setBalance(amount)
  253. }
  254. func (self *stateObject) setBalance(amount *big.Int) {
  255. self.data.Balance = amount
  256. }
  257. // Return the gas back to the origin. Used by the Virtual machine or Closures
  258. func (c *stateObject) ReturnGas(gas *big.Int) {}
  259. func (self *stateObject) deepCopy(db *StateDB) *stateObject {
  260. stateObject := newObject(db, self.address, self.data)
  261. if self.trie != nil {
  262. stateObject.trie = db.db.CopyTrie(self.trie)
  263. }
  264. stateObject.code = self.code
  265. stateObject.dirtyStorage = self.dirtyStorage.Copy()
  266. stateObject.originStorage = self.originStorage.Copy()
  267. stateObject.suicided = self.suicided
  268. stateObject.dirtyCode = self.dirtyCode
  269. stateObject.deleted = self.deleted
  270. return stateObject
  271. }
  272. //
  273. // Attribute accessors
  274. //
  275. // Returns the address of the contract/account
  276. func (c *stateObject) Address() common.Address {
  277. return c.address
  278. }
  279. // Code returns the contract code associated with this object, if any.
  280. func (self *stateObject) Code(db Database) []byte {
  281. if self.code != nil {
  282. return self.code
  283. }
  284. if bytes.Equal(self.CodeHash(), emptyCodeHash) {
  285. return nil
  286. }
  287. code, err := db.ContractCode(self.addrHash, common.BytesToHash(self.CodeHash()))
  288. if err != nil {
  289. self.setError(fmt.Errorf("can't load code hash %x: %v", self.CodeHash(), err))
  290. }
  291. self.code = code
  292. return code
  293. }
  294. func (self *stateObject) SetCode(codeHash common.Hash, code []byte) {
  295. prevcode := self.Code(self.db.db)
  296. self.db.journal.append(codeChange{
  297. account: &self.address,
  298. prevhash: self.CodeHash(),
  299. prevcode: prevcode,
  300. })
  301. self.setCode(codeHash, code)
  302. }
  303. func (self *stateObject) setCode(codeHash common.Hash, code []byte) {
  304. self.code = code
  305. self.data.CodeHash = codeHash[:]
  306. self.dirtyCode = true
  307. }
  308. func (self *stateObject) SetNonce(nonce uint64) {
  309. self.db.journal.append(nonceChange{
  310. account: &self.address,
  311. prev: self.data.Nonce,
  312. })
  313. self.setNonce(nonce)
  314. }
  315. func (self *stateObject) setNonce(nonce uint64) {
  316. self.data.Nonce = nonce
  317. }
  318. func (self *stateObject) CodeHash() []byte {
  319. return self.data.CodeHash
  320. }
  321. func (self *stateObject) Balance() *big.Int {
  322. return self.data.Balance
  323. }
  324. func (self *stateObject) Nonce() uint64 {
  325. return self.data.Nonce
  326. }
  327. // Never called, but must be present to allow stateObject to be used
  328. // as a vm.Account interface that also satisfies the vm.ContractRef
  329. // interface. Interfaces are awesome.
  330. func (self *stateObject) Value() *big.Int {
  331. panic("Value on stateObject should never be called")
  332. }