Block.h 14 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 Block.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 <libethcore/ChainOperationParams.h>
  28. #include <libevm/ExtVMFace.h>
  29. #include "Account.h"
  30. #include "Transaction.h"
  31. #include "TransactionReceipt.h"
  32. #include "GasPricer.h"
  33. #include "State.h"
  34. namespace dev
  35. {
  36. namespace test { class ImportTest; class StateLoader; }
  37. namespace eth
  38. {
  39. class SealEngineFace;
  40. class BlockChain;
  41. class State;
  42. class TransactionQueue;
  43. struct VerifiedBlockRef;
  44. struct BlockChat: public LogChannel { static const char* name(); static const int verbosity = 4; };
  45. struct BlockTrace: public LogChannel { static const char* name(); static const int verbosity = 5; };
  46. struct BlockDetail: public LogChannel { static const char* name(); static const int verbosity = 14; };
  47. struct BlockSafeExceptions: public LogChannel { static const char* name(); static const int verbosity = 21; };
  48. struct PopulationStatistics
  49. {
  50. double verify;
  51. double enact;
  52. };
  53. DEV_SIMPLE_EXCEPTION(ChainOperationWithUnknownBlockChain);
  54. DEV_SIMPLE_EXCEPTION(InvalidOperationOnSealedBlock);
  55. /**
  56. * @brief Active model of a block within the block chain.
  57. * Keeps track of all transactions, receipts and state for a particular block. Can apply all
  58. * needed transforms of the state for rewards and contains logic for sealing the block.
  59. */
  60. class Block
  61. {
  62. friend class ExtVM;
  63. friend class dev::test::ImportTest;
  64. friend class dev::test::StateLoader;
  65. friend class Executive;
  66. friend class BlockChain;
  67. public:
  68. // TODO: pass in ChainOperationParams rather than u256
  69. /// Default constructor; creates with a blank database prepopulated with the genesis block.
  70. Block(u256 const& _accountStartNonce): m_state(_accountStartNonce, OverlayDB(), BaseState::Empty), m_precommit(_accountStartNonce) {}
  71. /// Basic state object from database.
  72. /// Use the default when you already have a database and you just want to make a Block object
  73. /// which uses it. If you have no preexisting database then set BaseState to something other
  74. /// than BaseState::PreExisting in order to prepopulate the Trie.
  75. /// You can also set the author address.
  76. Block(BlockChain const& _bc, OverlayDB const& _db, BaseState _bs = BaseState::PreExisting, Address const& _author = Address());
  77. /// Basic state object from database.
  78. /// Use the default when you already have a database and you just want to make a Block object
  79. /// which uses it.
  80. /// Will throw InvalidRoot if the root passed is not in the database.
  81. /// You can also set the author address.
  82. Block(BlockChain const& _bc, OverlayDB const& _db, h256 const& _root, Address const& _author = Address());
  83. #if ETH_ALLOW_EMPTY_BLOCK_AND_STATE
  84. Block(): Block(Block::Null) {}
  85. explicit Block(OverlayDB const& _db, BaseState _bs = BaseState::PreExisting, Address const& _author = Address()): Block(Invalid256, _db, _bs, _author) {}
  86. Block(OverlayDB const& _db, h256 const& _root, Address const& _author = Address()): Block(Invalid256, _db, _root, _author) {}
  87. #endif
  88. enum NullType { Null };
  89. Block(NullType): m_state(0, OverlayDB(), BaseState::Empty), m_precommit(0) {}
  90. /// Construct from a given blockchain. Empty, but associated with @a _bc 's chain params.
  91. explicit Block(BlockChain const& _bc): Block(Null) { noteChain(_bc); }
  92. /// Copy state object.
  93. Block(Block const& _s);
  94. /// Copy state object.
  95. Block& operator=(Block const& _s);
  96. /// Get the author address for any transactions we do and rewards we get.
  97. Address author() const { return m_author; }
  98. /// Set the author address for any transactions we do and rewards we get.
  99. /// This causes a complete reset of current block.
  100. void setAuthor(Address const& _id) { m_author = _id; resetCurrent(); }
  101. /// Note the fact that this block is being used with a particular chain.
  102. /// Call this before using any non-const methods.
  103. void noteChain(BlockChain const& _bc);
  104. // Account-getters. All operate on the final state.
  105. /// Get an account's balance.
  106. /// @returns 0 if the address has never been used.
  107. u256 balance(Address const& _address) const { return m_state.balance(_address); }
  108. /// Get the number of transactions a particular address has sent (used for the transaction nonce).
  109. /// @returns 0 if the address has never been used.
  110. u256 transactionsFrom(Address const& _address) const { return m_state.getNonce(_address); }
  111. /// Check if the address is in use.
  112. bool addressInUse(Address const& _address) const { return m_state.addressInUse(_address); }
  113. /// Check if the address contains executable code.
  114. bool addressHasCode(Address const& _address) const { return m_state.addressHasCode(_address); }
  115. /// Get the root of the storage of an account.
  116. h256 storageRoot(Address const& _contract) const { return m_state.storageRoot(_contract); }
  117. /// Get the value of a storage position of an account.
  118. /// @returns 0 if no account exists at that address.
  119. u256 storage(Address const& _contract, u256 const& _memory) const { return m_state.storage(_contract, _memory); }
  120. /// Get the storage of an account.
  121. /// @note This is expensive. Don't use it unless you need to.
  122. /// @returns std::map<u256, u256> if no account exists at that address.
  123. std::map<u256, u256> storage(Address const& _contract) const { return m_state.storage(_contract); }
  124. /// Get the code of an account.
  125. /// @returns bytes() if no account exists at that address.
  126. bytes const& code(Address const& _contract) const { return m_state.code(_contract); }
  127. /// Get the code hash of an account.
  128. /// @returns EmptySHA3 if no account exists at that address or if there is no code associated with the address.
  129. h256 codeHash(Address const& _contract) const { return m_state.codeHash(_contract); }
  130. // General information from state
  131. /// Get the backing state object.
  132. State const& state() const { return m_state; }
  133. /// Open a DB - useful for passing into the constructor & keeping for other states that are necessary.
  134. OverlayDB const& db() const { return m_state.db(); }
  135. /// The hash of the root of our state tree.
  136. h256 rootHash() const { return m_state.rootHash(); }
  137. /// @returns the set containing all addresses currently in use in Ethereum.
  138. /// @throws InterfaceNotSupported if compiled without ETH_FATDB.
  139. std::unordered_map<Address, u256> addresses() const { return m_state.addresses(); }
  140. // For altering accounts behind-the-scenes
  141. /// Get a mutable State object which is backing this block.
  142. /// @warning Only use this is you know what you're doing. If you use it while constructing a
  143. /// normal sealable block, don't expect things to work right.
  144. State& mutableState() { return m_state; }
  145. // Information concerning ongoing transactions
  146. /// Get the remaining gas limit in this block.
  147. u256 gasLimitRemaining() const { return m_currentBlock.gasLimit() - gasUsed(); }
  148. /// Get the list of pending transactions.
  149. Transactions const& pending() const { return m_transactions; }
  150. /// Get the list of hashes of pending transactions.
  151. h256Hash const& pendingHashes() const { return m_transactionSet; }
  152. /// Get the transaction receipt for the transaction of the given index.
  153. TransactionReceipt const& receipt(unsigned _i) const { return m_receipts[_i]; }
  154. /// Get the list of pending transactions.
  155. LogEntries const& log(unsigned _i) const { return m_receipts[_i].log(); }
  156. /// Get the bloom filter of all logs that happened in the block.
  157. LogBloom logBloom() const;
  158. /// Get the bloom filter of a particular transaction that happened in the block.
  159. LogBloom const& logBloom(unsigned _i) const { return m_receipts[_i].bloom(); }
  160. /// Get the State immediately after the given number of pending transactions have been applied.
  161. /// If (_i == 0) returns the initial state of the block.
  162. /// If (_i == pending().size()) returns the final state of the block, prior to rewards.
  163. State fromPending(unsigned _i) const;
  164. // State-change operations
  165. /// Construct state object from arbitrary point in blockchain.
  166. PopulationStatistics populateFromChain(BlockChain const& _bc, h256 const& _hash, ImportRequirements::value _ir = ImportRequirements::None);
  167. /// Execute a given transaction.
  168. /// This will append @a _t to the transaction list and change the state accordingly.
  169. ExecutionResult execute(LastHashes const& _lh, Transaction const& _t, Permanence _p = Permanence::Committed, OnOpFunc const& _onOp = OnOpFunc());
  170. /// Sync our transactions, killing those from the queue that we have and assimilating those that we don't.
  171. /// @returns a list of receipts one for each transaction placed from the queue into the state and bool, true iff there are more transactions to be processed.
  172. std::pair<TransactionReceipts, bool> sync(BlockChain const& _bc, TransactionQueue& _tq, GasPricer const& _gp, unsigned _msTimeout = 100);
  173. /// Sync our state with the block chain.
  174. /// This basically involves wiping ourselves if we've been superceded and rebuilding from the transaction queue.
  175. bool sync(BlockChain const& _bc);
  176. /// Sync with the block chain, but rather than synching to the latest block, instead sync to the given block.
  177. bool sync(BlockChain const& _bc, h256 const& _blockHash, BlockHeader const& _bi = BlockHeader());
  178. /// Execute all transactions within a given block.
  179. /// @returns the additional total difficulty.
  180. u256 enactOn(VerifiedBlockRef const& _block, BlockChain const& _bc);
  181. /// Returns back to a pristine state after having done a playback.
  182. /// @arg _fullCommit if true flush everything out to disk. If false, this effectively only validates
  183. /// the block since all state changes are ultimately reversed.
  184. void cleanup(bool _fullCommit);
  185. /// Sets m_currentBlock to a clean state, (i.e. no change from m_previousBlock) and
  186. /// optionally modifies the timestamp.
  187. void resetCurrent(u256 const& _timestamp = u256(utcTime()));
  188. // Sealing
  189. /// Prepares the current state for mining.
  190. /// Commits all transactions into the trie, compiles uncles and transactions list, applies all
  191. /// rewards and populates the current block header with the appropriate hashes.
  192. /// The only thing left to do after this is to actually mine().
  193. ///
  194. /// This may be called multiple times and without issue.
  195. void commitToSeal(BlockChain const& _bc, bytes const& _extraData = {});
  196. /// Pass in a properly sealed header matching this block.
  197. /// @returns true iff we were previously committed to sealing, the header is valid and it
  198. /// corresponds to this block.
  199. /// TODO: verify it prior to calling this.
  200. /** Commit to DB and build the final block if the previous call to mine()'s result is completion.
  201. * Typically looks like:
  202. * @code
  203. * while (!isSealed)
  204. * {
  205. * // lock
  206. * commitToSeal(_blockChain); // will call uncommitToSeal if a repeat.
  207. * sealBlock(sealedHeader);
  208. * // unlock
  209. * @endcode
  210. */
  211. bool sealBlock(bytes const& _header) { return sealBlock(&_header); }
  212. bool sealBlock(bytesConstRef _header);
  213. /// @returns true if sealed - in this case you can no longer append transactions.
  214. bool isSealed() const { return !m_currentBytes.empty(); }
  215. /// Get the complete current block, including valid nonce.
  216. /// Only valid when isSealed() is true.
  217. bytes const& blockData() const { return m_currentBytes; }
  218. /// Get the header information on the present block.
  219. BlockHeader const& info() const { return m_currentBlock; }
  220. private:
  221. SealEngineFace* sealEngine() const;
  222. /// Undo the changes to the state for committing to mine.
  223. void uncommitToSeal();
  224. /// Retrieve all information about a given address into the cache.
  225. /// If _requireMemory is true, grab the full memory should it be a contract item.
  226. /// If _forceCreate is true, then insert a default item into the cache, in the case it doesn't
  227. /// exist in the DB.
  228. void ensureCached(Address const& _a, bool _requireCode, bool _forceCreate) const;
  229. /// Retrieve all information about a given address into a cache.
  230. void ensureCached(std::unordered_map<Address, Account>& _cache, Address const& _a, bool _requireCode, bool _forceCreate) const;
  231. /// Execute the given block, assuming it corresponds to m_currentBlock.
  232. /// Throws on failure.
  233. u256 enact(VerifiedBlockRef const& _block, BlockChain const& _bc);
  234. /// Finalise the block, applying the earned rewards.
  235. void applyRewards(std::vector<BlockHeader> const& _uncleBlockHeaders, u256 const& _blockReward);
  236. /// @returns gas used by transactions thus far executed.
  237. u256 gasUsed() const { return m_receipts.size() ? m_receipts.back().gasUsed() : 0; }
  238. /// Performs irregular modifications right after initialization, e.g. to implement a hard fork.
  239. void performIrregularModifications();
  240. /// Provide a standard VM trace for debugging purposes.
  241. std::string vmTrace(bytesConstRef _block, BlockChain const& _bc, ImportRequirements::value _ir);
  242. State m_state; ///< Our state tree, as an OverlayDB DB.
  243. Transactions m_transactions; ///< The current list of transactions that we've included in the state.
  244. TransactionReceipts m_receipts; ///< The corresponding list of transaction receipts.
  245. h256Hash m_transactionSet; ///< The set of transaction hashes that we've included in the state.
  246. State m_precommit; ///< State at the point immediately prior to rewards.
  247. BlockHeader m_previousBlock; ///< The previous block's information.
  248. BlockHeader m_currentBlock; ///< The current block's information.
  249. bytes m_currentBytes; ///< The current block's bytes.
  250. bool m_committedToSeal = false; ///< Have we committed to mine on the present m_currentBlock?
  251. bytes m_currentTxs; ///< The RLP-encoded block of transactions.
  252. bytes m_currentUncles; ///< The RLP-encoded block of uncles.
  253. Address m_author; ///< Our address (i.e. the address to which fees go).
  254. SealEngineFace* m_sealEngine = nullptr; ///< The chain's seal engine.
  255. friend std::ostream& operator<<(std::ostream& _out, Block const& _s);
  256. };
  257. std::ostream& operator<<(std::ostream& _out, Block const& _s);
  258. }
  259. }