Client.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847
  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 Client.cpp
  15. * @author Gav Wood <i@gavwood.com>
  16. * @date 2014
  17. */
  18. #include "Client.h"
  19. #include <chrono>
  20. #include <memory>
  21. #include <thread>
  22. #include <boost/filesystem.hpp>
  23. #include <libdevcore/Log.h>
  24. #include <libp2p/Host.h>
  25. #include "Defaults.h"
  26. #include "Executive.h"
  27. #include "EthereumHost.h"
  28. #include "Utility.h"
  29. #include "Block.h"
  30. #include "TransactionQueue.h"
  31. using namespace std;
  32. using namespace dev;
  33. using namespace dev::eth;
  34. using namespace p2p;
  35. std::ostream& dev::eth::operator<<(std::ostream& _out, ActivityReport const& _r)
  36. {
  37. _out << "Since " << toString(_r.since) << " (" << std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock::now() - _r.since).count();
  38. _out << "): " << _r.ticks << "ticks";
  39. return _out;
  40. }
  41. #if defined(_WIN32)
  42. const char* ClientNote::name() { return EthTeal "^" EthBlue " i"; }
  43. const char* ClientChat::name() { return EthTeal "^" EthWhite " o"; }
  44. const char* ClientTrace::name() { return EthTeal "^" EthGray " O"; }
  45. const char* ClientDetail::name() { return EthTeal "^" EthCoal " 0"; }
  46. #else
  47. const char* ClientNote::name() { return EthTeal "⧫" EthBlue " ℹ"; }
  48. const char* ClientChat::name() { return EthTeal "⧫" EthWhite " ◌"; }
  49. const char* ClientTrace::name() { return EthTeal "⧫" EthGray " ◎"; }
  50. const char* ClientDetail::name() { return EthTeal "⧫" EthCoal " ●"; }
  51. #endif
  52. Client::Client(
  53. ChainParams const& _params,
  54. int _networkID,
  55. p2p::Host* _host,
  56. std::shared_ptr<GasPricer> _gpForAdoption,
  57. std::string const& _dbPath,
  58. WithExisting _forceAction,
  59. TransactionQueue::Limits const& _l
  60. ):
  61. ClientBase(_l),
  62. Worker("eth", 0),
  63. m_bc(_params, _dbPath, _forceAction, [](unsigned d, unsigned t){ std::cerr << "REVISING BLOCKCHAIN: Processed " << d << " of " << t << "...\r"; }),
  64. m_gp(_gpForAdoption ? _gpForAdoption : make_shared<TrivialGasPricer>()),
  65. m_preSeal(chainParams().accountStartNonce),
  66. m_postSeal(chainParams().accountStartNonce),
  67. m_working(chainParams().accountStartNonce)
  68. {
  69. init(_host, _dbPath, _forceAction, _networkID);
  70. }
  71. Client::~Client()
  72. {
  73. stopWorking();
  74. }
  75. void Client::init(p2p::Host* _extNet, std::string const& _dbPath, WithExisting _forceAction, u256 _networkId)
  76. {
  77. DEV_TIMED_FUNCTION_ABOVE(500);
  78. // Cannot be opened until after blockchain is open, since BlockChain may upgrade the database.
  79. // TODO: consider returning the upgrade mechanism here. will delaying the opening of the blockchain database
  80. // until after the construction.
  81. m_stateDB = State::openDB(_dbPath, bc().genesisHash(), _forceAction);
  82. // LAZY. TODO: move genesis state construction/commiting to stateDB openning and have this just take the root from the genesis block.
  83. m_preSeal = bc().genesisBlock(m_stateDB);
  84. m_postSeal = m_preSeal;
  85. m_bq.setChain(bc());
  86. m_lastGetWork = std::chrono::system_clock::now() - chrono::seconds(30);
  87. m_tqReady = m_tq.onReady([=](){ this->onTransactionQueueReady(); }); // TODO: should read m_tq->onReady(thisThread, syncTransactionQueue);
  88. m_tqReplaced = m_tq.onReplaced([=](h256 const&){ m_needStateReset = true; });
  89. m_bqReady = m_bq.onReady([=](){ this->onBlockQueueReady(); }); // TODO: should read m_bq->onReady(thisThread, syncBlockQueue);
  90. m_bq.setOnBad([=](Exception& ex){ this->onBadBlock(ex); });
  91. bc().setOnBad([=](Exception& ex){ this->onBadBlock(ex); });
  92. if (_forceAction == WithExisting::Rescue)
  93. bc().rescue(m_stateDB);
  94. m_gp->update(bc());
  95. auto host = _extNet->registerCapability(make_shared<EthereumHost>(bc(), m_stateDB, m_tq, m_bq, _networkId));
  96. m_host = host;
  97. _extNet->addCapability(host, EthereumHost::staticName(), EthereumHost::c_oldProtocolVersion); //TODO: remove this once v61+ protocol is common
  98. if (_dbPath.size())
  99. Defaults::setDBPath(_dbPath);
  100. doWork(false);
  101. startWorking();
  102. }
  103. ImportResult Client::queueBlock(bytes const& _block, bool _isSafe)
  104. {
  105. if (m_bq.status().verified + m_bq.status().verifying + m_bq.status().unverified > 10000)
  106. this_thread::sleep_for(std::chrono::milliseconds(500));
  107. return m_bq.import(&_block, _isSafe);
  108. }
  109. tuple<ImportRoute, bool, unsigned> Client::syncQueue(unsigned _max)
  110. {
  111. stopWorking();
  112. return bc().sync(m_bq, m_stateDB, _max);
  113. }
  114. void Client::onBadBlock(Exception& _ex) const
  115. {
  116. // BAD BLOCK!!!
  117. bytes const* block = boost::get_error_info<errinfo_block>(_ex);
  118. if (!block)
  119. {
  120. cwarn << "ODD: onBadBlock called but exception (" << _ex.what() << ") has no block in it.";
  121. cwarn << boost::diagnostic_information(_ex, true);
  122. return;
  123. }
  124. badBlock(*block, _ex.what());
  125. }
  126. void Client::callQueuedFunctions()
  127. {
  128. while (true)
  129. {
  130. function<void()> f;
  131. DEV_WRITE_GUARDED(x_functionQueue)
  132. if (!m_functionQueue.empty())
  133. {
  134. f = m_functionQueue.front();
  135. m_functionQueue.pop();
  136. }
  137. if (f)
  138. f();
  139. else
  140. break;
  141. }
  142. }
  143. u256 Client::networkId() const
  144. {
  145. if (auto h = m_host.lock())
  146. return h->networkId();
  147. return 0;
  148. }
  149. void Client::setNetworkId(u256 const& _n)
  150. {
  151. if (auto h = m_host.lock())
  152. h->setNetworkId(_n);
  153. }
  154. bool Client::isSyncing() const
  155. {
  156. if (auto h = m_host.lock())
  157. return h->isSyncing();
  158. return false;
  159. }
  160. bool Client::isMajorSyncing() const
  161. {
  162. if (auto h = m_host.lock())
  163. {
  164. SyncState state = h->status().state;
  165. return (state != SyncState::Idle && state != SyncState::NewBlocks) || h->bq().items().first > 10;
  166. }
  167. return false;
  168. }
  169. void Client::startedWorking()
  170. {
  171. // Synchronise the state according to the head of the block chain.
  172. // TODO: currently it contains keys for *all* blocks. Make it remove old ones.
  173. clog(ClientTrace) << "startedWorking()";
  174. DEV_WRITE_GUARDED(x_preSeal)
  175. m_preSeal.sync(bc());
  176. DEV_READ_GUARDED(x_preSeal)
  177. {
  178. DEV_WRITE_GUARDED(x_working)
  179. m_working = m_preSeal;
  180. DEV_WRITE_GUARDED(x_postSeal)
  181. m_postSeal = m_preSeal;
  182. }
  183. }
  184. void Client::doneWorking()
  185. {
  186. // Synchronise the state according to the head of the block chain.
  187. // TODO: currently it contains keys for *all* blocks. Make it remove old ones.
  188. DEV_WRITE_GUARDED(x_preSeal)
  189. m_preSeal.sync(bc());
  190. DEV_READ_GUARDED(x_preSeal)
  191. {
  192. DEV_WRITE_GUARDED(x_working)
  193. m_working = m_preSeal;
  194. DEV_WRITE_GUARDED(x_postSeal)
  195. m_postSeal = m_preSeal;
  196. }
  197. }
  198. void Client::reopenChain(WithExisting _we)
  199. {
  200. reopenChain(bc().chainParams(), _we);
  201. }
  202. void Client::reopenChain(ChainParams const& _p, WithExisting _we)
  203. {
  204. bool wasSealing = wouldSeal();
  205. if (wasSealing)
  206. stopSealing();
  207. stopWorking();
  208. m_tq.clear();
  209. m_bq.clear();
  210. sealEngine()->cancelGeneration();
  211. {
  212. WriteGuard l(x_postSeal);
  213. WriteGuard l2(x_preSeal);
  214. WriteGuard l3(x_working);
  215. auto author = m_preSeal.author(); // backup and restore author.
  216. m_preSeal = Block(chainParams().accountStartNonce);
  217. m_postSeal = Block(chainParams().accountStartNonce);
  218. m_working = Block(chainParams().accountStartNonce);
  219. m_stateDB = OverlayDB();
  220. bc().reopen(_p, _we);
  221. m_stateDB = State::openDB(Defaults::dbPath(), bc().genesisHash(), _we);
  222. m_preSeal = bc().genesisBlock(m_stateDB);
  223. m_preSeal.setAuthor(author);
  224. m_postSeal = m_preSeal;
  225. m_working = Block(chainParams().accountStartNonce);
  226. }
  227. if (auto h = m_host.lock())
  228. h->reset();
  229. startedWorking();
  230. doWork();
  231. startWorking();
  232. if (wasSealing)
  233. startSealing();
  234. }
  235. void Client::executeInMainThread(function<void ()> const& _function)
  236. {
  237. DEV_WRITE_GUARDED(x_functionQueue)
  238. m_functionQueue.push(_function);
  239. m_signalled.notify_all();
  240. }
  241. void Client::clearPending()
  242. {
  243. DEV_WRITE_GUARDED(x_postSeal)
  244. {
  245. if (!m_postSeal.pending().size())
  246. return;
  247. m_tq.clear();
  248. DEV_READ_GUARDED(x_preSeal)
  249. m_postSeal = m_preSeal;
  250. }
  251. startSealing();
  252. h256Hash changeds;
  253. noteChanged(changeds);
  254. }
  255. template <class S, class T>
  256. static S& filtersStreamOut(S& _out, T const& _fs)
  257. {
  258. _out << "{";
  259. unsigned i = 0;
  260. for (h256 const& f: _fs)
  261. {
  262. _out << (i++ ? ", " : "");
  263. if (f == PendingChangedFilter)
  264. _out << LogTag::Special << "pending";
  265. else if (f == ChainChangedFilter)
  266. _out << LogTag::Special << "chain";
  267. else
  268. _out << f;
  269. }
  270. _out << "}";
  271. return _out;
  272. }
  273. void Client::appendFromNewPending(TransactionReceipt const& _receipt, h256Hash& io_changed, h256 _sha3)
  274. {
  275. Guard l(x_filtersWatches);
  276. io_changed.insert(PendingChangedFilter);
  277. m_specialFilters.at(PendingChangedFilter).push_back(_sha3);
  278. for (pair<h256 const, InstalledFilter>& i: m_filters)
  279. {
  280. // acceptable number.
  281. auto m = i.second.filter.matches(_receipt);
  282. if (m.size())
  283. {
  284. // filter catches them
  285. for (LogEntry const& l: m)
  286. i.second.changes.push_back(LocalisedLogEntry(l));
  287. io_changed.insert(i.first);
  288. }
  289. }
  290. }
  291. void Client::appendFromBlock(h256 const& _block, BlockPolarity _polarity, h256Hash& io_changed)
  292. {
  293. // TODO: more precise check on whether the txs match.
  294. auto receipts = bc().receipts(_block).receipts;
  295. Guard l(x_filtersWatches);
  296. io_changed.insert(ChainChangedFilter);
  297. m_specialFilters.at(ChainChangedFilter).push_back(_block);
  298. for (pair<h256 const, InstalledFilter>& i: m_filters)
  299. {
  300. // acceptable number & looks like block may contain a matching log entry.
  301. for (size_t j = 0; j < receipts.size(); j++)
  302. {
  303. auto tr = receipts[j];
  304. auto m = i.second.filter.matches(tr);
  305. if (m.size())
  306. {
  307. auto transactionHash = transaction(_block, j).sha3();
  308. // filter catches them
  309. for (LogEntry const& l: m)
  310. i.second.changes.push_back(LocalisedLogEntry(l, _block, (BlockNumber)bc().number(_block), transactionHash, j, 0, _polarity));
  311. io_changed.insert(i.first);
  312. }
  313. }
  314. }
  315. }
  316. ExecutionResult Client::call(Address _dest, bytes const& _data, u256 _gas, u256 _value, u256 _gasPrice, Address const& _from)
  317. {
  318. ExecutionResult ret;
  319. try
  320. {
  321. Block temp(chainParams().accountStartNonce);
  322. clog(ClientDetail) << "Nonce at " << _dest << " pre:" << m_preSeal.transactionsFrom(_dest) << " post:" << m_postSeal.transactionsFrom(_dest);
  323. DEV_READ_GUARDED(x_postSeal)
  324. temp = m_postSeal;
  325. temp.mutableState().addBalance(_from, _value + _gasPrice * _gas);
  326. Executive e(temp);
  327. e.setResultRecipient(ret);
  328. if (!e.call(_dest, _from, _value, _gasPrice, &_data, _gas))
  329. e.go();
  330. e.finalize();
  331. }
  332. catch (...)
  333. {
  334. cwarn << "Client::call failed: " << boost::current_exception_diagnostic_information();
  335. }
  336. return ret;
  337. }
  338. unsigned static const c_syncMin = 1;
  339. unsigned static const c_syncMax = 1000;
  340. double static const c_targetDuration = 1;
  341. void Client::syncBlockQueue()
  342. {
  343. // cdebug << "syncBlockQueue()";
  344. ImportRoute ir;
  345. unsigned count;
  346. Timer t;
  347. tie(ir, m_syncBlockQueue, count) = bc().sync(m_bq, m_stateDB, m_syncAmount);
  348. double elapsed = t.elapsed();
  349. if (count)
  350. {
  351. clog(ClientNote) << count << "blocks imported in" << unsigned(elapsed * 1000) << "ms (" << (count / elapsed) << "blocks/s) in #" << bc().number();
  352. }
  353. if (elapsed > c_targetDuration * 1.1 && count > c_syncMin)
  354. m_syncAmount = max(c_syncMin, count * 9 / 10);
  355. else if (count == m_syncAmount && elapsed < c_targetDuration * 0.9 && m_syncAmount < c_syncMax)
  356. m_syncAmount = min(c_syncMax, m_syncAmount * 11 / 10 + 1);
  357. if (ir.liveBlocks.empty())
  358. return;
  359. onChainChanged(ir);
  360. }
  361. void Client::syncTransactionQueue()
  362. {
  363. Timer timer;
  364. h256Hash changeds;
  365. TransactionReceipts newPendingReceipts;
  366. DEV_WRITE_GUARDED(x_working)
  367. {
  368. if (m_working.isSealed())
  369. {
  370. ctrace << "Skipping txq sync for a sealed block.";
  371. return;
  372. }
  373. tie(newPendingReceipts, m_syncTransactionQueue) = m_working.sync(bc(), m_tq, *m_gp);
  374. }
  375. if (newPendingReceipts.empty())
  376. {
  377. auto s = m_tq.status();
  378. ctrace << "No transactions to process. " << m_working.pending().size() << " pending, " << s.current << " queued, " << s.future << " future, " << s.unverified << " unverified";
  379. return;
  380. }
  381. DEV_READ_GUARDED(x_working)
  382. DEV_WRITE_GUARDED(x_postSeal)
  383. m_postSeal = m_working;
  384. DEV_READ_GUARDED(x_postSeal)
  385. for (size_t i = 0; i < newPendingReceipts.size(); i++)
  386. appendFromNewPending(newPendingReceipts[i], changeds, m_postSeal.pending()[i].sha3());
  387. // Tell farm about new transaction (i.e. restart mining).
  388. onPostStateChanged();
  389. // Tell watches about the new transactions.
  390. noteChanged(changeds);
  391. // Tell network about the new transactions.
  392. if (auto h = m_host.lock())
  393. h->noteNewTransactions();
  394. ctrace << "Processed " << newPendingReceipts.size() << " transactions in" << (timer.elapsed() * 1000) << "(" << (bool)m_syncTransactionQueue << ")";
  395. }
  396. void Client::onDeadBlocks(h256s const& _blocks, h256Hash& io_changed)
  397. {
  398. // insert transactions that we are declaring the dead part of the chain
  399. for (auto const& h: _blocks)
  400. {
  401. clog(ClientTrace) << "Dead block:" << h;
  402. for (auto const& t: bc().transactions(h))
  403. {
  404. clog(ClientTrace) << "Resubmitting dead-block transaction " << Transaction(t, CheckTransaction::None);
  405. ctrace << "Resubmitting dead-block transaction " << Transaction(t, CheckTransaction::None);
  406. m_tq.import(t, IfDropped::Retry);
  407. }
  408. }
  409. for (auto const& h: _blocks)
  410. appendFromBlock(h, BlockPolarity::Dead, io_changed);
  411. }
  412. void Client::onNewBlocks(h256s const& _blocks, h256Hash& io_changed)
  413. {
  414. // remove transactions from m_tq nicely rather than relying on out of date nonce later on.
  415. for (auto const& h: _blocks)
  416. clog(ClientTrace) << "Live block:" << h;
  417. if (auto h = m_host.lock())
  418. h->noteNewBlocks();
  419. for (auto const& h: _blocks)
  420. appendFromBlock(h, BlockPolarity::Live, io_changed);
  421. }
  422. void Client::resyncStateFromChain()
  423. {
  424. // RESTART MINING
  425. // ctrace << "resyncStateFromChain()";
  426. if (!isMajorSyncing())
  427. {
  428. bool preChanged = false;
  429. Block newPreMine(chainParams().accountStartNonce);
  430. DEV_READ_GUARDED(x_preSeal)
  431. newPreMine = m_preSeal;
  432. // TODO: use m_postSeal to avoid re-evaluating our own blocks.
  433. preChanged = newPreMine.sync(bc());
  434. if (preChanged || m_postSeal.author() != m_preSeal.author())
  435. {
  436. DEV_WRITE_GUARDED(x_preSeal)
  437. m_preSeal = newPreMine;
  438. DEV_WRITE_GUARDED(x_working)
  439. m_working = newPreMine;
  440. DEV_READ_GUARDED(x_postSeal)
  441. if (!m_postSeal.isSealed() || m_postSeal.info().hash() != newPreMine.info().parentHash())
  442. for (auto const& t: m_postSeal.pending())
  443. {
  444. clog(ClientTrace) << "Resubmitting post-seal transaction " << t;
  445. // ctrace << "Resubmitting post-seal transaction " << t;
  446. auto ir = m_tq.import(t, IfDropped::Retry);
  447. if (ir != ImportResult::Success)
  448. onTransactionQueueReady();
  449. }
  450. DEV_READ_GUARDED(x_working) DEV_WRITE_GUARDED(x_postSeal)
  451. m_postSeal = m_working;
  452. onPostStateChanged();
  453. }
  454. // Quick hack for now - the TQ at this point already has the prior pending transactions in it;
  455. // we should resync with it manually until we are stricter about what constitutes "knowing".
  456. onTransactionQueueReady();
  457. }
  458. }
  459. void Client::resetState()
  460. {
  461. Block newPreMine(chainParams().accountStartNonce);
  462. DEV_READ_GUARDED(x_preSeal)
  463. newPreMine = m_preSeal;
  464. DEV_WRITE_GUARDED(x_working)
  465. m_working = newPreMine;
  466. DEV_READ_GUARDED(x_working) DEV_WRITE_GUARDED(x_postSeal)
  467. m_postSeal = m_working;
  468. onPostStateChanged();
  469. onTransactionQueueReady();
  470. }
  471. void Client::onChainChanged(ImportRoute const& _ir)
  472. {
  473. // ctrace << "onChainChanged()";
  474. h256Hash changeds;
  475. onDeadBlocks(_ir.deadBlocks, changeds);
  476. for (auto const& t: _ir.goodTranactions)
  477. {
  478. clog(ClientTrace) << "Safely dropping transaction " << t.sha3();
  479. m_tq.dropGood(t);
  480. }
  481. onNewBlocks(_ir.liveBlocks, changeds);
  482. resyncStateFromChain();
  483. noteChanged(changeds);
  484. }
  485. bool Client::remoteActive() const
  486. {
  487. return chrono::system_clock::now() - m_lastGetWork < chrono::seconds(30);
  488. }
  489. void Client::onPostStateChanged()
  490. {
  491. clog(ClientTrace) << "Post state changed.";
  492. m_signalled.notify_all();
  493. m_remoteWorking = false;
  494. }
  495. void Client::startSealing()
  496. {
  497. if (m_wouldSeal == true)
  498. return;
  499. clog(ClientNote) << "Mining Beneficiary: " << author();
  500. if (author())
  501. {
  502. m_wouldSeal = true;
  503. m_signalled.notify_all();
  504. }
  505. else
  506. clog(ClientNote) << "You need to set an author in order to seal!";
  507. }
  508. void Client::rejigSealing()
  509. {
  510. if ((wouldSeal() || remoteActive()) && !isMajorSyncing())
  511. {
  512. if (sealEngine()->shouldSeal(this))
  513. {
  514. m_wouldButShouldnot = false;
  515. clog(ClientTrace) << "Rejigging seal engine...";
  516. DEV_WRITE_GUARDED(x_working)
  517. {
  518. if (m_working.isSealed())
  519. {
  520. clog(ClientNote) << "Tried to seal sealed block...";
  521. return;
  522. }
  523. m_working.commitToSeal(bc(), m_extraData);
  524. }
  525. DEV_READ_GUARDED(x_working)
  526. {
  527. DEV_WRITE_GUARDED(x_postSeal)
  528. m_postSeal = m_working;
  529. m_sealingInfo = m_working.info();
  530. }
  531. if (wouldSeal())
  532. {
  533. sealEngine()->onSealGenerated([=](bytes const& header){
  534. if (!this->submitSealed(header))
  535. clog(ClientNote) << "Submitting block failed...";
  536. });
  537. ctrace << "Generating seal on" << m_sealingInfo.hash(WithoutSeal) << "#" << m_sealingInfo.number();
  538. sealEngine()->generateSeal(m_sealingInfo);
  539. }
  540. }
  541. else
  542. m_wouldButShouldnot = true;
  543. }
  544. if (!m_wouldSeal)
  545. sealEngine()->cancelGeneration();
  546. }
  547. void Client::noteChanged(h256Hash const& _filters)
  548. {
  549. Guard l(x_filtersWatches);
  550. if (_filters.size())
  551. filtersStreamOut(cwatch << "noteChanged:", _filters);
  552. // accrue all changes left in each filter into the watches.
  553. for (auto& w: m_watches)
  554. if (_filters.count(w.second.id))
  555. {
  556. if (m_filters.count(w.second.id))
  557. {
  558. cwatch << "!!!" << w.first << w.second.id.abridged();
  559. w.second.changes += m_filters.at(w.second.id).changes;
  560. }
  561. else if (m_specialFilters.count(w.second.id))
  562. for (h256 const& hash: m_specialFilters.at(w.second.id))
  563. {
  564. cwatch << "!!!" << w.first << LogTag::Special << (w.second.id == PendingChangedFilter ? "pending" : w.second.id == ChainChangedFilter ? "chain" : "???");
  565. w.second.changes.push_back(LocalisedLogEntry(SpecialLogEntry, hash));
  566. }
  567. }
  568. // clear the filters now.
  569. for (auto& i: m_filters)
  570. i.second.changes.clear();
  571. for (auto& i: m_specialFilters)
  572. i.second.clear();
  573. }
  574. void Client::doWork(bool _doWait)
  575. {
  576. bool t = true;
  577. if (m_syncBlockQueue.compare_exchange_strong(t, false))
  578. syncBlockQueue();
  579. if (m_needStateReset)
  580. {
  581. resetState();
  582. m_needStateReset = false;
  583. }
  584. t = true;
  585. bool isSealed = false;
  586. DEV_READ_GUARDED(x_working)
  587. isSealed = m_working.isSealed();
  588. if (!isSealed && !isSyncing() && !m_remoteWorking && m_syncTransactionQueue.compare_exchange_strong(t, false))
  589. syncTransactionQueue();
  590. tick();
  591. rejigSealing();
  592. callQueuedFunctions();
  593. DEV_READ_GUARDED(x_working)
  594. isSealed = m_working.isSealed();
  595. // If the block is sealed, we have to wait for it to tickle through the block queue
  596. // (which only signals as wanting to be synced if it is ready).
  597. if (!m_syncBlockQueue && !m_syncTransactionQueue && (_doWait || isSealed))
  598. {
  599. std::unique_lock<std::mutex> l(x_signalled);
  600. m_signalled.wait_for(l, chrono::seconds(1));
  601. }
  602. }
  603. void Client::tick()
  604. {
  605. if (chrono::system_clock::now() - m_lastTick > chrono::seconds(1))
  606. {
  607. m_report.ticks++;
  608. checkWatchGarbage();
  609. m_bq.tick();
  610. m_lastTick = chrono::system_clock::now();
  611. if (m_report.ticks == 15)
  612. clog(ClientTrace) << activityReport();
  613. }
  614. }
  615. void Client::checkWatchGarbage()
  616. {
  617. if (chrono::system_clock::now() - m_lastGarbageCollection > chrono::seconds(5))
  618. {
  619. // watches garbage collection
  620. vector<unsigned> toUninstall;
  621. DEV_GUARDED(x_filtersWatches)
  622. for (auto key: keysOf(m_watches))
  623. if (m_watches[key].lastPoll != chrono::system_clock::time_point::max() && chrono::system_clock::now() - m_watches[key].lastPoll > chrono::seconds(20))
  624. {
  625. toUninstall.push_back(key);
  626. clog(ClientTrace) << "GC: Uninstall" << key << "(" << chrono::duration_cast<chrono::seconds>(chrono::system_clock::now() - m_watches[key].lastPoll).count() << "s old)";
  627. }
  628. for (auto i: toUninstall)
  629. uninstallWatch(i);
  630. // blockchain GC
  631. bc().garbageCollect();
  632. m_lastGarbageCollection = chrono::system_clock::now();
  633. }
  634. }
  635. void Client::prepareForTransaction()
  636. {
  637. startWorking();
  638. }
  639. Block Client::block(h256 const& _block) const
  640. {
  641. try
  642. {
  643. Block ret(bc(), m_stateDB);
  644. ret.populateFromChain(bc(), _block);
  645. return ret;
  646. }
  647. catch (Exception& ex)
  648. {
  649. ex << errinfo_block(bc().block(_block));
  650. onBadBlock(ex);
  651. return Block(bc());
  652. }
  653. }
  654. Block Client::block(h256 const& _blockHash, PopulationStatistics* o_stats) const
  655. {
  656. try
  657. {
  658. Block ret(bc(), m_stateDB);
  659. PopulationStatistics s = ret.populateFromChain(bc(), _blockHash);
  660. if (o_stats)
  661. swap(s, *o_stats);
  662. return ret;
  663. }
  664. catch (Exception& ex)
  665. {
  666. ex << errinfo_block(bc().block(_blockHash));
  667. onBadBlock(ex);
  668. return Block(bc());
  669. }
  670. }
  671. State Client::state(unsigned _txi, h256 const& _blockHash) const
  672. {
  673. try
  674. {
  675. return block(_blockHash).fromPending(_txi);
  676. }
  677. catch (Exception& ex)
  678. {
  679. ex << errinfo_block(bc().block(_blockHash));
  680. onBadBlock(ex);
  681. return State(chainParams().accountStartNonce);
  682. }
  683. }
  684. eth::State Client::state(unsigned _txi) const
  685. {
  686. DEV_READ_GUARDED(x_postSeal)
  687. return m_postSeal.fromPending(_txi);
  688. assert(false);
  689. return State(chainParams().accountStartNonce);
  690. }
  691. void Client::flushTransactions()
  692. {
  693. doWork();
  694. }
  695. SyncStatus Client::syncStatus() const
  696. {
  697. auto h = m_host.lock();
  698. if (!h)
  699. return SyncStatus();
  700. SyncStatus status = h->status();
  701. status.majorSyncing = isMajorSyncing();
  702. return status;
  703. }
  704. bool Client::submitSealed(bytes const& _header)
  705. {
  706. bytes newBlock;
  707. {
  708. UpgradableGuard l(x_working);
  709. {
  710. UpgradeGuard l2(l);
  711. if (!m_working.sealBlock(_header))
  712. return false;
  713. }
  714. DEV_WRITE_GUARDED(x_postSeal)
  715. m_postSeal = m_working;
  716. newBlock = m_working.blockData();
  717. }
  718. // OPTIMISE: very inefficient to not utilise the existing OverlayDB in m_postSeal that contains all trie changes.
  719. return m_bq.import(&newBlock, true) == ImportResult::Success;
  720. }
  721. void Client::rewind(unsigned _n)
  722. {
  723. executeInMainThread([=]() {
  724. bc().rewind(_n);
  725. onChainChanged(ImportRoute());
  726. });
  727. for (unsigned i = 0; i < 10; ++i)
  728. {
  729. u256 n;
  730. DEV_READ_GUARDED(x_working)
  731. n = m_working.info().number();
  732. if (n == _n + 1)
  733. break;
  734. this_thread::sleep_for(std::chrono::milliseconds(50));
  735. }
  736. auto h = m_host.lock();
  737. if (h)
  738. h->reset();
  739. }