State.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  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 State.h
  15. * @author Gav Wood <i@gavwood.com>
  16. * @date 2014
  17. */
  18. #pragma once
  19. #include <array>
  20. #include <unordered_map>
  21. #include <libdevcore/Common.h>
  22. #include <libdevcore/RLP.h>
  23. #include <libdevcore/TrieDB.h>
  24. #include <libdevcore/OverlayDB.h>
  25. #include <libethcore/Exceptions.h>
  26. #include <libethcore/BlockHeader.h>
  27. #include <libethereum/CodeSizeCache.h>
  28. #include <libethereum/GenericMiner.h>
  29. #include <libevm/ExtVMFace.h>
  30. #include "Account.h"
  31. #include "Transaction.h"
  32. #include "TransactionReceipt.h"
  33. #include "GasPricer.h"
  34. namespace dev
  35. {
  36. namespace test { class ImportTest; class StateLoader; }
  37. namespace eth
  38. {
  39. // Import-specific errinfos
  40. using errinfo_uncleIndex = boost::error_info<struct tag_uncleIndex, unsigned>;
  41. using errinfo_currentNumber = boost::error_info<struct tag_currentNumber, u256>;
  42. using errinfo_uncleNumber = boost::error_info<struct tag_uncleNumber, u256>;
  43. using errinfo_unclesExcluded = boost::error_info<struct tag_unclesExcluded, h256Hash>;
  44. using errinfo_block = boost::error_info<struct tag_block, bytes>;
  45. using errinfo_now = boost::error_info<struct tag_now, unsigned>;
  46. using errinfo_transactionIndex = boost::error_info<struct tag_transactionIndex, unsigned>;
  47. using errinfo_vmtrace = boost::error_info<struct tag_vmtrace, std::string>;
  48. using errinfo_receipts = boost::error_info<struct tag_receipts, std::vector<bytes>>;
  49. using errinfo_transaction = boost::error_info<struct tag_transaction, bytes>;
  50. using errinfo_phase = boost::error_info<struct tag_phase, unsigned>;
  51. using errinfo_required_LogBloom = boost::error_info<struct tag_required_LogBloom, LogBloom>;
  52. using errinfo_got_LogBloom = boost::error_info<struct tag_get_LogBloom, LogBloom>;
  53. using LogBloomRequirementError = boost::tuple<errinfo_required_LogBloom, errinfo_got_LogBloom>;
  54. class BlockChain;
  55. class State;
  56. class TransactionQueue;
  57. struct VerifiedBlockRef;
  58. struct StateChat: public LogChannel { static const char* name(); static const int verbosity = 4; };
  59. struct StateTrace: public LogChannel { static const char* name(); static const int verbosity = 5; };
  60. struct StateDetail: public LogChannel { static const char* name(); static const int verbosity = 14; };
  61. struct StateSafeExceptions: public LogChannel { static const char* name(); static const int verbosity = 21; };
  62. enum class BaseState
  63. {
  64. PreExisting,
  65. Empty
  66. };
  67. enum class Permanence
  68. {
  69. Reverted,
  70. Committed
  71. };
  72. #if ETH_FATDB
  73. template <class KeyType, class DB> using SecureTrieDB = SpecificTrieDB<FatGenericTrieDB<DB>, KeyType>;
  74. #else
  75. template <class KeyType, class DB> using SecureTrieDB = SpecificTrieDB<HashedGenericTrieDB<DB>, KeyType>;
  76. #endif
  77. DEV_SIMPLE_EXCEPTION(InvalidAccountStartNonceInState);
  78. DEV_SIMPLE_EXCEPTION(IncorrectAccountStartNonceInState);
  79. //#define ETH_ALLOW_EMPTY_BLOCK_AND_STATE 1
  80. class SealEngineFace;
  81. /**
  82. * @brief Model of an Ethereum state, essentially a facade for the trie.
  83. * Allows you to query the state of accounts, and has built-in caching for various aspects of the
  84. * state.
  85. */
  86. class State
  87. {
  88. friend class ExtVM;
  89. friend class dev::test::ImportTest;
  90. friend class dev::test::StateLoader;
  91. friend class BlockChain;
  92. public:
  93. enum class CommitBehaviour
  94. {
  95. KeepEmptyAccounts,
  96. RemoveEmptyAccounts
  97. };
  98. /// Default constructor; creates with a blank database prepopulated with the genesis block.
  99. explicit State(u256 const& _accountStartNonce): State(_accountStartNonce, OverlayDB(), BaseState::Empty) {}
  100. /// Basic state object from database.
  101. /// Use the default when you already have a database and you just want to make a State object
  102. /// which uses it. If you have no preexisting database then set BaseState to something other
  103. /// than BaseState::PreExisting in order to prepopulate the Trie.
  104. explicit State(u256 const& _accountStartNonce, OverlayDB const& _db, BaseState _bs = BaseState::PreExisting);
  105. #if ETH_ALLOW_EMPTY_BLOCK_AND_STATE
  106. State(): State(Invalid256, OverlayDB(), BaseState::Empty) {}
  107. explicit State(OverlayDB const& _db, BaseState _bs = BaseState::PreExisting): State(Invalid256, _db, _bs) {}
  108. #endif
  109. enum NullType { Null };
  110. State(NullType): State(Invalid256, OverlayDB(), BaseState::Empty) {}
  111. /// Copy state object.
  112. State(State const& _s);
  113. /// Copy state object.
  114. State& operator=(State const& _s);
  115. /// Open a DB - useful for passing into the constructor & keeping for other states that are necessary.
  116. static OverlayDB openDB(std::string const& _path, h256 const& _genesisHash, WithExisting _we = WithExisting::Trust);
  117. static OverlayDB openDB(h256 const& _genesisHash, WithExisting _we = WithExisting::Trust) { return openDB(std::string(), _genesisHash, _we); }
  118. OverlayDB const& db() const { return m_db; }
  119. OverlayDB& db() { return m_db; }
  120. /// Populate the state from the given AccountMap. Just uses dev::eth::commit().
  121. void populateFrom(AccountMap const& _map);
  122. /// @returns the set containing all addresses currently in use in Ethereum.
  123. /// @warning This is slowslowslow. Don't use it unless you want to lock the object for seconds or minutes at a time.
  124. /// @throws InterfaceNotSupported if compiled without ETH_FATDB.
  125. std::unordered_map<Address, u256> addresses() const;
  126. /// Execute a given transaction.
  127. /// This will change the state accordingly.
  128. std::pair<ExecutionResult, TransactionReceipt> execute(EnvInfo const& _envInfo, SealEngineFace const& _sealEngine, Transaction const& _t, Permanence _p = Permanence::Committed, OnOpFunc const& _onOp = OnOpFunc());
  129. /// Check if the address is in use.
  130. bool addressInUse(Address const& _address) const;
  131. /// Check if the account exists in the state and is non empty (nonce > 0 || balance > 0 || code nonempty).
  132. /// These two notions are equivalent after EIP158.
  133. bool accountNonemptyAndExisting(Address const& _address) const;
  134. /// Check if the address contains executable code.
  135. bool addressHasCode(Address const& _address) const;
  136. /// Get an account's balance.
  137. /// @returns 0 if the address has never been used.
  138. u256 balance(Address const& _id) const;
  139. /// Add some amount to balance.
  140. /// Will initialise the address if it has never been used.
  141. void addBalance(Address const& _id, u256 const& _amount);
  142. /** Subtract some amount from balance.
  143. * @throws NotEnoughCash if balance of @a _id is less than @a _value (or has never been used).
  144. * @note We use bigint here as we don't want any accidental problems with negative numbers.
  145. */
  146. void subBalance(Address const& _id, bigint const& _value);
  147. /**
  148. * @brief Transfers "the balance @a _value between two accounts.
  149. * @param _from Account from which @a _value will be deducted.
  150. * @param _to Account to which @a _value will be added.
  151. * @param _value Amount to be transferred.
  152. */
  153. void transferBalance(Address const& _from, Address const& _to, u256 const& _value) { subBalance(_from, _value); addBalance(_to, _value); }
  154. /// Get the root of the storage of an account.
  155. h256 storageRoot(Address const& _contract) const;
  156. /// Get the value of a storage position of an account.
  157. /// @returns 0 if no account exists at that address.
  158. u256 storage(Address const& _contract, u256 const& _memory) const;
  159. /// Set the value of a storage position of an account.
  160. void setStorage(Address const& _contract, u256 const& _location, u256 const& _value) { m_cache[_contract].setStorage(_location, _value); }
  161. /// Create a contract at the given address (with unset code and unchanged balance).
  162. /// If @a _incrementNonce is true, increment the nonce upon creation.
  163. void createContract(Address const& _address, bool _incrementNonce);
  164. /// Similar to `createContract`, but used in a normal transaction that targets _address.
  165. void ensureAccountExists(Address const& _address);
  166. /// Sets the code of the account. Must only be called during / after contract creation.
  167. void setCode(Address const& _address, bytes&& _code) { m_cache[_address].setCode(std::move(_code)); }
  168. /// Delete an account (used for processing suicides).
  169. void kill(Address _a);
  170. /// Get the storage of an account.
  171. /// @note This is expensive. Don't use it unless you need to.
  172. /// @returns std::map<u256, u256> if no account exists at that address.
  173. std::map<u256, u256> storage(Address const& _contract) const;
  174. /// Get the code of an account.
  175. /// @returns bytes() if no account exists at that address.
  176. bytes const& code(Address const& _contract) const;
  177. /// Get the code hash of an account.
  178. /// @returns EmptySHA3 if no account exists at that address or if there is no code associated with the address.
  179. h256 codeHash(Address const& _contract) const;
  180. /// Get the byte-size of the code of an account.
  181. /// @returns code(_contract).size(), but utilizes CodeSizeHash.
  182. size_t codeSize(Address const& _contract) const;
  183. /// Increament the account nonce.
  184. void incNonce(Address const& _id);
  185. /// Set the account nonce to the given value. Is used to revert account
  186. /// changes.
  187. void setNonce(Address const& _addr, u256 const& _nonce);
  188. /// Get the account nonce -- the number of transactions it has sent.
  189. /// @returns 0 if the address has never been used.
  190. u256 getNonce(Address const& _addr) const;
  191. /// The hash of the root of our state tree.
  192. h256 rootHash() const { return m_state.root(); }
  193. /// Commit all changes waiting in the address cache to the DB.
  194. /// @param _commitBehaviour whether or not to remove empty accounts during commit.
  195. void commit(CommitBehaviour _commitBehaviour);
  196. /// Resets any uncommitted changes to the cache.
  197. void setRoot(h256 const& _root);
  198. /// Get the account start nonce. May be required.
  199. u256 const& accountStartNonce() const { return m_accountStartNonce; }
  200. u256 const& requireAccountStartNonce() const;
  201. void noteAccountStartNonce(u256 const& _actual);
  202. private:
  203. /// Turns all "touched" empty accounts into non-alive accounts.
  204. void removeEmptyAccounts();
  205. /// @returns the account at the given address or a null pointer if it does not exist.
  206. /// The pointer is valid until the next access to the state or account.
  207. Account const* account(Address const& _a, bool _requireCode = false) const;
  208. /// @returns the account at the given address or a null pointer if it does not exist.
  209. /// The pointer is valid until the next access to the state or account.
  210. Account* account(Address const& _a, bool _requireCode = false);
  211. /// Purges non-modified entries in m_cache if it grows too large.
  212. void clearCacheIfTooLarge() const;
  213. /// Debugging only. Good for checking the Trie is in shape.
  214. bool isTrieGood(bool _enforceRefs, bool _requireNoLeftOvers) const;
  215. /// Debugging only. Good for checking the Trie is in shape.
  216. void paranoia(std::string const& _when, bool _enforceRefs = false) const;
  217. OverlayDB m_db; ///< Our overlay for the state tree.
  218. SecureTrieDB<Address, OverlayDB> m_state; ///< Our state tree, as an OverlayDB DB.
  219. mutable std::unordered_map<Address, Account> m_cache; ///< Our address cache. This stores the states of each address that has (or at least might have) been changed.
  220. mutable std::vector<Address> m_unchangedCacheEntries; ///< Tracks entries in m_cache that can potentially be purged if it grows too large.
  221. AddressHash m_touched; ///< Tracks all addresses touched so far.
  222. u256 m_accountStartNonce;
  223. friend std::ostream& operator<<(std::ostream& _out, State const& _s);
  224. };
  225. std::ostream& operator<<(std::ostream& _out, State const& _s);
  226. template <class DB>
  227. AddressHash commit(AccountMap const& _cache, SecureTrieDB<Address, DB>& _state)
  228. {
  229. AddressHash ret;
  230. for (auto const& i: _cache)
  231. if (i.second.isDirty())
  232. {
  233. if (!i.second.isAlive())
  234. _state.remove(i.first);
  235. else
  236. {
  237. RLPStream s(4);
  238. s << i.second.nonce() << i.second.balance();
  239. if (i.second.storageOverlay().empty())
  240. {
  241. assert(i.second.baseRoot());
  242. s.append(i.second.baseRoot());
  243. }
  244. else
  245. {
  246. SecureTrieDB<h256, DB> storageDB(_state.db(), i.second.baseRoot());
  247. for (auto const& j: i.second.storageOverlay())
  248. if (j.second)
  249. storageDB.insert(j.first, rlp(j.second));
  250. else
  251. storageDB.remove(j.first);
  252. assert(storageDB.root());
  253. s.append(storageDB.root());
  254. }
  255. if (i.second.isFreshCode())
  256. {
  257. h256 ch = sha3(i.second.code());
  258. // Store the size of the code
  259. CodeSizeCache::instance().store(ch, i.second.code().size());
  260. _state.db()->insert(ch, &i.second.code());
  261. s << ch;
  262. }
  263. else
  264. s << i.second.codeHash();
  265. _state.insert(i.first, &s.out());
  266. }
  267. ret.insert(i.first);
  268. }
  269. return ret;
  270. }
  271. }
  272. }