Account.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. /*
  2. This file is part of cpp-ethereum.
  3. cpp-ethereum is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation, either version 3 of the License, or
  6. (at your option) any later version.
  7. cpp-ethereum is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
  13. */
  14. /** @file Account.h
  15. * @author Gav Wood <i@gavwood.com>
  16. * @date 2014
  17. */
  18. #pragma once
  19. #include <libdevcore/Common.h>
  20. #include <libdevcore/RLP.h>
  21. #include <libdevcore/TrieDB.h>
  22. #include <libdevcore/SHA3.h>
  23. #include <libethcore/Common.h>
  24. namespace dev
  25. {
  26. namespace eth
  27. {
  28. /**
  29. * Models the state of a single Ethereum account.
  30. * Used to cache a portion of the full Ethereum state. State keeps a mapping of Address's to Accounts.
  31. *
  32. * Aside from storing the nonce and balance, the account may also be "dead" (where isAlive() returns false).
  33. * This allows State to explicitly store the notion of a deleted account in it's cache. kill() can be used
  34. * for this.
  35. *
  36. * For the account's storage, the class operates a cache. baseRoot() specifies the base state of the storage
  37. * given as the Trie root to be looked up in the state database. Alterations beyond this base are specified
  38. * in the overlay, stored in this class and retrieved with storageOverlay(). setStorage allows the overlay
  39. * to be altered.
  40. *
  41. * The code handling explicitly supports a two-stage commit model needed for contract-creation. When creating
  42. * a contract (running the initialisation code), the code of the account is considered empty. The attribute
  43. * of emptiness can be retrieved with codeBearing(). After initialisation one must set the code accordingly;
  44. * the code of the Account can be set with setCode(). To validate a setCode() call, this class records the
  45. * state of being in contract-creation (and thus in a state where setCode may validly be called). It can be
  46. * determined through isFreshCode().
  47. *
  48. * The code can be retrieved through code(), and its hash through codeHash(). codeHash() is only valid when
  49. * the account is not in the contract-creation phase (i.e. when isFreshCode() returns false). This class
  50. * supports populating code on-demand from the state database. To determine if the code has been prepopulated
  51. * call codeCacheValid(). To populate the code, look it up with codeHash() and populate with noteCode().
  52. *
  53. * @todo: need to make a noteCodeCommitted().
  54. *
  55. * The constructor allows you to create an one of a number of "types" of accounts. The default constructor
  56. * makes a dead account (this is ignored by State when writing out the Trie). Another three allow a basic
  57. * or contract account to be specified along with an initial balance. The fina two allow either a basic or
  58. * a contract account to be created with arbitrary values.
  59. */
  60. class Account
  61. {
  62. public:
  63. /// Type of account to create.
  64. enum NewAccountType
  65. {
  66. /// Normal account.
  67. NormalCreation,
  68. /// Contract account - we place this object into the contract-creation state (and as such we
  69. /// expect setCode(), but codeHash() won't work).
  70. ContractConception
  71. };
  72. /// Changedness of account to create.
  73. enum Changedness
  74. {
  75. /// Account starts as though it has been changed.
  76. Changed,
  77. /// Account starts as though it has not been changed.
  78. Unchanged
  79. };
  80. /// Construct a dead Account.
  81. Account() {}
  82. /// Construct an alive Account, with given endowment, for either a normal (non-contract) account or for a
  83. /// contract account in the
  84. /// conception phase, where the code is not yet known.
  85. Account(u256 _nonce, u256 _balance, NewAccountType _t, Changedness _c = Changed): m_isAlive(true), m_isUnchanged(_c == Unchanged), m_nonce(_nonce), m_balance(_balance), m_codeHash(_t == NormalCreation ? EmptySHA3 : c_contractConceptionCodeHash) {}
  86. /// Explicit constructor for wierd cases of construction of a normal account.
  87. Account(u256 _nonce, u256 _balance, Changedness _c = Changed): m_isAlive(true), m_isUnchanged(_c == Unchanged), m_nonce(_nonce), m_balance(_balance) {}
  88. /// Explicit constructor for wierd cases of construction or a contract account.
  89. Account(u256 _nonce, u256 _balance, h256 _contractRoot, h256 _codeHash, Changedness _c): m_isAlive(true), m_isUnchanged(_c == Unchanged), m_nonce(_nonce), m_balance(_balance), m_storageRoot(_contractRoot), m_codeHash(_codeHash) { assert(_contractRoot); }
  90. /// Kill this account. Useful for the suicide opcode. Following this call, isAlive() returns false.
  91. void kill() { m_isAlive = false; m_storageOverlay.clear(); m_codeHash = EmptySHA3; m_storageRoot = EmptyTrie; m_balance = 0; m_nonce = 0; changed(); }
  92. /// @returns true iff this object represents an account in the state. Returns false if this object
  93. /// represents an account that should no longer exist in the trie (an account that never existed or was
  94. /// suicided).
  95. bool isAlive() const { return m_isAlive; }
  96. /// @returns true if the account is unchanged from creation.
  97. bool isDirty() const { return !m_isUnchanged; }
  98. /// @returns true if the nonce, balance and code is zero / empty. Code is considered empty
  99. /// during creation phase.
  100. bool isEmpty() const { return nonce() == 0 && balance() == 0 && (isFreshCode() ? code().empty() : codeHash() == EmptySHA3); }
  101. /// @returns the balance of this account. Can be altered in place.
  102. u256& balance() { return m_balance; }
  103. /// @returns the balance of this account.
  104. u256 const& balance() const { return m_balance; }
  105. /// Increments the balance of this account by the given amount. It's a bigint, so can be negative.
  106. void addBalance(bigint _i) { m_balance = (u256)((bigint)m_balance + _i); changed(); }
  107. /// @returns the nonce of the account.
  108. u256 nonce() const { return m_nonce; }
  109. /// Increment the nonce of the account by one.
  110. void incNonce() { ++m_nonce; changed(); }
  111. /// Set nonce to a new value. This is used when reverting changes made to
  112. /// the account.
  113. void setNonce(u256 const& _nonce) { m_nonce = _nonce; changed(); }
  114. /// @returns the root of the trie (whose nodes are stored in the state db externally to this class)
  115. /// which encodes the base-state of the account's storage (upon which the storage is overlaid).
  116. h256 baseRoot() const { assert(m_storageRoot); return m_storageRoot; }
  117. /// @returns the storage overlay as a simple hash map.
  118. std::unordered_map<u256, u256> const& storageOverlay() const { return m_storageOverlay; }
  119. /// Set a key/value pair in the account's storage. This actually goes into the overlay, for committing
  120. /// to the trie later.
  121. void setStorage(u256 _p, u256 _v) { m_storageOverlay[_p] = _v; changed(); }
  122. /// Set a key/value pair in the account's storage to a value that is already present inside the
  123. /// database.
  124. void setStorageCache(u256 _p, u256 _v) const { const_cast<decltype(m_storageOverlay)&>(m_storageOverlay)[_p] = _v; }
  125. /// @returns true if we are in the contract-conception state and setCode is valid to call.
  126. bool isFreshCode() const { return m_codeHash == c_contractConceptionCodeHash; }
  127. /// @returns true if we are either in the contract-conception state or if the account's code is not
  128. /// empty.
  129. bool codeBearing() const { return m_codeHash != EmptySHA3; }
  130. /// @returns the hash of the account's code. Must only be called when isFreshCode() returns false.
  131. h256 codeHash() const { assert(!isFreshCode()); return m_codeHash; }
  132. /// Sets the code of the account. Must only be called when isFreshCode() returns true.
  133. void setCode(bytes&& _code) { assert(isFreshCode()); m_codeCache = std::move(_code); changed(); }
  134. /// @returns true if the account's code is available through code().
  135. bool codeCacheValid() const { return m_codeHash == EmptySHA3 || m_codeHash == c_contractConceptionCodeHash || m_codeCache.size(); }
  136. /// Specify to the object what the actual code is for the account. @a _code must have a SHA3 equal to
  137. /// codeHash() and must only be called when isFreshCode() returns false.
  138. void noteCode(bytesConstRef _code) { assert(sha3(_code) == m_codeHash); m_codeCache = _code.toBytes(); }
  139. /// @returns the account's code. Must only be called when codeCacheValid returns true.
  140. bytes const& code() const { assert(codeCacheValid()); return m_codeCache; }
  141. private:
  142. /// Note that we've altered the account.
  143. void changed() { m_isUnchanged = false; }
  144. /// Is this account existant? If not, it represents a deleted account.
  145. bool m_isAlive = false;
  146. /// True if we've not made any alteration to the account having been given it's properties directly.
  147. bool m_isUnchanged = false;
  148. /// Account's nonce.
  149. u256 m_nonce;
  150. /// Account's balance.
  151. u256 m_balance = 0;
  152. /// The base storage root. Used with the state DB to give a base to the storage. m_storageOverlay is
  153. /// overlaid on this and takes precedence for all values set.
  154. h256 m_storageRoot = EmptyTrie;
  155. /** If c_contractConceptionCodeHash then we're in the limbo where we're running the initialisation code.
  156. * We expect a setCode() at some point later.
  157. * If EmptySHA3, then m_code, which should be empty, is valid.
  158. * If anything else, then m_code is valid iff it's not empty, otherwise, State::ensureCached() needs to
  159. * be called with the correct args.
  160. */
  161. h256 m_codeHash = EmptySHA3;
  162. /// The map with is overlaid onto whatever storage is implied by the m_storageRoot in the trie.
  163. std::unordered_map<u256, u256> m_storageOverlay;
  164. /// The associated code for this account. The SHA3 of this should be equal to m_codeHash unless m_codeHash
  165. /// equals c_contractConceptionCodeHash.
  166. bytes m_codeCache;
  167. /// Value for m_codeHash when this account is having its code determined.
  168. static const h256 c_contractConceptionCodeHash;
  169. };
  170. class AccountMask
  171. {
  172. public:
  173. AccountMask(bool _all = false):
  174. m_hasBalance(_all),
  175. m_hasNonce(_all),
  176. m_hasCode(_all),
  177. m_hasStorage(_all)
  178. {}
  179. AccountMask(
  180. bool _hasBalance,
  181. bool _hasNonce,
  182. bool _hasCode,
  183. bool _hasStorage,
  184. bool _shouldNotExist = false
  185. ):
  186. m_hasBalance(_hasBalance),
  187. m_hasNonce(_hasNonce),
  188. m_hasCode(_hasCode),
  189. m_hasStorage(_hasStorage),
  190. m_shouldNotExist(_shouldNotExist)
  191. {}
  192. bool allSet() const { return m_hasBalance && m_hasNonce && m_hasCode && m_hasStorage; }
  193. bool hasBalance() const { return m_hasBalance; }
  194. bool hasNonce() const { return m_hasNonce; }
  195. bool hasCode() const { return m_hasCode; }
  196. bool hasStorage() const { return m_hasStorage; }
  197. bool shouldExist() const { return !m_shouldNotExist; }
  198. private:
  199. bool m_hasBalance;
  200. bool m_hasNonce;
  201. bool m_hasCode;
  202. bool m_hasStorage;
  203. bool m_shouldNotExist = false;
  204. };
  205. using AccountMap = std::unordered_map<Address, Account>;
  206. using AccountMaskMap = std::unordered_map<Address, AccountMask>;
  207. class PrecompiledContract;
  208. using PrecompiledContractMap = std::unordered_map<Address, PrecompiledContract>;
  209. AccountMap jsonToAccountMap(std::string const& _json, u256 const& _defaultNonce = 0, AccountMaskMap* o_mask = nullptr, PrecompiledContractMap* o_precompiled = nullptr);
  210. }
  211. }