Block.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918
  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.cpp
  15. * @author Gav Wood <i@gavwood.com>
  16. * @date 2014
  17. */
  18. #include "Block.h"
  19. #include <ctime>
  20. #include <boost/filesystem.hpp>
  21. #include <boost/timer.hpp>
  22. #include <libdevcore/CommonIO.h>
  23. #include <libdevcore/Assertions.h>
  24. #include <libdevcore/TrieHash.h>
  25. #include <libevmcore/Instruction.h>
  26. #include <libethcore/Exceptions.h>
  27. #include <libethcore/SealEngine.h>
  28. #include <libevm/VMFactory.h>
  29. #include "BlockChain.h"
  30. #include "Defaults.h"
  31. #include "ExtVM.h"
  32. #include "Executive.h"
  33. #include "BlockChain.h"
  34. #include "TransactionQueue.h"
  35. #include "GenesisInfo.h"
  36. using namespace std;
  37. using namespace dev;
  38. using namespace dev::eth;
  39. namespace fs = boost::filesystem;
  40. #define ETH_TIMED_ENACTMENTS 0
  41. static const unsigned c_maxSyncTransactions = 1024;
  42. const char* BlockSafeExceptions::name() { return EthViolet "⚙" EthBlue " ℹ"; }
  43. const char* BlockDetail::name() { return EthViolet "⚙" EthWhite " ◌"; }
  44. const char* BlockTrace::name() { return EthViolet "⚙" EthGray " ◎"; }
  45. const char* BlockChat::name() { return EthViolet "⚙" EthWhite " ◌"; }
  46. Block::Block(BlockChain const& _bc, OverlayDB const& _db, BaseState _bs, Address const& _author):
  47. m_state(Invalid256, _db, _bs),
  48. m_precommit(Invalid256),
  49. m_author(_author)
  50. {
  51. noteChain(_bc);
  52. m_previousBlock.clear();
  53. m_currentBlock.clear();
  54. // assert(m_state.root() == m_previousBlock.stateRoot());
  55. }
  56. Block::Block(BlockChain const& _bc, OverlayDB const& _db, h256 const& _root, Address const& _author):
  57. m_state(Invalid256, _db, BaseState::PreExisting),
  58. m_precommit(Invalid256),
  59. m_author(_author)
  60. {
  61. noteChain(_bc);
  62. m_state.setRoot(_root);
  63. m_previousBlock.clear();
  64. m_currentBlock.clear();
  65. // assert(m_state.root() == m_previousBlock.stateRoot());
  66. }
  67. Block::Block(Block const& _s):
  68. m_state(_s.m_state),
  69. m_transactions(_s.m_transactions),
  70. m_receipts(_s.m_receipts),
  71. m_transactionSet(_s.m_transactionSet),
  72. m_precommit(_s.m_state),
  73. m_previousBlock(_s.m_previousBlock),
  74. m_currentBlock(_s.m_currentBlock),
  75. m_currentBytes(_s.m_currentBytes),
  76. m_author(_s.m_author),
  77. m_sealEngine(_s.m_sealEngine)
  78. {
  79. m_committedToSeal = false;
  80. }
  81. Block& Block::operator=(Block const& _s)
  82. {
  83. if (&_s == this)
  84. return *this;
  85. m_state = _s.m_state;
  86. m_transactions = _s.m_transactions;
  87. m_receipts = _s.m_receipts;
  88. m_transactionSet = _s.m_transactionSet;
  89. m_previousBlock = _s.m_previousBlock;
  90. m_currentBlock = _s.m_currentBlock;
  91. m_currentBytes = _s.m_currentBytes;
  92. m_author = _s.m_author;
  93. m_sealEngine = _s.m_sealEngine;
  94. m_precommit = m_state;
  95. m_committedToSeal = false;
  96. return *this;
  97. }
  98. void Block::resetCurrent(u256 const& _timestamp)
  99. {
  100. m_transactions.clear();
  101. m_receipts.clear();
  102. m_transactionSet.clear();
  103. m_currentBlock = BlockHeader();
  104. m_currentBlock.setAuthor(m_author);
  105. m_currentBlock.setTimestamp(max(m_previousBlock.timestamp() + 1, _timestamp));
  106. m_currentBytes.clear();
  107. sealEngine()->populateFromParent(m_currentBlock, m_previousBlock);
  108. // TODO: check.
  109. m_state.setRoot(m_previousBlock.stateRoot());
  110. m_precommit = m_state;
  111. m_committedToSeal = false;
  112. performIrregularModifications();
  113. }
  114. SealEngineFace* Block::sealEngine() const
  115. {
  116. if (!m_sealEngine)
  117. BOOST_THROW_EXCEPTION(ChainOperationWithUnknownBlockChain());
  118. return m_sealEngine;
  119. }
  120. void Block::noteChain(BlockChain const& _bc)
  121. {
  122. if (!m_sealEngine)
  123. {
  124. m_state.noteAccountStartNonce(_bc.chainParams().accountStartNonce);
  125. m_precommit.noteAccountStartNonce(_bc.chainParams().accountStartNonce);
  126. m_sealEngine = _bc.sealEngine();
  127. }
  128. }
  129. PopulationStatistics Block::populateFromChain(BlockChain const& _bc, h256 const& _h, ImportRequirements::value _ir)
  130. {
  131. noteChain(_bc);
  132. PopulationStatistics ret { 0.0, 0.0 };
  133. if (!_bc.isKnown(_h))
  134. {
  135. // Might be worth throwing here.
  136. cwarn << "Invalid block given for state population: " << _h;
  137. BOOST_THROW_EXCEPTION(BlockNotFound() << errinfo_target(_h));
  138. }
  139. auto b = _bc.block(_h);
  140. BlockHeader bi(b); // No need to check - it's already in the DB.
  141. if (bi.number())
  142. {
  143. // Non-genesis:
  144. // 1. Start at parent's end state (state root).
  145. BlockHeader bip(_bc.block(bi.parentHash()));
  146. sync(_bc, bi.parentHash(), bip);
  147. // 2. Enact the block's transactions onto this state.
  148. m_author = bi.author();
  149. Timer t;
  150. auto vb = _bc.verifyBlock(&b, function<void(Exception&)>(), _ir | ImportRequirements::TransactionBasic);
  151. ret.verify = t.elapsed();
  152. t.restart();
  153. enact(vb, _bc);
  154. ret.enact = t.elapsed();
  155. }
  156. else
  157. {
  158. // Genesis required:
  159. // We know there are no transactions, so just populate directly.
  160. m_state = State(m_state.accountStartNonce(), m_state.db(), BaseState::Empty); // TODO: try with PreExisting.
  161. sync(_bc, _h, bi);
  162. }
  163. return ret;
  164. }
  165. bool Block::sync(BlockChain const& _bc)
  166. {
  167. return sync(_bc, _bc.currentHash());
  168. }
  169. bool Block::sync(BlockChain const& _bc, h256 const& _block, BlockHeader const& _bi)
  170. {
  171. noteChain(_bc);
  172. bool ret = false;
  173. // BLOCK
  174. BlockHeader bi = _bi ? _bi : _bc.info(_block);
  175. #if ETH_PARANOIA
  176. if (!bi)
  177. while (1)
  178. {
  179. try
  180. {
  181. auto b = _bc.block(_block);
  182. bi.populate(b);
  183. break;
  184. }
  185. catch (Exception const& _e)
  186. {
  187. // TODO: Slightly nicer handling? :-)
  188. cerr << "ERROR: Corrupt block-chain! Delete your block-chain DB and restart." << endl;
  189. cerr << diagnostic_information(_e) << endl;
  190. }
  191. catch (std::exception const& _e)
  192. {
  193. // TODO: Slightly nicer handling? :-)
  194. cerr << "ERROR: Corrupt block-chain! Delete your block-chain DB and restart." << endl;
  195. cerr << _e.what() << endl;
  196. }
  197. }
  198. #endif
  199. if (bi == m_currentBlock)
  200. {
  201. // We mined the last block.
  202. // Our state is good - we just need to move on to next.
  203. m_previousBlock = m_currentBlock;
  204. resetCurrent();
  205. ret = true;
  206. }
  207. else if (bi == m_previousBlock)
  208. {
  209. // No change since last sync.
  210. // Carry on as we were.
  211. }
  212. else
  213. {
  214. // New blocks available, or we've switched to a different branch. All change.
  215. // Find most recent state dump and replay what's left.
  216. // (Most recent state dump might end up being genesis.)
  217. if (m_state.db().lookup(bi.stateRoot()).empty()) // TODO: API in State for this?
  218. {
  219. cwarn << "Unable to sync to" << bi.hash() << "; state root" << bi.stateRoot() << "not found in database.";
  220. cwarn << "Database corrupt: contains block without stateRoot:" << bi;
  221. cwarn << "Try rescuing the database by running: eth --rescue";
  222. BOOST_THROW_EXCEPTION(InvalidStateRoot() << errinfo_target(bi.stateRoot()));
  223. }
  224. m_previousBlock = bi;
  225. resetCurrent();
  226. ret = true;
  227. }
  228. #if ALLOW_REBUILD
  229. else
  230. {
  231. // New blocks available, or we've switched to a different branch. All change.
  232. // Find most recent state dump and replay what's left.
  233. // (Most recent state dump might end up being genesis.)
  234. std::vector<h256> chain;
  235. while (bi.number() != 0 && m_db.lookup(bi.stateRoot()).empty()) // while we don't have the state root of the latest block...
  236. {
  237. chain.push_back(bi.hash()); // push back for later replay.
  238. bi.populate(_bc.block(bi.parentHash())); // move to parent.
  239. }
  240. m_previousBlock = bi;
  241. resetCurrent();
  242. // Iterate through in reverse, playing back each of the blocks.
  243. try
  244. {
  245. for (auto it = chain.rbegin(); it != chain.rend(); ++it)
  246. {
  247. auto b = _bc.block(*it);
  248. enact(&b, _bc, _ir);
  249. cleanup(true);
  250. }
  251. }
  252. catch (...)
  253. {
  254. // TODO: Slightly nicer handling? :-)
  255. cerr << "ERROR: Corrupt block-chain! Delete your block-chain DB and restart." << endl;
  256. cerr << boost::current_exception_diagnostic_information() << endl;
  257. exit(1);
  258. }
  259. resetCurrent();
  260. ret = true;
  261. }
  262. #endif
  263. return ret;
  264. }
  265. pair<TransactionReceipts, bool> Block::sync(BlockChain const& _bc, TransactionQueue& _tq, GasPricer const& _gp, unsigned msTimeout)
  266. {
  267. if (isSealed())
  268. BOOST_THROW_EXCEPTION(InvalidOperationOnSealedBlock());
  269. noteChain(_bc);
  270. // TRANSACTIONS
  271. pair<TransactionReceipts, bool> ret;
  272. auto ts = _tq.topTransactions(c_maxSyncTransactions, m_transactionSet);
  273. ret.second = (ts.size() == c_maxSyncTransactions); // say there's more to the caller if we hit the limit
  274. LastHashes lh;
  275. auto deadline = chrono::steady_clock::now() + chrono::milliseconds(msTimeout);
  276. for (int goodTxs = max(0, (int)ts.size() - 1); goodTxs < (int)ts.size(); )
  277. {
  278. goodTxs = 0;
  279. for (auto const& t: ts)
  280. if (!m_transactionSet.count(t.sha3()))
  281. {
  282. try
  283. {
  284. if (t.gasPrice() >= _gp.ask(*this))
  285. {
  286. // Timer t;
  287. if (lh.empty())
  288. lh = _bc.lastHashes();
  289. execute(lh, t);
  290. ret.first.push_back(m_receipts.back());
  291. ++goodTxs;
  292. // cnote << "TX took:" << t.elapsed() * 1000;
  293. }
  294. else if (t.gasPrice() < _gp.ask(*this) * 9 / 10)
  295. {
  296. clog(StateTrace) << t.sha3() << "Dropping El Cheapo transaction (<90% of ask price)";
  297. _tq.drop(t.sha3());
  298. }
  299. }
  300. catch (InvalidNonce const& in)
  301. {
  302. bigint const& req = *boost::get_error_info<errinfo_required>(in);
  303. bigint const& got = *boost::get_error_info<errinfo_got>(in);
  304. if (req > got)
  305. {
  306. // too old
  307. clog(StateTrace) << t.sha3() << "Dropping old transaction (nonce too low)";
  308. _tq.drop(t.sha3());
  309. }
  310. else if (got > req + _tq.waiting(t.sender()))
  311. {
  312. // too new
  313. clog(StateTrace) << t.sha3() << "Dropping new transaction (too many nonces ahead)";
  314. _tq.drop(t.sha3());
  315. }
  316. else
  317. _tq.setFuture(t.sha3());
  318. }
  319. catch (BlockGasLimitReached const& e)
  320. {
  321. bigint const& got = *boost::get_error_info<errinfo_got>(e);
  322. if (got > m_currentBlock.gasLimit())
  323. {
  324. clog(StateTrace) << t.sha3() << "Dropping over-gassy transaction (gas > block's gas limit)";
  325. _tq.drop(t.sha3());
  326. }
  327. else
  328. {
  329. clog(StateTrace) << t.sha3() << "Temporarily no gas left in current block (txs gas > block's gas limit)";
  330. //_tq.drop(t.sha3());
  331. // Temporarily no gas left in current block.
  332. // OPTIMISE: could note this and then we don't evaluate until a block that does have the gas left.
  333. // for now, just leave alone.
  334. }
  335. }
  336. catch (Exception const& _e)
  337. {
  338. // Something else went wrong - drop it.
  339. clog(StateTrace) << t.sha3() << "Dropping invalid transaction:" << diagnostic_information(_e);
  340. _tq.drop(t.sha3());
  341. }
  342. catch (std::exception const&)
  343. {
  344. // Something else went wrong - drop it.
  345. _tq.drop(t.sha3());
  346. cwarn << t.sha3() << "Transaction caused low-level exception :(";
  347. }
  348. }
  349. if (chrono::steady_clock::now() > deadline)
  350. {
  351. ret.second = true; // say there's more to the caller if we ended up crossing the deadline.
  352. break;
  353. }
  354. }
  355. return ret;
  356. }
  357. u256 Block::enactOn(VerifiedBlockRef const& _block, BlockChain const& _bc)
  358. {
  359. noteChain(_bc);
  360. #if ETH_TIMED_ENACTMENTS
  361. Timer t;
  362. double populateVerify;
  363. double populateGrand;
  364. double syncReset;
  365. double enactment;
  366. #endif
  367. // Check family:
  368. BlockHeader biParent = _bc.info(_block.info.parentHash());
  369. _block.info.verify(CheckNothingNew/*CheckParent*/, biParent);
  370. #if ETH_TIMED_ENACTMENTS
  371. populateVerify = t.elapsed();
  372. t.restart();
  373. #endif
  374. BlockHeader biGrandParent;
  375. if (biParent.number())
  376. biGrandParent = _bc.info(biParent.parentHash());
  377. #if ETH_TIMED_ENACTMENTS
  378. populateGrand = t.elapsed();
  379. t.restart();
  380. #endif
  381. sync(_bc, _block.info.parentHash(), BlockHeader());
  382. resetCurrent();
  383. #if ETH_TIMED_ENACTMENTS
  384. syncReset = t.elapsed();
  385. t.restart();
  386. #endif
  387. m_previousBlock = biParent;
  388. auto ret = enact(_block, _bc);
  389. #if ETH_TIMED_ENACTMENTS
  390. enactment = t.elapsed();
  391. if (populateVerify + populateGrand + syncReset + enactment > 0.5)
  392. clog(StateChat) << "popVer/popGrand/syncReset/enactment = " << populateVerify << "/" << populateGrand << "/" << syncReset << "/" << enactment;
  393. #endif
  394. return ret;
  395. }
  396. u256 Block::enact(VerifiedBlockRef const& _block, BlockChain const& _bc)
  397. {
  398. noteChain(_bc);
  399. DEV_TIMED_FUNCTION_ABOVE(500);
  400. // m_currentBlock is assumed to be prepopulated and reset.
  401. #if !ETH_RELEASE
  402. assert(m_previousBlock.hash() == _block.info.parentHash());
  403. assert(m_currentBlock.parentHash() == _block.info.parentHash());
  404. #endif
  405. if (m_currentBlock.parentHash() != m_previousBlock.hash())
  406. // Internal client error.
  407. BOOST_THROW_EXCEPTION(InvalidParentHash());
  408. // Populate m_currentBlock with the correct values.
  409. m_currentBlock.noteDirty();
  410. m_currentBlock = _block.info;
  411. // cnote << "playback begins:" << m_currentBlock.hash() << "(without: " << m_currentBlock.hash(WithoutSeal) << ")";
  412. // cnote << m_state;
  413. LastHashes lh;
  414. DEV_TIMED_ABOVE("lastHashes", 500)
  415. lh = _bc.lastHashes(m_currentBlock.parentHash());
  416. RLP rlp(_block.block);
  417. vector<bytes> receipts;
  418. // All ok with the block generally. Play back the transactions now...
  419. unsigned i = 0;
  420. DEV_TIMED_ABOVE("txExec", 500)
  421. for (Transaction const& tr: _block.transactions)
  422. {
  423. try
  424. {
  425. LogOverride<ExecutiveWarnChannel> o(false);
  426. // cnote << "Enacting transaction: " << tr.nonce() << tr.from() << state().transactionsFrom(tr.from()) << tr.value();
  427. execute(lh, tr);
  428. // cnote << "Now: " << tr.from() << state().transactionsFrom(tr.from());
  429. // cnote << m_state;
  430. }
  431. catch (Exception& ex)
  432. {
  433. ex << errinfo_transactionIndex(i);
  434. throw;
  435. }
  436. RLPStream receiptRLP;
  437. m_receipts.back().streamRLP(receiptRLP);
  438. receipts.push_back(receiptRLP.out());
  439. ++i;
  440. }
  441. h256 receiptsRoot;
  442. DEV_TIMED_ABOVE(".receiptsRoot()", 500)
  443. receiptsRoot = orderedTrieRoot(receipts);
  444. if (receiptsRoot != m_currentBlock.receiptsRoot())
  445. {
  446. InvalidReceiptsStateRoot ex;
  447. ex << Hash256RequirementError(receiptsRoot, m_currentBlock.receiptsRoot());
  448. ex << errinfo_receipts(receipts);
  449. // ex << errinfo_vmtrace(vmTrace(_block.block, _bc, ImportRequirements::None));
  450. BOOST_THROW_EXCEPTION(ex);
  451. }
  452. if (m_currentBlock.logBloom() != logBloom())
  453. {
  454. InvalidLogBloom ex;
  455. ex << LogBloomRequirementError(logBloom(), m_currentBlock.logBloom());
  456. ex << errinfo_receipts(receipts);
  457. BOOST_THROW_EXCEPTION(ex);
  458. }
  459. // Initialise total difficulty calculation.
  460. u256 tdIncrease = m_currentBlock.difficulty();
  461. // Check uncles & apply their rewards to state.
  462. if (rlp[2].itemCount() > 2)
  463. {
  464. TooManyUncles ex;
  465. ex << errinfo_max(2);
  466. ex << errinfo_got(rlp[2].itemCount());
  467. BOOST_THROW_EXCEPTION(ex);
  468. }
  469. vector<BlockHeader> rewarded;
  470. h256Hash excluded;
  471. DEV_TIMED_ABOVE("allKin", 500)
  472. excluded = _bc.allKinFrom(m_currentBlock.parentHash(), 6);
  473. excluded.insert(m_currentBlock.hash());
  474. unsigned ii = 0;
  475. DEV_TIMED_ABOVE("uncleCheck", 500)
  476. for (auto const& i: rlp[2])
  477. {
  478. try
  479. {
  480. auto h = sha3(i.data());
  481. if (excluded.count(h))
  482. {
  483. UncleInChain ex;
  484. ex << errinfo_comment("Uncle in block already mentioned");
  485. ex << errinfo_unclesExcluded(excluded);
  486. ex << errinfo_hash256(sha3(i.data()));
  487. BOOST_THROW_EXCEPTION(ex);
  488. }
  489. excluded.insert(h);
  490. // CheckNothing since it's a VerifiedBlock.
  491. BlockHeader uncle(i.data(), HeaderData, h);
  492. BlockHeader uncleParent;
  493. if (!_bc.isKnown(uncle.parentHash()))
  494. BOOST_THROW_EXCEPTION(UnknownParent() << errinfo_hash256(uncle.parentHash()));
  495. uncleParent = BlockHeader(_bc.block(uncle.parentHash()));
  496. // m_currentBlock.number() - uncle.number() m_cB.n - uP.n()
  497. // 1 2
  498. // 2
  499. // 3
  500. // 4
  501. // 5
  502. // 6 7
  503. // (8 Invalid)
  504. bigint depth = (bigint)m_currentBlock.number() - (bigint)uncle.number();
  505. if (depth > 6)
  506. {
  507. UncleTooOld ex;
  508. ex << errinfo_uncleNumber(uncle.number());
  509. ex << errinfo_currentNumber(m_currentBlock.number());
  510. BOOST_THROW_EXCEPTION(ex);
  511. }
  512. else if (depth < 1)
  513. {
  514. UncleIsBrother ex;
  515. ex << errinfo_uncleNumber(uncle.number());
  516. ex << errinfo_currentNumber(m_currentBlock.number());
  517. BOOST_THROW_EXCEPTION(ex);
  518. }
  519. // cB
  520. // cB.p^1 1 depth, valid uncle
  521. // cB.p^2 ---/ 2
  522. // cB.p^3 -----/ 3
  523. // cB.p^4 -------/ 4
  524. // cB.p^5 ---------/ 5
  525. // cB.p^6 -----------/ 6
  526. // cB.p^7 -------------/
  527. // cB.p^8
  528. auto expectedUncleParent = _bc.details(m_currentBlock.parentHash()).parent;
  529. for (unsigned i = 1; i < depth; expectedUncleParent = _bc.details(expectedUncleParent).parent, ++i) {}
  530. if (expectedUncleParent != uncleParent.hash())
  531. {
  532. UncleParentNotInChain ex;
  533. ex << errinfo_uncleNumber(uncle.number());
  534. ex << errinfo_currentNumber(m_currentBlock.number());
  535. BOOST_THROW_EXCEPTION(ex);
  536. }
  537. uncle.verify(CheckNothingNew/*CheckParent*/, uncleParent);
  538. rewarded.push_back(uncle);
  539. ++ii;
  540. }
  541. catch (Exception& ex)
  542. {
  543. ex << errinfo_uncleIndex(ii);
  544. throw;
  545. }
  546. }
  547. DEV_TIMED_ABOVE("applyRewards", 500)
  548. applyRewards(rewarded, _bc.chainParams().blockReward);
  549. // Commit all cached state changes to the state trie.
  550. bool removeEmptyAccounts = m_currentBlock.number() >= _bc.chainParams().u256Param("EIP158ForkBlock");
  551. DEV_TIMED_ABOVE("commit", 500)
  552. m_state.commit(removeEmptyAccounts ? State::CommitBehaviour::RemoveEmptyAccounts : State::CommitBehaviour::KeepEmptyAccounts);
  553. // Hash the state trie and check against the state_root hash in m_currentBlock.
  554. if (m_currentBlock.stateRoot() != m_previousBlock.stateRoot() && m_currentBlock.stateRoot() != rootHash())
  555. {
  556. auto r = rootHash();
  557. m_state.db().rollback(); // TODO: API in State for this?
  558. BOOST_THROW_EXCEPTION(InvalidStateRoot() << Hash256RequirementError(r, m_currentBlock.stateRoot()));
  559. }
  560. if (m_currentBlock.gasUsed() != gasUsed())
  561. {
  562. // Rollback the trie.
  563. m_state.db().rollback(); // TODO: API in State for this?
  564. BOOST_THROW_EXCEPTION(InvalidGasUsed() << RequirementError(bigint(gasUsed()), bigint(m_currentBlock.gasUsed())));
  565. }
  566. return tdIncrease;
  567. }
  568. ExecutionResult Block::execute(LastHashes const& _lh, Transaction const& _t, Permanence _p, OnOpFunc const& _onOp)
  569. {
  570. if (isSealed())
  571. BOOST_THROW_EXCEPTION(InvalidOperationOnSealedBlock());
  572. // Uncommitting is a non-trivial operation - only do it once we've verified as much of the
  573. // transaction as possible.
  574. uncommitToSeal();
  575. std::pair<ExecutionResult, TransactionReceipt> resultReceipt = m_state.execute(EnvInfo(info(), _lh, gasUsed()), *m_sealEngine, _t, _p, _onOp);
  576. if (_p == Permanence::Committed)
  577. {
  578. // Add to the user-originated transactions that we've executed.
  579. m_transactions.push_back(_t);
  580. m_receipts.push_back(resultReceipt.second);
  581. m_transactionSet.insert(_t.sha3());
  582. }
  583. return resultReceipt.first;
  584. }
  585. void Block::applyRewards(vector<BlockHeader> const& _uncleBlockHeaders, u256 const& _blockReward)
  586. {
  587. u256 r = _blockReward;
  588. for (auto const& i: _uncleBlockHeaders)
  589. {
  590. m_state.addBalance(i.author(), _blockReward * (8 + i.number() - m_currentBlock.number()) / 8);
  591. r += _blockReward / 32;
  592. }
  593. m_state.addBalance(m_currentBlock.author(), r);
  594. }
  595. void Block::performIrregularModifications()
  596. {
  597. u256 daoHardfork = m_sealEngine->chainParams().u256Param("daoHardforkBlock");
  598. if (daoHardfork != 0 && info().number() == daoHardfork)
  599. {
  600. Address recipient("0xbf4ed7b27f1d666546e30d74d50d173d20bca754");
  601. Addresses allDAOs = childDaos();
  602. for (Address const& dao: allDAOs)
  603. m_state.transferBalance(dao, recipient, m_state.balance(dao));
  604. m_state.commit(State::CommitBehaviour::KeepEmptyAccounts);
  605. }
  606. }
  607. void Block::commitToSeal(BlockChain const& _bc, bytes const& _extraData)
  608. {
  609. if (isSealed())
  610. BOOST_THROW_EXCEPTION(InvalidOperationOnSealedBlock());
  611. noteChain(_bc);
  612. if (m_committedToSeal)
  613. uncommitToSeal();
  614. else
  615. m_precommit = m_state;
  616. vector<BlockHeader> uncleBlockHeaders;
  617. RLPStream unclesData;
  618. unsigned unclesCount = 0;
  619. if (m_previousBlock.number() != 0)
  620. {
  621. // 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.
  622. clog(StateDetail) << "Checking " << m_previousBlock.hash() << ", parent=" << m_previousBlock.parentHash();
  623. h256Hash excluded = _bc.allKinFrom(m_currentBlock.parentHash(), 6);
  624. auto p = m_previousBlock.parentHash();
  625. for (unsigned gen = 0; gen < 6 && p != _bc.genesisHash() && unclesCount < 2; ++gen, p = _bc.details(p).parent)
  626. {
  627. auto us = _bc.details(p).children;
  628. assert(us.size() >= 1); // must be at least 1 child of our grandparent - it's our own parent!
  629. for (auto const& u: us)
  630. if (!excluded.count(u)) // ignore any uncles/mainline blocks that we know about.
  631. {
  632. uncleBlockHeaders.push_back(_bc.info(u));
  633. unclesData.appendRaw(_bc.headerData(u));
  634. ++unclesCount;
  635. if (unclesCount == 2)
  636. break;
  637. excluded.insert(u);
  638. }
  639. }
  640. }
  641. BytesMap transactionsMap;
  642. BytesMap receiptsMap;
  643. RLPStream txs;
  644. txs.appendList(m_transactions.size());
  645. for (unsigned i = 0; i < m_transactions.size(); ++i)
  646. {
  647. RLPStream k;
  648. k << i;
  649. RLPStream receiptrlp;
  650. m_receipts[i].streamRLP(receiptrlp);
  651. receiptsMap.insert(std::make_pair(k.out(), receiptrlp.out()));
  652. RLPStream txrlp;
  653. m_transactions[i].streamRLP(txrlp);
  654. transactionsMap.insert(std::make_pair(k.out(), txrlp.out()));
  655. txs.appendRaw(txrlp.out());
  656. //#if ETH_PARANOIA
  657. /* if (fromPending(i).transactionsFrom(m_transactions[i].from()) != m_transactions[i].nonce())
  658. {
  659. cwarn << "GAAA Something went wrong! " << fromPending(i).transactionsFrom(m_transactions[i].from()) << "!=" << m_transactions[i].nonce();
  660. }*/
  661. //#endif
  662. }
  663. txs.swapOut(m_currentTxs);
  664. RLPStream(unclesCount).appendRaw(unclesData.out(), unclesCount).swapOut(m_currentUncles);
  665. // Apply rewards last of all.
  666. applyRewards(uncleBlockHeaders, _bc.chainParams().blockReward);
  667. // Commit any and all changes to the trie that are in the cache, then update the state root accordingly.
  668. bool removeEmptyAccounts = m_currentBlock.number() >= _bc.chainParams().u256Param("EIP158ForkBlock");
  669. DEV_TIMED_ABOVE("commit", 500)
  670. m_state.commit(removeEmptyAccounts ? State::CommitBehaviour::RemoveEmptyAccounts : State::CommitBehaviour::KeepEmptyAccounts);
  671. clog(StateDetail) << "Post-reward stateRoot:" << m_state.rootHash();
  672. clog(StateDetail) << m_state;
  673. clog(StateDetail) << *this;
  674. m_currentBlock.setLogBloom(logBloom());
  675. m_currentBlock.setGasUsed(gasUsed());
  676. m_currentBlock.setRoots(hash256(transactionsMap), hash256(receiptsMap), sha3(m_currentUncles), m_state.rootHash());
  677. m_currentBlock.setParentHash(m_previousBlock.hash());
  678. m_currentBlock.setExtraData(_extraData);
  679. if (m_currentBlock.extraData().size() > 32)
  680. {
  681. auto ed = m_currentBlock.extraData();
  682. ed.resize(32);
  683. m_currentBlock.setExtraData(ed);
  684. }
  685. m_committedToSeal = true;
  686. }
  687. void Block::uncommitToSeal()
  688. {
  689. if (m_committedToSeal)
  690. {
  691. m_state = m_precommit;
  692. m_committedToSeal = false;
  693. }
  694. }
  695. bool Block::sealBlock(bytesConstRef _header)
  696. {
  697. if (!m_committedToSeal)
  698. return false;
  699. if (BlockHeader(_header, HeaderData).hash(WithoutSeal) != m_currentBlock.hash(WithoutSeal))
  700. return false;
  701. clog(StateDetail) << "Sealing block!";
  702. // Compile block:
  703. RLPStream ret;
  704. ret.appendList(3);
  705. ret.appendRaw(_header);
  706. ret.appendRaw(m_currentTxs);
  707. ret.appendRaw(m_currentUncles);
  708. ret.swapOut(m_currentBytes);
  709. m_currentBlock = BlockHeader(_header, HeaderData);
  710. // cnote << "Mined " << m_currentBlock.hash() << "(parent: " << m_currentBlock.parentHash() << ")";
  711. // TODO: move into SealEngine
  712. m_state = m_precommit;
  713. // m_currentBytes is now non-empty; we're in a sealed state so no more transactions can be added.
  714. return true;
  715. }
  716. State Block::fromPending(unsigned _i) const
  717. {
  718. State ret = m_state;
  719. _i = min<unsigned>(_i, m_transactions.size());
  720. if (!_i)
  721. ret.setRoot(m_previousBlock.stateRoot());
  722. else
  723. ret.setRoot(m_receipts[_i - 1].stateRoot());
  724. return ret;
  725. }
  726. LogBloom Block::logBloom() const
  727. {
  728. LogBloom ret;
  729. for (TransactionReceipt const& i: m_receipts)
  730. ret |= i.bloom();
  731. return ret;
  732. }
  733. void Block::cleanup(bool _fullCommit)
  734. {
  735. if (_fullCommit)
  736. {
  737. // Commit the new trie to disk.
  738. if (isChannelVisible<StateTrace>()) // Avoid calling toHex if not needed
  739. clog(StateTrace) << "Committing to disk: stateRoot" << m_currentBlock.stateRoot() << "=" << rootHash() << "=" << toHex(asBytes(db().lookup(rootHash())));
  740. try
  741. {
  742. EnforceRefs er(db(), true);
  743. rootHash();
  744. }
  745. catch (BadRoot const&)
  746. {
  747. clog(StateChat) << "Trie corrupt! :-(";
  748. throw;
  749. }
  750. m_state.db().commit(); // TODO: State API for this?
  751. if (isChannelVisible<StateTrace>()) // Avoid calling toHex if not needed
  752. clog(StateTrace) << "Committed: stateRoot" << m_currentBlock.stateRoot() << "=" << rootHash() << "=" << toHex(asBytes(db().lookup(rootHash())));
  753. m_previousBlock = m_currentBlock;
  754. sealEngine()->populateFromParent(m_currentBlock, m_previousBlock);
  755. clog(StateTrace) << "finalising enactment. current -> previous, hash is" << m_previousBlock.hash();
  756. }
  757. else
  758. m_state.db().rollback(); // TODO: State API for this?
  759. resetCurrent();
  760. }
  761. string Block::vmTrace(bytesConstRef _block, BlockChain const& _bc, ImportRequirements::value _ir)
  762. {
  763. noteChain(_bc);
  764. RLP rlp(_block);
  765. cleanup(false);
  766. BlockHeader bi(_block);
  767. m_currentBlock = bi;
  768. m_currentBlock.verify((_ir & ImportRequirements::ValidSeal) ? CheckEverything : IgnoreSeal, _block);
  769. m_currentBlock.noteDirty();
  770. LastHashes lh = _bc.lastHashes(m_currentBlock.parentHash());
  771. string ret;
  772. unsigned i = 0;
  773. for (auto const& tr: rlp[1])
  774. {
  775. StandardTrace st;
  776. st.setShowMnemonics();
  777. execute(lh, Transaction(tr.data(), CheckTransaction::Everything), Permanence::Committed, st.onOp());
  778. ret += (ret.empty() ? "[" : ",") + st.json();
  779. ++i;
  780. }
  781. return ret.empty() ? "[]" : (ret + "]");
  782. }
  783. std::ostream& dev::eth::operator<<(std::ostream& _out, Block const& _s)
  784. {
  785. (void)_s;
  786. return _out;
  787. }