state_object.go 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  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. cachedStorage Storage // Storage entry cache to avoid duplicate reads
  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. cachedStorage: 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
  122. // generated from flattened journals
  123. c.db.journal.dirtyOverride(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 returns a value in account storage.
  138. func (self *stateObject) GetState(db Database, key common.Hash) common.Hash {
  139. value, exists := self.cachedStorage[key]
  140. if exists {
  141. return value
  142. }
  143. // Load from DB in case it is missing.
  144. enc, err := self.getTrie(db).TryGet(key[:])
  145. if err != nil {
  146. self.setError(err)
  147. return common.Hash{}
  148. }
  149. if len(enc) > 0 {
  150. _, content, _, err := rlp.Split(enc)
  151. if err != nil {
  152. self.setError(err)
  153. }
  154. value.SetBytes(content)
  155. }
  156. if (value != common.Hash{}) {
  157. self.cachedStorage[key] = value
  158. }
  159. return value
  160. }
  161. // SetState updates a value in account storage.
  162. func (self *stateObject) SetState(db Database, key, value common.Hash) {
  163. self.db.journal.append(storageChange{
  164. account: &self.address,
  165. key: key,
  166. prevalue: self.GetState(db, key),
  167. })
  168. self.setState(key, value)
  169. }
  170. func (self *stateObject) setState(key, value common.Hash) {
  171. self.cachedStorage[key] = value
  172. self.dirtyStorage[key] = value
  173. }
  174. // updateTrie writes cached storage modifications into the object's storage trie.
  175. func (self *stateObject) updateTrie(db Database) Trie {
  176. tr := self.getTrie(db)
  177. for key, value := range self.dirtyStorage {
  178. delete(self.dirtyStorage, key)
  179. if (value == common.Hash{}) {
  180. self.setError(tr.TryDelete(key[:]))
  181. continue
  182. }
  183. // Encoding []byte cannot fail, ok to ignore the error.
  184. v, _ := rlp.EncodeToBytes(bytes.TrimLeft(value[:], "\x00"))
  185. self.setError(tr.TryUpdate(key[:], v))
  186. }
  187. return tr
  188. }
  189. // UpdateRoot sets the trie root to the current root hash of
  190. func (self *stateObject) updateRoot(db Database) {
  191. self.updateTrie(db)
  192. self.data.Root = self.trie.Hash()
  193. }
  194. // CommitTrie the storage trie of the object to dwb.
  195. // This updates the trie root.
  196. func (self *stateObject) CommitTrie(db Database) error {
  197. self.updateTrie(db)
  198. if self.dbErr != nil {
  199. return self.dbErr
  200. }
  201. root, err := self.trie.Commit(nil)
  202. if err == nil {
  203. self.data.Root = root
  204. }
  205. return err
  206. }
  207. // AddBalance removes amount from c's balance.
  208. // It is used to add funds to the destination account of a transfer.
  209. func (c *stateObject) AddBalance(amount *big.Int) {
  210. // EIP158: We must check emptiness for the objects such that the account
  211. // clearing (0,0,0 objects) can take effect.
  212. if amount.Sign() == 0 {
  213. if c.empty() {
  214. c.touch()
  215. }
  216. return
  217. }
  218. c.SetBalance(new(big.Int).Add(c.Balance(), amount))
  219. }
  220. // SubBalance removes amount from c's balance.
  221. // It is used to remove funds from the origin account of a transfer.
  222. func (c *stateObject) SubBalance(amount *big.Int) {
  223. if amount.Sign() == 0 {
  224. return
  225. }
  226. c.SetBalance(new(big.Int).Sub(c.Balance(), amount))
  227. }
  228. func (self *stateObject) SetBalance(amount *big.Int) {
  229. self.db.journal.append(balanceChange{
  230. account: &self.address,
  231. prev: new(big.Int).Set(self.data.Balance),
  232. })
  233. self.setBalance(amount)
  234. }
  235. func (self *stateObject) setBalance(amount *big.Int) {
  236. self.data.Balance = amount
  237. }
  238. // Return the gas back to the origin. Used by the Virtual machine or Closures
  239. func (c *stateObject) ReturnGas(gas *big.Int) {}
  240. func (self *stateObject) deepCopy(db *StateDB) *stateObject {
  241. stateObject := newObject(db, self.address, self.data)
  242. if self.trie != nil {
  243. stateObject.trie = db.db.CopyTrie(self.trie)
  244. }
  245. stateObject.code = self.code
  246. stateObject.dirtyStorage = self.dirtyStorage.Copy()
  247. stateObject.cachedStorage = self.dirtyStorage.Copy()
  248. stateObject.suicided = self.suicided
  249. stateObject.dirtyCode = self.dirtyCode
  250. stateObject.deleted = self.deleted
  251. return stateObject
  252. }
  253. //
  254. // Attribute accessors
  255. //
  256. // Returns the address of the contract/account
  257. func (c *stateObject) Address() common.Address {
  258. return c.address
  259. }
  260. // Code returns the contract code associated with this object, if any.
  261. func (self *stateObject) Code(db Database) []byte {
  262. if self.code != nil {
  263. return self.code
  264. }
  265. if bytes.Equal(self.CodeHash(), emptyCodeHash) {
  266. return nil
  267. }
  268. code, err := db.ContractCode(self.addrHash, common.BytesToHash(self.CodeHash()))
  269. if err != nil {
  270. self.setError(fmt.Errorf("can't load code hash %x: %v", self.CodeHash(), err))
  271. }
  272. self.code = code
  273. return code
  274. }
  275. func (self *stateObject) SetCode(codeHash common.Hash, code []byte) {
  276. prevcode := self.Code(self.db.db)
  277. self.db.journal.append(codeChange{
  278. account: &self.address,
  279. prevhash: self.CodeHash(),
  280. prevcode: prevcode,
  281. })
  282. self.setCode(codeHash, code)
  283. }
  284. func (self *stateObject) setCode(codeHash common.Hash, code []byte) {
  285. self.code = code
  286. self.data.CodeHash = codeHash[:]
  287. self.dirtyCode = true
  288. }
  289. func (self *stateObject) SetNonce(nonce uint64) {
  290. self.db.journal.append(nonceChange{
  291. account: &self.address,
  292. prev: self.data.Nonce,
  293. })
  294. self.setNonce(nonce)
  295. }
  296. func (self *stateObject) setNonce(nonce uint64) {
  297. self.data.Nonce = nonce
  298. }
  299. func (self *stateObject) CodeHash() []byte {
  300. return self.data.CodeHash
  301. }
  302. func (self *stateObject) Balance() *big.Int {
  303. return self.data.Balance
  304. }
  305. func (self *stateObject) Nonce() uint64 {
  306. return self.data.Nonce
  307. }
  308. // Never called, but must be present to allow stateObject to be used
  309. // as a vm.Account interface that also satisfies the vm.ContractRef
  310. // interface. Interfaces are awesome.
  311. func (self *stateObject) Value() *big.Int {
  312. panic("Value on stateObject should never be called")
  313. }