25 #include <boost/filesystem.hpp> 26 #include <boost/timer.hpp> 44 namespace fs = boost::filesystem;
46 #define ETH_TIMED_ENACTMENTS 0 48 static const unsigned c_maxSyncTransactions = 1024;
136 BOOST_THROW_EXCEPTION(ChainOperationWithUnknownBlockChain());
159 cwarn <<
"Invalid block given for state population: " << _h;
211 auto b = _bc.
block(_block);
218 cerr <<
"ERROR: Corrupt block-chain! Delete your block-chain DB and restart." << endl;
219 cerr << diagnostic_information(_e) << endl;
221 catch (std::exception
const& _e)
224 cerr <<
"ERROR: Corrupt block-chain! Delete your block-chain DB and restart." << endl;
225 cerr << _e.what() << endl;
250 cwarn <<
"Unable to sync to" << bi.
hash() <<
"; state root" << bi.
stateRoot() <<
"not found in database.";
251 cwarn <<
"Database corrupt: contains block without stateRoot:" << bi;
252 cwarn <<
"Try rescuing the database by running: eth --rescue";
253 BOOST_THROW_EXCEPTION(InvalidStateRoot() <<
errinfo_target(bi.stateRoot()));
266 std::vector<h256> chain;
269 chain.push_back(bi.
hash());
279 for (
auto it = chain.rbegin(); it != chain.rend(); ++it)
289 cerr <<
"ERROR: Corrupt block-chain! Delete your block-chain DB and restart." << endl;
290 cerr << boost::current_exception_diagnostic_information() << endl;
304 BOOST_THROW_EXCEPTION(InvalidOperationOnSealedBlock());
309 pair<TransactionReceipts, bool> ret;
312 ret.second = (ts.size() == c_maxSyncTransactions);
316 auto deadline = chrono::steady_clock::now() + chrono::milliseconds(msTimeout);
318 for (
int goodTxs =
max(0, (
int)ts.size() - 1); goodTxs < (int)ts.size(); )
321 for (
auto const& t: ts)
326 if (t.gasPrice() >= _gp.
ask(*
this))
336 else if (t.gasPrice() < _gp.
ask(*
this) * 9 / 10)
338 clog(
StateTrace) << t.sha3() <<
"Dropping El Cheapo transaction (<90% of ask price)";
344 bigint const& req = *boost::get_error_info<errinfo_required>(in);
345 bigint const& got = *boost::get_error_info<errinfo_got>(in);
350 clog(
StateTrace) << t.sha3() <<
"Dropping old transaction (nonce too low)";
353 else if (got > req + _tq.
waiting(t.sender()))
356 clog(
StateTrace) << t.sha3() <<
"Dropping new transaction (too many nonces ahead)";
364 bigint const& got = *boost::get_error_info<errinfo_got>(
e);
367 clog(
StateTrace) << t.sha3() <<
"Dropping over-gassy transaction (gas > block's gas limit)";
372 clog(
StateTrace) << t.sha3() <<
"Temporarily no gas left in current block (txs gas > block's gas limit)";
382 clog(
StateTrace) << t.sha3() <<
"Dropping invalid transaction:" << diagnostic_information(_e);
385 catch (std::exception
const&)
389 cwarn << t.sha3() <<
"Transaction caused low-level exception :(";
392 if (chrono::steady_clock::now() > deadline)
405 #if ETH_TIMED_ENACTMENTS 407 double populateVerify;
408 double populateGrand;
417 #if ETH_TIMED_ENACTMENTS 426 #if ETH_TIMED_ENACTMENTS 434 #if ETH_TIMED_ENACTMENTS 440 auto ret =
enact(_block, _bc);
442 #if ETH_TIMED_ENACTMENTS 444 if (populateVerify + populateGrand + syncReset + enactment > 0.5)
445 clog(
StateChat) <<
"popVer/popGrand/syncReset/enactment = " << populateVerify <<
"/" << populateGrand <<
"/" << syncReset <<
"/" << enactment;
464 BOOST_THROW_EXCEPTION(InvalidParentHash());
479 vector<bytes> receipts;
502 receipts.push_back(receiptRLP.
out());
512 InvalidReceiptsStateRoot ex;
516 BOOST_THROW_EXCEPTION(ex);
524 BOOST_THROW_EXCEPTION(ex);
531 if (rlp[2].itemCount() > 2)
536 BOOST_THROW_EXCEPTION(ex);
539 vector<BlockHeader> rewarded;
547 for (
auto const& i: rlp[2])
551 auto h =
sha3(i.data());
552 if (excluded.count(
h))
558 BOOST_THROW_EXCEPTION(ex);
566 if (!_bc.
isKnown(uncle.parentHash()))
584 BOOST_THROW_EXCEPTION(ex);
591 BOOST_THROW_EXCEPTION(ex);
603 for (
unsigned i = 1; i < depth; expectedUncleParent = _bc.
details(expectedUncleParent).
parent, ++i) {}
604 if (expectedUncleParent != uncleParent.hash())
606 UncleParentNotInChain ex;
609 BOOST_THROW_EXCEPTION(ex);
613 rewarded.push_back(uncle);
652 BOOST_THROW_EXCEPTION(InvalidOperationOnSealedBlock());
668 return resultReceipt.first;
673 u256 r = _blockReward;
674 for (
auto const& i: _uncleBlockHeaders)
677 r += _blockReward / 32;
685 if (daoHardfork != 0 &&
info().number() == daoHardfork)
687 Address recipient(
"0xbf4ed7b27f1d666546e30d74d50d173d20bca754");
689 for (
Address const& dao: allDAOs)
698 BOOST_THROW_EXCEPTION(InvalidOperationOnSealedBlock());
707 vector<BlockHeader> uncleBlockHeaders;
710 unsigned unclesCount = 0;
721 for (
auto const& u: us)
722 if (!excluded.count(u))
724 uncleBlockHeaders.push_back(_bc.
info(u));
727 if (unclesCount == 2)
747 receiptsMap.insert(std::make_pair(k.
out(), receiptrlp.
out()));
751 transactionsMap.insert(std::make_pair(k.
out(), txrlp.
out()));
856 if (isChannelVisible<StateTrace>())
872 if (isChannelVisible<StateTrace>())
902 for (
auto const& tr: rlp[1])
907 ret += (ret.empty() ?
"[" :
",") + st.
json();
910 return ret.empty() ?
"[]" : (ret +
"]");
h256Hash allKinFrom(h256 const &_parent, unsigned _generations) const
Get all blocks not allowed as uncles given a parent (i.e.
u256 balance(Address const &_id) const
Get an account's balance.
Adapted from code found on http://stackoverflow.com/questions/180947/base64-decode-snippet-in-c Origi...
boost::error_info< struct tag_unclesExcluded, h256Hash > errinfo_unclesExcluded
std::string toHex(T const &_data, int _w=2, HexPrefix _prefix=HexPrefix::DontAdd)
boost::tuple< errinfo_required_h256, errinfo_got_h256 > Hash256RequirementError
std::pair< TransactionReceipts, bool > sync(BlockChain const &_bc, TransactionQueue &_tq, GasPricer const &_gp, unsigned _msTimeout=100)
Sync our transactions, killing those from the queue that we have and assimilating those that we don't...
std::map< bytes, bytes > BytesMap
ChainParams const & chainParams() const
BlockDetails details(h256 const &_hash) const
Get the familial details concerning a block (or the most recent mined if none given). Thread-safe.
void commit(CommitBehaviour _commitBehaviour)
Commit all changes waiting in the address cache to the DB.
A queue of Transactions, each stored as RLP.
boost::error_info< struct tag_receipts, std::vector< bytes >> errinfo_receipts
bool m_committedToSeal
Have we committed to mine on the present m_currentBlock?
Transactions m_transactions
The current list of transactions that we've included in the state.
ChainOperationParams const & chainParams() const
BlockHeader info(h256 const &_hash) const
Get the partial-header of a block (or the most recent mined if none given). Thread-safe.
State fromPending(unsigned _i) const
Get the State immediately after the given number of pending transactions have been applied...
boost::error_info< struct tag_uncleIndex, unsigned > errinfo_uncleIndex
Implements the blockchain database.
SealEngineFace * sealEngine() const
bytes rlp(_T _t)
Export a single item in RLP format, returning a byte array.
boost::multiprecision::number< boost::multiprecision::cpp_int_backend<>> bigint
void noteAccountStartNonce(u256 const &_actual)
std::ostream & operator<<(std::ostream &_out, BlockHeader const &_bi)
bytes const & out() const
Read the byte stream.
void noteChain(BlockChain const &_bc)
Note the fact that this block is being used with a particular chain.
boost::error_info< struct tag_currentNumber, u256 > errinfo_currentNumber
void drop(h256 const &_txHash)
Remove transaction from the queue.
LastHashes lastHashes() const
Get the last N hashes for a given block. (N is determined by the LastHashes type.) ...
u256 const & accountStartNonce() const
Get the account start nonce. May be required.
bytes m_currentBytes
The current block's bytes.
void commitToSeal(BlockChain const &_bc, bytes const &_extraData={})
Prepares the current state for mining.
std::hash for asio::adress
assert(len-trim+(2 *lenIndices)<=WIDTH)
boost::error_info< struct tag_max, bigint > errinfo_max
bytes headerData(h256 const &_hash) const
Get a block (RLP format) for the given hash (or the most recent mined if none given). Thread-safe.
void uncommitToSeal()
Undo the changes to the state for committing to mine.
Block(u256 const &_accountStartNonce)
Default constructor; creates with a blank database prepopulated with the genesis block.
#define DEV_TIMED_ABOVE(S, MS)
TransactionReceipts m_receipts
The corresponding list of transaction receipts.
Description of the result of executing a transaction.
Model of an Ethereum state, essentially a facade for the trie.
OverlayDB const & db() const
bytesConstRef block
Block data reference.
u256 enactOn(VerifiedBlockRef const &_block, BlockChain const &_bc)
Execute all transactions within a given block.
std::string lookup(h256 const &_h) const
void applyRewards(std::vector< BlockHeader > const &_uncleBlockHeaders, u256 const &_blockReward)
Finalise the block, applying the earned rewards.
Transactions topTransactions(unsigned _limit, h256Hash const &_avoid=h256Hash()) const
Get top transactions from the queue.
h256 hash256(BytesMap const &_s)
Active model of a block within the block chain.
boost::error_info< struct tag_hash, h256 > errinfo_hash256
std::vector< h256 > LastHashes
Check the basic structure of the transactions.
std::string json(bool _styled=false) const
Base class for all exceptions.
std::string vmTrace(bytesConstRef _block, BlockChain const &_bc, ImportRequirements::value _ir)
Provide a standard VM trace for debugging purposes.
std::pair< ExecutionResult, TransactionReceipt > execute(EnvInfo const &_envInfo, SealEngineFace const &_sealEngine, Transaction const &_t, Permanence _p=Permanence::Committed, OnOpFunc const &_onOp=OnOpFunc())
Execute a given transaction.
void cleanup(bool _fullCommit)
Returns back to a pristine state after having done a playback.
PopulationStatistics populateFromChain(BlockChain const &_bc, h256 const &_hash, ImportRequirements::value _ir=ImportRequirements::None)
Construct state object from arbitrary point in blockchain.
LogBloom logBloom() const
Get the bloom filter of all logs that happened in the block.
Address m_author
Our address (i.e. the address to which fees go).
BlockHeader m_currentBlock
The current block's information.
BlockGetAndPut< word32, BigEndian > Block
boost::error_info< struct tag_got, bigint > errinfo_got
h256 currentHash() const
Get a given block (RLP format). Thread-safe.
SealEngineFace * m_sealEngine
The chain's seal engine.
std::vector< byte > bytes
Fixed-size raw-byte array container type, with an API optimised for storing hashes.
BlockHeader m_previousBlock
The previous block's information.
std::function< void(uint64_t, uint64_t, Instruction, bigint, bigint, bigint, VM *, ExtVMFace const *)> OnOpFunc
RLPStream & appendList(size_t _items)
Appends a list.
boost::error_info< struct tag_target, h256 > errinfo_target
bytes asBytes(std::string const &_b)
Converts a string to a byte array containing the string's (byte) data.
h256 sha3(IncludeSignature _sig=WithSignature) const
bool sealBlock(bytes const &_header)
Pass in a properly sealed header matching this block.
boost::multiprecision::number< boost::multiprecision::cpp_int_backend< 256, 256, boost::multiprecision::unsigned_magnitude, boost::multiprecision::unchecked, void >> u256
bool isKnown(h256 const &_hash, bool _isCurrent=true) const
Returns true if the given block is known (though not necessarily a part of the canon chain)...
h160s Addresses
A vector of Ethereum addresses.
void resetCurrent(u256 const &_timestamp=u256(utcTime()))
Sets m_currentBlock to a clean state, (i.e.
Encodes a transaction, ready to be exported to or freshly imported from RLP.
OverlayDB const & db() const
Open a DB - useful for passing into the constructor & keeping for other states that are necessary...
void setRoot(h256 const &_root)
Resets any uncommitted changes to the cache.
h256 rootHash() const
The hash of the root of our state tree.
dev::Addresses childDaos()
u256 enact(VerifiedBlockRef const &_block, BlockChain const &_bc)
Execute the given block, assuming it corresponds to m_currentBlock.
State m_precommit
State at the point immediately prior to rewards.
void setFuture(h256 const &_t)
Mark transaction as future.
u256 u256Param(std::string const &_name) const
Convenience method to get an otherParam as a u256 int.
Verified block info, does not hold block data, but a reference instead.
virtual void transferBalance(Address const &_from, Address const &_to, u256 const &_value)
Transfers "the balance _value between two accounts.
h256Hash m_transactionSet
The set of transaction hashes that we've included in the state.
boost::error_info< struct tag_comment, std::string > errinfo_comment
bytes m_currentUncles
The RLP-encoded block of uncles.
bool sha3(bytesConstRef _input, bytesRef o_output)
Calculate SHA3-256 hash of the given input and load it into the given output.
virtual void addBalance(Address const &_id, u256 const &_amount)
Add some amount to balance.
h256 rootHash() const
The hash of the root of our state tree.
virtual void populateFromParent(BlockHeader &_bi, BlockHeader const &_parent) const
Don't forget to call Super::populateFromParent when subclassing & overriding.
h256 genesisHash() const
Get the hash of the genesis block. Thread-safe.
ExecutionResult execute(LastHashes const &_lh, Transaction const &_t, Permanence _p=Permanence::Committed, OnOpFunc const &_onOp=OnOpFunc())
Execute a given transaction.
std::vector< Transaction > transactions
Verified list of block transactions.
std::unordered_set< h256 > h256Hash
void performIrregularModifications()
Performs irregular modifications right after initialization, e.g. to implement a hard fork...
void swapOut(bytes &_dest)
Swap the contents of the output stream out for some other byte array.
bytes block(h256 const &_hash) const
Get a block (RLP format) for the given hash (or the most recent mined if none given). Thread-safe.
h256 orderedTrieRoot(std::vector< bytes > const &_data)
bytes m_currentTxs
The RLP-encoded block of transactions.
boost::error_info< struct tag_transactionIndex, unsigned > errinfo_transactionIndex
u256 blockReward
General chain params.
virtual u256 ask(Block const &) const =0
boost::error_info< struct tag_uncleNumber, u256 > errinfo_uncleNumber
boost::tuple< errinfo_required, errinfo_got > RequirementError
Class for writing to an RLP bytestream.
BlockHeader info
Prepopulated block info.
Block & operator=(Block const &_s)
Copy state object.
RLPStream & appendRaw(bytesConstRef _rlp, size_t _itemCount=1)
Appends raw (pre-serialised) RLP data. Use with caution.
unsigned waiting(Address const &_a) const
Get number of pending transactions for account.
#define DEV_TIMED_FUNCTION_ABOVE(MS)
Class for interpreting Recursive Linear-Prefix Data.
State m_state
Our state tree, as an OverlayDB DB.
SealEngineFace * sealEngine() const
VerifiedBlockRef verifyBlock(bytesConstRef _block, std::function< void(Exception &)> const &_onBad, ImportRequirements::value _ir=ImportRequirements::OutOfOrderChecks) const
Verify block and prepare it for enactment.
BlockHeader const & info() const
Get the header information on the present block.
boost::tuple< errinfo_required_LogBloom, errinfo_got_LogBloom > LogBloomRequirementError