Fabcoin Core  0.16.2
P2P Digital Currency
Block.cpp
Go to the documentation of this file.
1 /*
2  This file is part of cpp-ethereum.
3 
4  cpp-ethereum is free software: you can redistribute it and/or modify
5  it under the terms of the GNU General Public License as published by
6  the Free Software Foundation, either version 3 of the License, or
7  (at your option) any later version.
8 
9  cpp-ethereum is distributed in the hope that it will be useful,
10  but WITHOUT ANY WARRANTY; without even the implied warranty of
11  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12  GNU General Public License for more details.
13 
14  You should have received a copy of the GNU General Public License
15  along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
16 */
22 #include "Block.h"
23 
24 #include <ctime>
25 #include <boost/filesystem.hpp>
26 #include <boost/timer.hpp>
27 #include <libdevcore/CommonIO.h>
28 #include <libdevcore/Assertions.h>
29 #include <libdevcore/TrieHash.h>
30 #include <libevmcore/Instruction.h>
31 #include <libethcore/Exceptions.h>
32 #include <libethcore/SealEngine.h>
33 #include <libevm/VMFactory.h>
34 #include "BlockChain.h"
35 #include "Defaults.h"
36 #include "ExtVM.h"
37 #include "Executive.h"
38 #include "BlockChain.h"
39 #include "TransactionQueue.h"
40 #include "GenesisInfo.h"
41 using namespace std;
42 using namespace dev;
43 using namespace dev::eth;
44 namespace fs = boost::filesystem;
45 
46 #define ETH_TIMED_ENACTMENTS 0
47 
48 static const unsigned c_maxSyncTransactions = 1024;
49 
50 const char* BlockSafeExceptions::name() { return EthViolet "⚙" EthBlue " ℹ"; }
51 const char* BlockDetail::name() { return EthViolet "⚙" EthWhite " ◌"; }
52 const char* BlockTrace::name() { return EthViolet "⚙" EthGray " ◎"; }
53 const char* BlockChat::name() { return EthViolet "⚙" EthWhite " ◌"; }
54 
55 Block::Block(BlockChain const& _bc, OverlayDB const& _db, BaseState _bs, Address const& _author):
56  m_state(Invalid256, _db, _bs),
57  m_precommit(Invalid256),
58  m_author(_author)
59 {
60  noteChain(_bc);
63 // assert(m_state.root() == m_previousBlock.stateRoot());
64 }
65 
66 Block::Block(BlockChain const& _bc, OverlayDB const& _db, h256 const& _root, Address const& _author):
69  m_author(_author)
70 {
71  noteChain(_bc);
72  m_state.setRoot(_root);
75 // assert(m_state.root() == m_previousBlock.stateRoot());
76 }
77 
78 Block::Block(Block const& _s):
79  m_state(_s.m_state),
83  m_precommit(_s.m_state),
87  m_author(_s.m_author),
89 {
90  m_committedToSeal = false;
91 }
92 
94 {
95  if (&_s == this)
96  return *this;
97 
98  m_state = _s.m_state;
100  m_receipts = _s.m_receipts;
105  m_author = _s.m_author;
107 
109  m_committedToSeal = false;
110  return *this;
111 }
112 
113 void Block::resetCurrent(u256 const& _timestamp)
114 {
115  m_transactions.clear();
116  m_receipts.clear();
117  m_transactionSet.clear();
121  m_currentBytes.clear();
123 
124  // TODO: check.
125 
128  m_committedToSeal = false;
129 
131 }
132 
134 {
135  if (!m_sealEngine)
136  BOOST_THROW_EXCEPTION(ChainOperationWithUnknownBlockChain());
137  return m_sealEngine;
138 }
139 
140 void Block::noteChain(BlockChain const& _bc)
141 {
142  if (!m_sealEngine)
143  {
146  m_sealEngine = _bc.sealEngine();
147  }
148 }
149 
151 {
152  noteChain(_bc);
153 
154  PopulationStatistics ret { 0.0, 0.0 };
155 
156  if (!_bc.isKnown(_h))
157  {
158  // Might be worth throwing here.
159  cwarn << "Invalid block given for state population: " << _h;
160  BOOST_THROW_EXCEPTION(BlockNotFound() << errinfo_target(_h));
161  }
162 
163  auto b = _bc.block(_h);
164  BlockHeader bi(b); // No need to check - it's already in the DB.
165  if (bi.number())
166  {
167  // Non-genesis:
168 
169  // 1. Start at parent's end state (state root).
170  BlockHeader bip(_bc.block(bi.parentHash()));
171  sync(_bc, bi.parentHash(), bip);
172 
173  // 2. Enact the block's transactions onto this state.
174  m_author = bi.author();
175  Timer t;
176  auto vb = _bc.verifyBlock(&b, function<void(Exception&)>(), _ir | ImportRequirements::TransactionBasic);
177  ret.verify = t.elapsed();
178  t.restart();
179  enact(vb, _bc);
180  ret.enact = t.elapsed();
181  }
182  else
183  {
184  // Genesis required:
185  // We know there are no transactions, so just populate directly.
186  m_state = State(m_state.accountStartNonce(), m_state.db(), BaseState::Empty); // TODO: try with PreExisting.
187  sync(_bc, _h, bi);
188  }
189 
190  return ret;
191 }
192 
193 bool Block::sync(BlockChain const& _bc)
194 {
195  return sync(_bc, _bc.currentHash());
196 }
197 
198 bool Block::sync(BlockChain const& _bc, h256 const& _block, BlockHeader const& _bi)
199 {
200  noteChain(_bc);
201 
202  bool ret = false;
203  // BLOCK
204  BlockHeader bi = _bi ? _bi : _bc.info(_block);
205 #if ETH_PARANOIA
206  if (!bi)
207  while (1)
208  {
209  try
210  {
211  auto b = _bc.block(_block);
212  bi.populate(b);
213  break;
214  }
215  catch (Exception const& _e)
216  {
217  // TODO: Slightly nicer handling? :-)
218  cerr << "ERROR: Corrupt block-chain! Delete your block-chain DB and restart." << endl;
219  cerr << diagnostic_information(_e) << endl;
220  }
221  catch (std::exception const& _e)
222  {
223  // TODO: Slightly nicer handling? :-)
224  cerr << "ERROR: Corrupt block-chain! Delete your block-chain DB and restart." << endl;
225  cerr << _e.what() << endl;
226  }
227  }
228 #endif
229  if (bi == m_currentBlock)
230  {
231  // We mined the last block.
232  // Our state is good - we just need to move on to next.
234  resetCurrent();
235  ret = true;
236  }
237  else if (bi == m_previousBlock)
238  {
239  // No change since last sync.
240  // Carry on as we were.
241  }
242  else
243  {
244  // New blocks available, or we've switched to a different branch. All change.
245  // Find most recent state dump and replay what's left.
246  // (Most recent state dump might end up being genesis.)
247 
248  if (m_state.db().lookup(bi.stateRoot()).empty()) // TODO: API in State for this?
249  {
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()));
254  }
255  m_previousBlock = bi;
256  resetCurrent();
257  ret = true;
258  }
259 #if ALLOW_REBUILD
260  else
261  {
262  // New blocks available, or we've switched to a different branch. All change.
263  // Find most recent state dump and replay what's left.
264  // (Most recent state dump might end up being genesis.)
265 
266  std::vector<h256> chain;
267  while (bi.number() != 0 && m_db.lookup(bi.stateRoot()).empty()) // while we don't have the state root of the latest block...
268  {
269  chain.push_back(bi.hash()); // push back for later replay.
270  bi.populate(_bc.block(bi.parentHash())); // move to parent.
271  }
272 
273  m_previousBlock = bi;
274  resetCurrent();
275 
276  // Iterate through in reverse, playing back each of the blocks.
277  try
278  {
279  for (auto it = chain.rbegin(); it != chain.rend(); ++it)
280  {
281  auto b = _bc.block(*it);
282  enact(&b, _bc, _ir);
283  cleanup(true);
284  }
285  }
286  catch (...)
287  {
288  // TODO: Slightly nicer handling? :-)
289  cerr << "ERROR: Corrupt block-chain! Delete your block-chain DB and restart." << endl;
290  cerr << boost::current_exception_diagnostic_information() << endl;
291  exit(1);
292  }
293 
294  resetCurrent();
295  ret = true;
296  }
297 #endif
298  return ret;
299 }
300 
301 pair<TransactionReceipts, bool> Block::sync(BlockChain const& _bc, TransactionQueue& _tq, GasPricer const& _gp, unsigned msTimeout)
302 {
303  if (isSealed())
304  BOOST_THROW_EXCEPTION(InvalidOperationOnSealedBlock());
305 
306  noteChain(_bc);
307 
308  // TRANSACTIONS
309  pair<TransactionReceipts, bool> ret;
310 
311  auto ts = _tq.topTransactions(c_maxSyncTransactions, m_transactionSet);
312  ret.second = (ts.size() == c_maxSyncTransactions); // say there's more to the caller if we hit the limit
313 
314  LastHashes lh;
315 
316  auto deadline = chrono::steady_clock::now() + chrono::milliseconds(msTimeout);
317 
318  for (int goodTxs = max(0, (int)ts.size() - 1); goodTxs < (int)ts.size(); )
319  {
320  goodTxs = 0;
321  for (auto const& t: ts)
322  if (!m_transactionSet.count(t.sha3()))
323  {
324  try
325  {
326  if (t.gasPrice() >= _gp.ask(*this))
327  {
328 // Timer t;
329  if (lh.empty())
330  lh = _bc.lastHashes();
331  execute(lh, t);
332  ret.first.push_back(m_receipts.back());
333  ++goodTxs;
334 // cnote << "TX took:" << t.elapsed() * 1000;
335  }
336  else if (t.gasPrice() < _gp.ask(*this) * 9 / 10)
337  {
338  clog(StateTrace) << t.sha3() << "Dropping El Cheapo transaction (<90% of ask price)";
339  _tq.drop(t.sha3());
340  }
341  }
342  catch (InvalidNonce const& in)
343  {
344  bigint const& req = *boost::get_error_info<errinfo_required>(in);
345  bigint const& got = *boost::get_error_info<errinfo_got>(in);
346 
347  if (req > got)
348  {
349  // too old
350  clog(StateTrace) << t.sha3() << "Dropping old transaction (nonce too low)";
351  _tq.drop(t.sha3());
352  }
353  else if (got > req + _tq.waiting(t.sender()))
354  {
355  // too new
356  clog(StateTrace) << t.sha3() << "Dropping new transaction (too many nonces ahead)";
357  _tq.drop(t.sha3());
358  }
359  else
360  _tq.setFuture(t.sha3());
361  }
362  catch (BlockGasLimitReached const& e)
363  {
364  bigint const& got = *boost::get_error_info<errinfo_got>(e);
365  if (got > m_currentBlock.gasLimit())
366  {
367  clog(StateTrace) << t.sha3() << "Dropping over-gassy transaction (gas > block's gas limit)";
368  _tq.drop(t.sha3());
369  }
370  else
371  {
372  clog(StateTrace) << t.sha3() << "Temporarily no gas left in current block (txs gas > block's gas limit)";
373  //_tq.drop(t.sha3());
374  // Temporarily no gas left in current block.
375  // OPTIMISE: could note this and then we don't evaluate until a block that does have the gas left.
376  // for now, just leave alone.
377  }
378  }
379  catch (Exception const& _e)
380  {
381  // Something else went wrong - drop it.
382  clog(StateTrace) << t.sha3() << "Dropping invalid transaction:" << diagnostic_information(_e);
383  _tq.drop(t.sha3());
384  }
385  catch (std::exception const&)
386  {
387  // Something else went wrong - drop it.
388  _tq.drop(t.sha3());
389  cwarn << t.sha3() << "Transaction caused low-level exception :(";
390  }
391  }
392  if (chrono::steady_clock::now() > deadline)
393  {
394  ret.second = true; // say there's more to the caller if we ended up crossing the deadline.
395  break;
396  }
397  }
398  return ret;
399 }
400 
401 u256 Block::enactOn(VerifiedBlockRef const& _block, BlockChain const& _bc)
402 {
403  noteChain(_bc);
404 
405 #if ETH_TIMED_ENACTMENTS
406  Timer t;
407  double populateVerify;
408  double populateGrand;
409  double syncReset;
410  double enactment;
411 #endif
412 
413  // Check family:
414  BlockHeader biParent = _bc.info(_block.info.parentHash());
415  _block.info.verify(CheckNothingNew/*CheckParent*/, biParent);
416 
417 #if ETH_TIMED_ENACTMENTS
418  populateVerify = t.elapsed();
419  t.restart();
420 #endif
421 
422  BlockHeader biGrandParent;
423  if (biParent.number())
424  biGrandParent = _bc.info(biParent.parentHash());
425 
426 #if ETH_TIMED_ENACTMENTS
427  populateGrand = t.elapsed();
428  t.restart();
429 #endif
430 
431  sync(_bc, _block.info.parentHash(), BlockHeader());
432  resetCurrent();
433 
434 #if ETH_TIMED_ENACTMENTS
435  syncReset = t.elapsed();
436  t.restart();
437 #endif
438 
439  m_previousBlock = biParent;
440  auto ret = enact(_block, _bc);
441 
442 #if ETH_TIMED_ENACTMENTS
443  enactment = t.elapsed();
444  if (populateVerify + populateGrand + syncReset + enactment > 0.5)
445  clog(StateChat) << "popVer/popGrand/syncReset/enactment = " << populateVerify << "/" << populateGrand << "/" << syncReset << "/" << enactment;
446 #endif
447  return ret;
448 }
449 
450 u256 Block::enact(VerifiedBlockRef const& _block, BlockChain const& _bc)
451 {
452  noteChain(_bc);
453 
455 
456  // m_currentBlock is assumed to be prepopulated and reset.
457 #if !ETH_RELEASE
458  assert(m_previousBlock.hash() == _block.info.parentHash());
460 #endif
461 
463  // Internal client error.
464  BOOST_THROW_EXCEPTION(InvalidParentHash());
465 
466  // Populate m_currentBlock with the correct values.
468  m_currentBlock = _block.info;
469 
470 // cnote << "playback begins:" << m_currentBlock.hash() << "(without: " << m_currentBlock.hash(WithoutSeal) << ")";
471 // cnote << m_state;
472 
473  LastHashes lh;
474  DEV_TIMED_ABOVE("lastHashes", 500)
476 
477  RLP rlp(_block.block);
478 
479  vector<bytes> receipts;
480 
481  // All ok with the block generally. Play back the transactions now...
482  unsigned i = 0;
483  DEV_TIMED_ABOVE("txExec", 500)
484  for (Transaction const& tr: _block.transactions)
485  {
486  try
487  {
489 // cnote << "Enacting transaction: " << tr.nonce() << tr.from() << state().transactionsFrom(tr.from()) << tr.value();
490  execute(lh, tr);
491 // cnote << "Now: " << tr.from() << state().transactionsFrom(tr.from());
492 // cnote << m_state;
493  }
494  catch (Exception& ex)
495  {
496  ex << errinfo_transactionIndex(i);
497  throw;
498  }
499 
500  RLPStream receiptRLP;
501  m_receipts.back().streamRLP(receiptRLP);
502  receipts.push_back(receiptRLP.out());
503  ++i;
504  }
505 
506  h256 receiptsRoot;
507  DEV_TIMED_ABOVE(".receiptsRoot()", 500)
508  receiptsRoot = orderedTrieRoot(receipts);
509 
510  if (receiptsRoot != m_currentBlock.receiptsRoot())
511  {
512  InvalidReceiptsStateRoot ex;
513  ex << Hash256RequirementError(receiptsRoot, m_currentBlock.receiptsRoot());
514  ex << errinfo_receipts(receipts);
515 // ex << errinfo_vmtrace(vmTrace(_block.block, _bc, ImportRequirements::None));
516  BOOST_THROW_EXCEPTION(ex);
517  }
518 
519  if (m_currentBlock.logBloom() != logBloom())
520  {
521  InvalidLogBloom ex;
523  ex << errinfo_receipts(receipts);
524  BOOST_THROW_EXCEPTION(ex);
525  }
526 
527  // Initialise total difficulty calculation.
528  u256 tdIncrease = m_currentBlock.difficulty();
529 
530  // Check uncles & apply their rewards to state.
531  if (rlp[2].itemCount() > 2)
532  {
533  TooManyUncles ex;
534  ex << errinfo_max(2);
535  ex << errinfo_got(rlp[2].itemCount());
536  BOOST_THROW_EXCEPTION(ex);
537  }
538 
539  vector<BlockHeader> rewarded;
540  h256Hash excluded;
541  DEV_TIMED_ABOVE("allKin", 500)
542  excluded = _bc.allKinFrom(m_currentBlock.parentHash(), 6);
543  excluded.insert(m_currentBlock.hash());
544 
545  unsigned ii = 0;
546  DEV_TIMED_ABOVE("uncleCheck", 500)
547  for (auto const& i: rlp[2])
548  {
549  try
550  {
551  auto h = sha3(i.data());
552  if (excluded.count(h))
553  {
554  UncleInChain ex;
555  ex << errinfo_comment("Uncle in block already mentioned");
556  ex << errinfo_unclesExcluded(excluded);
557  ex << errinfo_hash256(sha3(i.data()));
558  BOOST_THROW_EXCEPTION(ex);
559  }
560  excluded.insert(h);
561 
562  // CheckNothing since it's a VerifiedBlock.
563  BlockHeader uncle(i.data(), HeaderData, h);
564 
565  BlockHeader uncleParent;
566  if (!_bc.isKnown(uncle.parentHash()))
567  BOOST_THROW_EXCEPTION(UnknownParent() << errinfo_hash256(uncle.parentHash()));
568  uncleParent = BlockHeader(_bc.block(uncle.parentHash()));
569 
570  // m_currentBlock.number() - uncle.number() m_cB.n - uP.n()
571  // 1 2
572  // 2
573  // 3
574  // 4
575  // 5
576  // 6 7
577  // (8 Invalid)
578  bigint depth = (bigint)m_currentBlock.number() - (bigint)uncle.number();
579  if (depth > 6)
580  {
581  UncleTooOld ex;
582  ex << errinfo_uncleNumber(uncle.number());
584  BOOST_THROW_EXCEPTION(ex);
585  }
586  else if (depth < 1)
587  {
588  UncleIsBrother ex;
589  ex << errinfo_uncleNumber(uncle.number());
591  BOOST_THROW_EXCEPTION(ex);
592  }
593  // cB
594  // cB.p^1 1 depth, valid uncle
595  // cB.p^2 ---/ 2
596  // cB.p^3 -----/ 3
597  // cB.p^4 -------/ 4
598  // cB.p^5 ---------/ 5
599  // cB.p^6 -----------/ 6
600  // cB.p^7 -------------/
601  // cB.p^8
602  auto expectedUncleParent = _bc.details(m_currentBlock.parentHash()).parent;
603  for (unsigned i = 1; i < depth; expectedUncleParent = _bc.details(expectedUncleParent).parent, ++i) {}
604  if (expectedUncleParent != uncleParent.hash())
605  {
606  UncleParentNotInChain ex;
607  ex << errinfo_uncleNumber(uncle.number());
609  BOOST_THROW_EXCEPTION(ex);
610  }
611  uncle.verify(CheckNothingNew/*CheckParent*/, uncleParent);
612 
613  rewarded.push_back(uncle);
614  ++ii;
615  }
616  catch (Exception& ex)
617  {
618  ex << errinfo_uncleIndex(ii);
619  throw;
620  }
621  }
622 
623  DEV_TIMED_ABOVE("applyRewards", 500)
624  applyRewards(rewarded, _bc.chainParams().blockReward);
625 
626  // Commit all cached state changes to the state trie.
627  bool removeEmptyAccounts = m_currentBlock.number() >= _bc.chainParams().u256Param("EIP158ForkBlock");
628  DEV_TIMED_ABOVE("commit", 500)
630 
631  // Hash the state trie and check against the state_root hash in m_currentBlock.
633  {
634  auto r = rootHash();
635  m_state.db().rollback(); // TODO: API in State for this?
636  BOOST_THROW_EXCEPTION(InvalidStateRoot() << Hash256RequirementError(r, m_currentBlock.stateRoot()));
637  }
638 
639  if (m_currentBlock.gasUsed() != gasUsed())
640  {
641  // Rollback the trie.
642  m_state.db().rollback(); // TODO: API in State for this?
643  BOOST_THROW_EXCEPTION(InvalidGasUsed() << RequirementError(bigint(gasUsed()), bigint(m_currentBlock.gasUsed())));
644  }
645 
646  return tdIncrease;
647 }
648 
649 ExecutionResult Block::execute(LastHashes const& _lh, Transaction const& _t, Permanence _p, OnOpFunc const& _onOp)
650 {
651  if (isSealed())
652  BOOST_THROW_EXCEPTION(InvalidOperationOnSealedBlock());
653 
654  // Uncommitting is a non-trivial operation - only do it once we've verified as much of the
655  // transaction as possible.
656  uncommitToSeal();
657 
658  std::pair<ExecutionResult, TransactionReceipt> resultReceipt = m_state.execute(EnvInfo(info(), _lh, gasUsed()), *m_sealEngine, _t, _p, _onOp);
659 
660  if (_p == Permanence::Committed)
661  {
662  // Add to the user-originated transactions that we've executed.
663  m_transactions.push_back(_t);
664  m_receipts.push_back(resultReceipt.second);
665  m_transactionSet.insert(_t.sha3());
666  }
667 
668  return resultReceipt.first;
669 }
670 
671 void Block::applyRewards(vector<BlockHeader> const& _uncleBlockHeaders, u256 const& _blockReward)
672 {
673  u256 r = _blockReward;
674  for (auto const& i: _uncleBlockHeaders)
675  {
676  m_state.addBalance(i.author(), _blockReward * (8 + i.number() - m_currentBlock.number()) / 8);
677  r += _blockReward / 32;
678  }
680 }
681 
683 {
684  u256 daoHardfork = m_sealEngine->chainParams().u256Param("daoHardforkBlock");
685  if (daoHardfork != 0 && info().number() == daoHardfork)
686  {
687  Address recipient("0xbf4ed7b27f1d666546e30d74d50d173d20bca754");
688  Addresses allDAOs = childDaos();
689  for (Address const& dao: allDAOs)
690  m_state.transferBalance(dao, recipient, m_state.balance(dao));
692  }
693 }
694 
695 void Block::commitToSeal(BlockChain const& _bc, bytes const& _extraData)
696 {
697  if (isSealed())
698  BOOST_THROW_EXCEPTION(InvalidOperationOnSealedBlock());
699 
700  noteChain(_bc);
701 
702  if (m_committedToSeal)
703  uncommitToSeal();
704  else
706 
707  vector<BlockHeader> uncleBlockHeaders;
708 
709  RLPStream unclesData;
710  unsigned unclesCount = 0;
711  if (m_previousBlock.number() != 0)
712  {
713  // Find great-uncles (or second-cousins or whatever they are) - children of great-grandparents, great-great-grandparents... that were not already uncles in previous generations.
714  clog(StateDetail) << "Checking " << m_previousBlock.hash() << ", parent=" << m_previousBlock.parentHash();
715  h256Hash excluded = _bc.allKinFrom(m_currentBlock.parentHash(), 6);
716  auto p = m_previousBlock.parentHash();
717  for (unsigned gen = 0; gen < 6 && p != _bc.genesisHash() && unclesCount < 2; ++gen, p = _bc.details(p).parent)
718  {
719  auto us = _bc.details(p).children;
720  assert(us.size() >= 1); // must be at least 1 child of our grandparent - it's our own parent!
721  for (auto const& u: us)
722  if (!excluded.count(u)) // ignore any uncles/mainline blocks that we know about.
723  {
724  uncleBlockHeaders.push_back(_bc.info(u));
725  unclesData.appendRaw(_bc.headerData(u));
726  ++unclesCount;
727  if (unclesCount == 2)
728  break;
729  excluded.insert(u);
730  }
731  }
732  }
733 
734  BytesMap transactionsMap;
735  BytesMap receiptsMap;
736 
737  RLPStream txs;
738  txs.appendList(m_transactions.size());
739 
740  for (unsigned i = 0; i < m_transactions.size(); ++i)
741  {
742  RLPStream k;
743  k << i;
744 
745  RLPStream receiptrlp;
746  m_receipts[i].streamRLP(receiptrlp);
747  receiptsMap.insert(std::make_pair(k.out(), receiptrlp.out()));
748 
749  RLPStream txrlp;
750  m_transactions[i].streamRLP(txrlp);
751  transactionsMap.insert(std::make_pair(k.out(), txrlp.out()));
752 
753  txs.appendRaw(txrlp.out());
754 
755 //#if ETH_PARANOIA
756 /* if (fromPending(i).transactionsFrom(m_transactions[i].from()) != m_transactions[i].nonce())
757  {
758  cwarn << "GAAA Something went wrong! " << fromPending(i).transactionsFrom(m_transactions[i].from()) << "!=" << m_transactions[i].nonce();
759  }*/
760 //#endif
761  }
762 
763  txs.swapOut(m_currentTxs);
764 
765  RLPStream(unclesCount).appendRaw(unclesData.out(), unclesCount).swapOut(m_currentUncles);
766 
767  // Apply rewards last of all.
768  applyRewards(uncleBlockHeaders, _bc.chainParams().blockReward);
769 
770  // Commit any and all changes to the trie that are in the cache, then update the state root accordingly.
771  bool removeEmptyAccounts = m_currentBlock.number() >= _bc.chainParams().u256Param("EIP158ForkBlock");
772  DEV_TIMED_ABOVE("commit", 500)
774 
775  clog(StateDetail) << "Post-reward stateRoot:" << m_state.rootHash();
777  clog(StateDetail) << *this;
778 
781  m_currentBlock.setRoots(hash256(transactionsMap), hash256(receiptsMap), sha3(m_currentUncles), m_state.rootHash());
782 
784  m_currentBlock.setExtraData(_extraData);
785  if (m_currentBlock.extraData().size() > 32)
786  {
787  auto ed = m_currentBlock.extraData();
788  ed.resize(32);
790  }
791 
792  m_committedToSeal = true;
793 }
794 
796 {
797  if (m_committedToSeal)
798  {
800  m_committedToSeal = false;
801  }
802 }
803 
805 {
806  if (!m_committedToSeal)
807  return false;
808 
810  return false;
811 
812  clog(StateDetail) << "Sealing block!";
813 
814  // Compile block:
815  RLPStream ret;
816  ret.appendList(3);
817  ret.appendRaw(_header);
818  ret.appendRaw(m_currentTxs);
820  ret.swapOut(m_currentBytes);
822 // cnote << "Mined " << m_currentBlock.hash() << "(parent: " << m_currentBlock.parentHash() << ")";
823  // TODO: move into SealEngine
824 
826 
827  // m_currentBytes is now non-empty; we're in a sealed state so no more transactions can be added.
828 
829  return true;
830 }
831 
832 State Block::fromPending(unsigned _i) const
833 {
834  State ret = m_state;
835  _i = min<unsigned>(_i, m_transactions.size());
836  if (!_i)
838  else
839  ret.setRoot(m_receipts[_i - 1].stateRoot());
840  return ret;
841 }
842 
844 {
845  LogBloom ret;
846  for (TransactionReceipt const& i: m_receipts)
847  ret |= i.bloom();
848  return ret;
849 }
850 
851 void Block::cleanup(bool _fullCommit)
852 {
853  if (_fullCommit)
854  {
855  // Commit the new trie to disk.
856  if (isChannelVisible<StateTrace>()) // Avoid calling toHex if not needed
857  clog(StateTrace) << "Committing to disk: stateRoot" << m_currentBlock.stateRoot() << "=" << rootHash() << "=" << toHex(asBytes(db().lookup(rootHash())));
858 
859  try
860  {
861  EnforceRefs er(db(), true);
862  rootHash();
863  }
864  catch (BadRoot const&)
865  {
866  clog(StateChat) << "Trie corrupt! :-(";
867  throw;
868  }
869 
870  m_state.db().commit(); // TODO: State API for this?
871 
872  if (isChannelVisible<StateTrace>()) // Avoid calling toHex if not needed
873  clog(StateTrace) << "Committed: stateRoot" << m_currentBlock.stateRoot() << "=" << rootHash() << "=" << toHex(asBytes(db().lookup(rootHash())));
874 
877 
878  clog(StateTrace) << "finalising enactment. current -> previous, hash is" << m_previousBlock.hash();
879  }
880  else
881  m_state.db().rollback(); // TODO: State API for this?
882 
883  resetCurrent();
884 }
885 
887 {
888  noteChain(_bc);
889 
890  RLP rlp(_block);
891 
892  cleanup(false);
893  BlockHeader bi(_block);
894  m_currentBlock = bi;
897 
899 
900  string ret;
901  unsigned i = 0;
902  for (auto const& tr: rlp[1])
903  {
904  StandardTrace st;
905  st.setShowMnemonics();
907  ret += (ret.empty() ? "[" : ",") + st.json();
908  ++i;
909  }
910  return ret.empty() ? "[]" : (ret + "]");
911 }
912 
913 std::ostream& dev::eth::operator<<(std::ostream& _out, Block const& _s)
914 {
915  (void)_s;
916  return _out;
917 }
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&#39;s balance.
Definition: State.cpp:266
Adapted from code found on http://stackoverflow.com/questions/180947/base64-decode-snippet-in-c Origi...
Definition: Arith256.cpp:15
boost::error_info< struct tag_unclesExcluded, h256Hash > errinfo_unclesExcluded
Definition: State.h:52
std::string toHex(T const &_data, int _w=2, HexPrefix _prefix=HexPrefix::DontAdd)
Definition: CommonData.h:54
boost::tuple< errinfo_required_h256, errinfo_got_h256 > Hash256RequirementError
Definition: Exceptions.h:84
LogBloom const & logBloom() const
Definition: BlockHeader.h:165
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&#39;t...
Definition: Block.cpp:301
u256 const & number() const
Definition: BlockHeader.h:162
std::map< bytes, bytes > BytesMap
Definition: Common.h:138
ChainParams const & chainParams() const
Definition: BlockChain.h:307
BlockDetails details(h256 const &_hash) const
Get the familial details concerning a block (or the most recent mined if none given). Thread-safe.
Definition: BlockChain.h:156
bool isSealed() const
Definition: Block.h:272
void commit(CommitBehaviour _commitBehaviour)
Commit all changes waiting in the address cache to the DB.
Definition: State.cpp:210
A queue of Transactions, each stored as RLP.
boost::error_info< struct tag_receipts, std::vector< bytes >> errinfo_receipts
Definition: State.h:59
bool m_committedToSeal
Have we committed to mine on the present m_currentBlock?
Definition: Block.h:321
Transactions m_transactions
The current list of transactions that we&#39;ve included in the state.
Definition: Block.h:313
ChainOperationParams const & chainParams() const
Definition: SealEngine.h:75
BlockHeader info(h256 const &_hash) const
Get the partial-header of a block (or the most recent mined if none given). Thread-safe.
Definition: BlockChain.h:144
State fromPending(unsigned _i) const
Get the State immediately after the given number of pending transactions have been applied...
Definition: Block.cpp:832
boost::error_info< struct tag_uncleIndex, unsigned > errinfo_uncleIndex
Definition: State.h:49
Implements the blockchain database.
Definition: BlockChain.h:105
SealEngineFace * sealEngine() const
Definition: Block.cpp:133
bytes rlp(_T _t)
Export a single item in RLP format, returning a byte array.
Definition: RLP.h:467
h256 const & stateRoot() const
Definition: BlockHeader.h:158
h256 hash(IncludeSeal _i=WithSeal) const
Definition: BlockHeader.cpp:64
Encapsulation of a block header.
Definition: BlockHeader.h:95
boost::multiprecision::number< boost::multiprecision::cpp_int_backend<>> bigint
Definition: Common.h:121
void noteAccountStartNonce(u256 const &_actual)
Definition: State.cpp:128
std::ostream & operator<<(std::ostream &_out, BlockHeader const &_bi)
Definition: BlockHeader.h:194
#define h(i)
Definition: sha.cpp:736
bytes const & out() const
Read the byte stream.
Definition: RLP.h:433
void noteChain(BlockChain const &_bc)
Note the fact that this block is being used with a particular chain.
Definition: Block.cpp:140
void setGasUsed(u256 const &_v)
Definition: BlockHeader.h:145
boost::error_info< struct tag_currentNumber, u256 > errinfo_currentNumber
Definition: State.h:50
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.) ...
Definition: BlockChain.h:186
u256 const & accountStartNonce() const
Get the account start nonce. May be required.
Definition: State.h:298
bytes m_currentBytes
The current block&#39;s bytes.
Definition: Block.h:320
void commitToSeal(BlockChain const &_bc, bytes const &_extraData={})
Prepares the current state for mining.
Definition: Block.cpp:695
std::hash for asio::adress
Definition: Common.h:323
assert(len-trim+(2 *lenIndices)<=WIDTH)
boost::error_info< struct tag_max, bigint > errinfo_max
Definition: Exceptions.h:79
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.
Definition: Block.cpp:795
Block(u256 const &_accountStartNonce)
Default constructor; creates with a blank database prepopulated with the genesis block.
Definition: Block.h:85
#define DEV_TIMED_ABOVE(S, MS)
Definition: Common.h:295
TransactionReceipts m_receipts
The corresponding list of transaction receipts.
Definition: Block.h:314
Description of the result of executing a transaction.
Definition: Transaction.h:69
u256 gasUsed() const
Definition: Block.h:304
Model of an Ethereum state, essentially a facade for the trie.
Definition: State.h:161
OverlayDB const & db() const
Definition: State.h:195
void noteDirty() const
Definition: BlockHeader.h:130
void setParentHash(h256 const &_v)
Definition: BlockHeader.h:140
bytesConstRef block
Block data reference.
Definition: VerifiedBlock.h:38
u256 enactOn(VerifiedBlockRef const &_block, BlockChain const &_bc)
Execute all transactions within a given block.
Definition: Block.cpp:401
std::string lookup(h256 const &_h) const
Definition: OverlayDB.cpp:120
void applyRewards(std::vector< BlockHeader > const &_uncleBlockHeaders, u256 const &_blockReward)
Finalise the block, applying the earned rewards.
Definition: Block.cpp:671
h256 const & parentHash() const
Definition: BlockHeader.h:154
Transactions topTransactions(unsigned _limit, h256Hash const &_avoid=h256Hash()) const
Get top transactions from the queue.
h256 hash256(BytesMap const &_s)
Definition: TrieHash.cpp:174
void setTimestamp(u256 const &_v)
Definition: BlockHeader.h:142
Active model of a block within the block chain.
Definition: Block.h:73
boost::error_info< struct tag_hash, h256 > errinfo_hash256
Definition: Exceptions.h:81
std::vector< h256 > LastHashes
Definition: ExtVMFace.h:191
double elapsed() const
Definition: Common.h:280
Check the basic structure of the transactions.
Definition: Common.h:117
std::string json(bool _styled=false) const
Definition: Executive.cpp:150
Base class for all exceptions.
Definition: Exceptions.h:39
std::string vmTrace(bytesConstRef _block, BlockChain const &_bc, ImportRequirements::value _ir)
Provide a standard VM trace for debugging purposes.
Definition: Block.cpp:886
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.
Definition: State.cpp:515
void cleanup(bool _fullCommit)
Returns back to a pristine state after having done a playback.
Definition: Block.cpp:851
PopulationStatistics populateFromChain(BlockChain const &_bc, h256 const &_hash, ImportRequirements::value _ir=ImportRequirements::None)
Construct state object from arbitrary point in blockchain.
Definition: Block.cpp:150
LogBloom logBloom() const
Get the bloom filter of all logs that happened in the block.
Definition: Block.cpp:843
Address m_author
Our address (i.e. the address to which fees go).
Definition: Block.h:326
BlockHeader m_currentBlock
The current block&#39;s information.
Definition: Block.h:319
BaseState
Definition: State.h:76
const char * name
Definition: rest.cpp:36
ExecStats::duration max
Definition: ExecStats.cpp:36
#define EthWhite
Definition: Terminal.h:119
BlockGetAndPut< word32, BigEndian > Block
Definition: cast.cpp:34
bytes const & extraData() const
Definition: BlockHeader.h:164
boost::error_info< struct tag_got, bigint > errinfo_got
Definition: Exceptions.h:77
h256 currentHash() const
Get a given block (RLP format). Thread-safe.
Definition: BlockChain.h:229
SealEngineFace * m_sealEngine
The chain&#39;s seal engine.
Definition: Block.h:328
std::vector< byte > bytes
Definition: Common.h:75
const u256 Invalid256
Definition: Common.cpp:38
Fixed-size raw-byte array container type, with an API optimised for storing hashes.
Definition: FixedHash.h:47
BlockHeader m_previousBlock
The previous block&#39;s information.
Definition: Block.h:318
std::function< void(uint64_t, uint64_t, Instruction, bigint, bigint, bigint, VM *, ExtVMFace const *)> OnOpFunc
Definition: ExtVMFace.h:193
RLPStream & appendList(size_t _items)
Appends a list.
Definition: RLP.cpp:276
void setLogBloom(LogBloom const &_v)
Definition: BlockHeader.h:149
void restart()
Definition: Common.h:281
#define EthGray
Definition: Terminal.h:118
boost::error_info< struct tag_target, h256 > errinfo_target
Definition: Exceptions.h:38
void verify(Strictness _s=CheckEverything, BlockHeader const &_parent=BlockHeader(), bytesConstRef _block=bytesConstRef()) const
bytes asBytes(std::string const &_b)
Converts a string to a byte array containing the string&#39;s (byte) data.
Definition: CommonData.h:92
h256 sha3(IncludeSignature _sig=WithSignature) const
#define cwarn
Definition: Log.h:304
bool sealBlock(bytes const &_header)
Pass in a properly sealed header matching this block.
Definition: Block.h:268
boost::multiprecision::number< boost::multiprecision::cpp_int_backend< 256, 256, boost::multiprecision::unsigned_magnitude, boost::multiprecision::unchecked, void >> u256
Definition: Common.h:125
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.
Definition: Common.h:68
void resetCurrent(u256 const &_timestamp=u256(utcTime()))
Sets m_currentBlock to a clean state, (i.e.
Definition: Block.cpp:113
Encodes a transaction, ready to be exported to or freshly imported from RLP.
Definition: Transaction.h:84
#define b(i, j)
OverlayDB const & db() const
Open a DB - useful for passing into the constructor & keeping for other states that are necessary...
Definition: Block.h:166
u256 const & timestamp() const
Definition: BlockHeader.h:156
void setRoot(h256 const &_root)
Resets any uncommitted changes to the cache.
Definition: State.cpp:236
h256 rootHash() const
The hash of the root of our state tree.
Definition: State.h:288
dev::Addresses childDaos()
u256 enact(VerifiedBlockRef const &_block, BlockChain const &_bc)
Execute the given block, assuming it corresponds to m_currentBlock.
Definition: Block.cpp:450
State m_precommit
State at the point immediately prior to rewards.
Definition: Block.h:316
#define EthViolet
Definition: Terminal.h:128
h256 const & receiptsRoot() const
Definition: BlockHeader.h:160
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.
Address const & author() const
Definition: BlockHeader.h:157
void setExtraData(bytes const &_v)
Definition: BlockHeader.h:148
Verified block info, does not hold block data, but a reference instead.
Definition: VerifiedBlock.h:36
virtual void transferBalance(Address const &_from, Address const &_to, u256 const &_value)
Transfers "the balance _value between two accounts.
Definition: State.h:240
h256Hash m_transactionSet
The set of transaction hashes that we&#39;ve included in the state.
Definition: Block.h:315
boost::error_info< struct tag_comment, std::string > errinfo_comment
Definition: Assertions.h:78
bytes m_currentUncles
The RLP-encoded block of uncles.
Definition: Block.h:324
u256 const & gasLimit() const
Definition: BlockHeader.h:163
bool sha3(bytesConstRef _input, bytesRef o_output)
Calculate SHA3-256 hash of the given input and load it into the given output.
Definition: SHA3.cpp:214
virtual void addBalance(Address const &_id, u256 const &_amount)
Add some amount to balance.
Definition: State.cpp:286
h256 rootHash() const
The hash of the root of our state tree.
Definition: Block.h:169
virtual void populateFromParent(BlockHeader &_bi, BlockHeader const &_parent) const
Don&#39;t forget to call Super::populateFromParent when subclassing & overriding.
Definition: SealEngine.cpp:41
#define clog(X)
Definition: Log.h:295
#define e(i)
Definition: sha.cpp:733
h256 genesisHash() const
Get the hash of the genesis block. Thread-safe.
Definition: BlockChain.h:232
ExecutionResult execute(LastHashes const &_lh, Transaction const &_t, Permanence _p=Permanence::Committed, OnOpFunc const &_onOp=OnOpFunc())
Execute a given transaction.
Definition: Block.cpp:649
std::vector< Transaction > transactions
Verified list of block transactions.
Definition: VerifiedBlock.h:40
std::unordered_set< h256 > h256Hash
Definition: FixedHash.h:349
void performIrregularModifications()
Performs irregular modifications right after initialization, e.g. to implement a hard fork...
Definition: Block.cpp:682
void swapOut(bytes &_dest)
Swap the contents of the output stream out for some other byte array.
Definition: RLP.h:439
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)
Definition: TrieHash.cpp:179
Permanence
Definition: State.h:82
bytes m_currentTxs
The RLP-encoded block of transactions.
Definition: Block.h:323
boost::error_info< struct tag_transactionIndex, unsigned > errinfo_transactionIndex
Definition: State.h:56
void setRoots(h256 const &_t, h256 const &_r, h256 const &_u, h256 const &_s)
Definition: BlockHeader.h:144
#define EthBlue
Definition: Terminal.h:127
u256 blockReward
General chain params.
virtual u256 ask(Block const &) const =0
boost::error_info< struct tag_uncleNumber, u256 > errinfo_uncleNumber
Definition: State.h:51
boost::tuple< errinfo_required, errinfo_got > RequirementError
Definition: Exceptions.h:80
u256 const & gasUsed() const
Definition: BlockHeader.h:161
Class for writing to an RLP bytestream.
Definition: RLP.h:383
BlockHeader info
Prepopulated block info.
Definition: VerifiedBlock.h:39
Block & operator=(Block const &_s)
Copy state object.
Definition: Block.cpp:93
RLPStream & appendRaw(bytesConstRef _rlp, size_t _itemCount=1)
Appends raw (pre-serialised) RLP data. Use with caution.
Definition: RLP.cpp:230
unsigned waiting(Address const &_a) const
Get number of pending transactions for account.
u256 const & difficulty() const
Definition: BlockHeader.h:166
#define DEV_TIMED_FUNCTION_ABOVE(MS)
Definition: Common.h:300
Class for interpreting Recursive Linear-Prefix Data.
Definition: RLP.h:64
void populate(RLP const &_header)
State m_state
Our state tree, as an OverlayDB DB.
Definition: Block.h:312
SealEngineFace * sealEngine() const
Definition: BlockChain.h:309
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.
Definition: Block.h:279
void setAuthor(Address const &_v)
Definition: BlockHeader.h:143
boost::tuple< errinfo_required_LogBloom, errinfo_got_LogBloom > LogBloomRequirementError
Definition: State.h:64