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