state_object.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  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. originalValue Storage // Map of original storage values, at the beginning of current call context
  68. // Cache flags.
  69. // When an object is marked suicided it will be delete from the trie
  70. // during the "update" phase of the state transition.
  71. dirtyCode bool // true if the code was updated
  72. suicided bool
  73. deleted bool
  74. }
  75. // empty returns whether the account is considered empty.
  76. func (s *stateObject) empty() bool {
  77. return s.data.Nonce == 0 && s.data.Balance.Sign() == 0 && bytes.Equal(s.data.CodeHash, emptyCodeHash)
  78. }
  79. // Account is the Ethereum consensus representation of accounts.
  80. // These objects are stored in the main account trie.
  81. type Account struct {
  82. Nonce uint64
  83. Balance *big.Int
  84. Root common.Hash // merkle root of the storage trie
  85. CodeHash []byte
  86. }
  87. // newObject creates a state object.
  88. func newObject(db *StateDB, address common.Address, data Account) *stateObject {
  89. if data.Balance == nil {
  90. data.Balance = new(big.Int)
  91. }
  92. if data.CodeHash == nil {
  93. data.CodeHash = emptyCodeHash
  94. }
  95. return &stateObject{
  96. db: db,
  97. address: address,
  98. addrHash: crypto.Keccak256Hash(address[:]),
  99. data: data,
  100. cachedStorage: make(Storage),
  101. dirtyStorage: make(Storage),
  102. originalValue: make(Storage),
  103. }
  104. }
  105. // EncodeRLP implements rlp.Encoder.
  106. func (c *stateObject) EncodeRLP(w io.Writer) error {
  107. return rlp.Encode(w, c.data)
  108. }
  109. // setError remembers the first non-nil error it is called with.
  110. func (self *stateObject) setError(err error) {
  111. if self.dbErr == nil {
  112. self.dbErr = err
  113. }
  114. }
  115. func (self *stateObject) markSuicided() {
  116. self.suicided = true
  117. }
  118. func (c *stateObject) touch() {
  119. c.db.journal.append(touchChange{
  120. account: &c.address,
  121. })
  122. if c.address == ripemd {
  123. // Explicitly put it in the dirty-cache, which is otherwise generated from
  124. // flattened journals.
  125. c.db.journal.dirty(c.address)
  126. }
  127. }
  128. func (c *stateObject) getTrie(db Database) Trie {
  129. if c.trie == nil {
  130. var err error
  131. c.trie, err = db.OpenStorageTrie(c.addrHash, c.data.Root)
  132. if err != nil {
  133. c.trie, _ = db.OpenStorageTrie(c.addrHash, common.Hash{})
  134. c.setError(fmt.Errorf("can't create storage trie: %v", err))
  135. }
  136. }
  137. return c.trie
  138. }
  139. // GetState returns a value in account storage.
  140. func (self *stateObject) GetState(db Database, key common.Hash) common.Hash {
  141. value, exists := self.cachedStorage[key]
  142. if exists {
  143. return value
  144. }
  145. // Load from DB in case it is missing.
  146. enc, err := self.getTrie(db).TryGet(key[:])
  147. if err != nil {
  148. self.setError(err)
  149. return common.Hash{}
  150. }
  151. if len(enc) > 0 {
  152. _, content, _, err := rlp.Split(enc)
  153. if err != nil {
  154. self.setError(err)
  155. }
  156. value.SetBytes(content)
  157. }
  158. self.cachedStorage[key] = value
  159. return value
  160. }
  161. // GetOriginalStateValue returns the state value that is currently in the Trie, that is, ignoring any
  162. // changes that have been made but not yet written to trie.
  163. func (self *stateObject) GetOriginalStateValue(db Database, key common.Hash) common.Hash{
  164. if original, exist:= self.originalValue[key]; exist {
  165. // original value has been set, return it
  166. return original
  167. }
  168. return self.GetState(db, key)
  169. }
  170. // SetState updates a value in account storage.
  171. func (self *stateObject) SetState(db Database, key, value common.Hash) {
  172. prev := self.GetState(db, key)
  173. self.db.journal.append(storageChange{
  174. account: &self.address,
  175. key: key,
  176. prevalue: prev,
  177. })
  178. if _, isSet := self.originalValue[key]; !isSet {
  179. // original value has not been set, so set it now
  180. self.originalValue[key] = prev
  181. }
  182. self.setState(key, value)
  183. }
  184. func (self *stateObject) setState(key, value common.Hash) {
  185. self.cachedStorage[key] = value
  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. if (value == common.Hash{}) {
  194. self.setError(tr.TryDelete(key[:]))
  195. continue
  196. }
  197. // Encoding []byte cannot fail, ok to ignore the error.
  198. v, _ := rlp.EncodeToBytes(bytes.TrimLeft(value[:], "\x00"))
  199. self.setError(tr.TryUpdate(key[:], v))
  200. }
  201. // Clean the map containing 'original' value of storage entries
  202. for k, _ := range self.originalValue {
  203. delete(self.originalValue, k)
  204. }
  205. return tr
  206. }
  207. // UpdateRoot sets the trie root to the current root hash of
  208. func (self *stateObject) updateRoot(db Database) {
  209. self.updateTrie(db)
  210. self.data.Root = self.trie.Hash()
  211. }
  212. // CommitTrie the storage trie of the object to db.
  213. // This updates the trie root.
  214. func (self *stateObject) CommitTrie(db Database) error {
  215. self.updateTrie(db)
  216. if self.dbErr != nil {
  217. return self.dbErr
  218. }
  219. root, err := self.trie.Commit(nil)
  220. if err == nil {
  221. self.data.Root = root
  222. }
  223. return err
  224. }
  225. // AddBalance removes amount from c's balance.
  226. // It is used to add funds to the destination account of a transfer.
  227. func (c *stateObject) AddBalance(amount *big.Int) {
  228. // EIP158: We must check emptiness for the objects such that the account
  229. // clearing (0,0,0 objects) can take effect.
  230. if amount.Sign() == 0 {
  231. if c.empty() {
  232. c.touch()
  233. }
  234. return
  235. }
  236. c.SetBalance(new(big.Int).Add(c.Balance(), amount))
  237. }
  238. // SubBalance removes amount from c's balance.
  239. // It is used to remove funds from the origin account of a transfer.
  240. func (c *stateObject) SubBalance(amount *big.Int) {
  241. if amount.Sign() == 0 {
  242. return
  243. }
  244. c.SetBalance(new(big.Int).Sub(c.Balance(), amount))
  245. }
  246. func (self *stateObject) SetBalance(amount *big.Int) {
  247. self.db.journal.append(balanceChange{
  248. account: &self.address,
  249. prev: new(big.Int).Set(self.data.Balance),
  250. })
  251. self.setBalance(amount)
  252. }
  253. func (self *stateObject) setBalance(amount *big.Int) {
  254. self.data.Balance = amount
  255. }
  256. // Return the gas back to the origin. Used by the Virtual machine or Closures
  257. func (c *stateObject) ReturnGas(gas *big.Int) {}
  258. func (self *stateObject) deepCopy(db *StateDB) *stateObject {
  259. stateObject := newObject(db, self.address, self.data)
  260. if self.trie != nil {
  261. stateObject.trie = db.db.CopyTrie(self.trie)
  262. }
  263. stateObject.code = self.code
  264. stateObject.dirtyStorage = self.dirtyStorage.Copy()
  265. stateObject.cachedStorage = self.dirtyStorage.Copy()
  266. stateObject.originalValue = self.originalValue.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. }