ClientBase.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591
  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 ClientBase.cpp
  15. * @author Gav Wood <i@gavwood.com>
  16. * @author Marek Kotewicz <marek@ethdev.com>
  17. * @date 2015
  18. */
  19. #include "ClientBase.h"
  20. #include <algorithm>
  21. #include "BlockChain.h"
  22. #include "Executive.h"
  23. #include "State.h"
  24. using namespace std;
  25. using namespace dev;
  26. using namespace dev::eth;
  27. const char* WatchChannel::name() { return EthBlue "ℹ" EthWhite " "; }
  28. const char* WorkInChannel::name() { return EthOrange "⚒" EthGreen "▬▶"; }
  29. const char* WorkOutChannel::name() { return EthOrange "⚒" EthNavy "◀▬"; }
  30. const char* WorkChannel::name() { return EthOrange "⚒" EthWhite " "; }
  31. namespace dev { namespace eth { const u256 c_maxGasEstimate = 50000000; } }
  32. pair<h256, Address> ClientBase::submitTransaction(TransactionSkeleton const& _t, Secret const& _secret)
  33. {
  34. prepareForTransaction();
  35. TransactionSkeleton ts(_t);
  36. ts.from = toAddress(_secret);
  37. if (_t.nonce == Invalid256)
  38. ts.nonce = max<u256>(postSeal().transactionsFrom(ts.from), m_tq.maxNonce(ts.from));
  39. if (ts.gasPrice == Invalid256)
  40. ts.gasPrice = gasBidPrice();
  41. if (ts.gas == Invalid256)
  42. ts.gas = min<u256>(gasLimitRemaining() / 5, balanceAt(ts.from) / ts.gasPrice);
  43. Transaction t(ts, _secret);
  44. m_tq.import(t.rlp());
  45. return make_pair(t.sha3(), toAddress(ts.from, ts.nonce));
  46. }
  47. // TODO: remove try/catch, allow exceptions
  48. ExecutionResult ClientBase::call(Address const& _from, u256 _value, Address _dest, bytes const& _data, u256 _gas, u256 _gasPrice, BlockNumber _blockNumber, FudgeFactor _ff)
  49. {
  50. ExecutionResult ret;
  51. try
  52. {
  53. Block temp = block(_blockNumber);
  54. u256 nonce = max<u256>(temp.transactionsFrom(_from), m_tq.maxNonce(_from));
  55. u256 gas = _gas == Invalid256 ? gasLimitRemaining() : _gas;
  56. u256 gasPrice = _gasPrice == Invalid256 ? gasBidPrice() : _gasPrice;
  57. Transaction t(_value, gasPrice, gas, _dest, _data, nonce);
  58. t.forceSender(_from);
  59. if (_ff == FudgeFactor::Lenient)
  60. temp.mutableState().addBalance(_from, (u256)(t.gas() * t.gasPrice() + t.value()));
  61. ret = temp.execute(bc().lastHashes(), t, Permanence::Reverted);
  62. }
  63. catch (...)
  64. {
  65. // TODO: Some sort of notification of failure.
  66. }
  67. return ret;
  68. }
  69. ExecutionResult ClientBase::create(Address const& _from, u256 _value, bytes const& _data, u256 _gas, u256 _gasPrice, BlockNumber _blockNumber, FudgeFactor _ff)
  70. {
  71. ExecutionResult ret;
  72. try
  73. {
  74. Block temp = block(_blockNumber);
  75. u256 n = temp.transactionsFrom(_from);
  76. // cdebug << "Nonce at " << toAddress(_secret) << " pre:" << m_preSeal.transactionsFrom(toAddress(_secret)) << " post:" << m_postSeal.transactionsFrom(toAddress(_secret));
  77. Transaction t(_value, _gasPrice, _gas, _data, n);
  78. t.forceSender(_from);
  79. if (_ff == FudgeFactor::Lenient)
  80. temp.mutableState().addBalance(_from, (u256)(t.gas() * t.gasPrice() + t.value()));
  81. ret = temp.execute(bc().lastHashes(), t, Permanence::Reverted);
  82. }
  83. catch (...)
  84. {
  85. // TODO: Some sort of notification of failure.
  86. }
  87. return ret;
  88. }
  89. std::pair<u256, ExecutionResult> ClientBase::estimateGas(Address const& _from, u256 _value, Address _dest, bytes const& _data, u256 _maxGas, u256 _gasPrice, BlockNumber _blockNumber, GasEstimationCallback const& _callback)
  90. {
  91. try
  92. {
  93. u256 upperBound = _maxGas;
  94. if (upperBound == Invalid256 || upperBound > c_maxGasEstimate)
  95. upperBound = c_maxGasEstimate;
  96. u256 lowerBound = (u256)Transaction::gasRequired(!_dest, &_data, EVMSchedule(), 0);
  97. Block bk = block(_blockNumber);
  98. u256 gasPrice = _gasPrice == Invalid256 ? gasBidPrice() : _gasPrice;
  99. ExecutionResult er;
  100. ExecutionResult lastGood;
  101. bool good = false;
  102. while (upperBound != lowerBound)
  103. {
  104. u256 mid = (lowerBound + upperBound) / 2;
  105. u256 n = bk.transactionsFrom(_from);
  106. Transaction t;
  107. if (_dest)
  108. t = Transaction(_value, gasPrice, mid, _dest, _data, n);
  109. else
  110. t = Transaction(_value, gasPrice, mid, _data, n);
  111. t.forceSender(_from);
  112. EnvInfo env(bk.info(), bc().lastHashes(), 0);
  113. env.setGasLimit(mid.convert_to<int64_t>());
  114. State tempState(bk.state());
  115. tempState.addBalance(_from, (u256)(t.gas() * t.gasPrice() + t.value()));
  116. er = tempState.execute(env, *bc().sealEngine(), t, Permanence::Reverted).first;
  117. if (er.excepted == TransactionException::OutOfGas ||
  118. er.excepted == TransactionException::OutOfGasBase ||
  119. er.excepted == TransactionException::OutOfGasIntrinsic ||
  120. er.codeDeposit == CodeDeposit::Failed ||
  121. er.excepted == TransactionException::BadJumpDestination)
  122. lowerBound = lowerBound == mid ? upperBound : mid;
  123. else
  124. {
  125. lastGood = er;
  126. upperBound = upperBound == mid ? lowerBound : mid;
  127. good = true;
  128. }
  129. if (_callback)
  130. _callback(GasEstimationProgress { lowerBound, upperBound });
  131. }
  132. if (_callback)
  133. _callback(GasEstimationProgress { lowerBound, upperBound });
  134. return make_pair(upperBound, good ? lastGood : er);
  135. }
  136. catch (...)
  137. {
  138. // TODO: Some sort of notification of failure.
  139. return make_pair(u256(), ExecutionResult());
  140. }
  141. }
  142. ImportResult ClientBase::injectBlock(bytes const& _block)
  143. {
  144. return bc().attemptImport(_block, preSeal().db()).first;
  145. }
  146. u256 ClientBase::balanceAt(Address _a, BlockNumber _block) const
  147. {
  148. return block(_block).balance(_a);
  149. }
  150. u256 ClientBase::countAt(Address _a, BlockNumber _block) const
  151. {
  152. return block(_block).transactionsFrom(_a);
  153. }
  154. u256 ClientBase::stateAt(Address _a, u256 _l, BlockNumber _block) const
  155. {
  156. return block(_block).storage(_a, _l);
  157. }
  158. h256 ClientBase::stateRootAt(Address _a, BlockNumber _block) const
  159. {
  160. return block(_block).storageRoot(_a);
  161. }
  162. bytes ClientBase::codeAt(Address _a, BlockNumber _block) const
  163. {
  164. return block(_block).code(_a);
  165. }
  166. h256 ClientBase::codeHashAt(Address _a, BlockNumber _block) const
  167. {
  168. return block(_block).codeHash(_a);
  169. }
  170. map<u256, u256> ClientBase::storageAt(Address _a, BlockNumber _block) const
  171. {
  172. return block(_block).storage(_a);
  173. }
  174. // TODO: remove try/catch, allow exceptions
  175. LocalisedLogEntries ClientBase::logs(unsigned _watchId) const
  176. {
  177. LogFilter f;
  178. try
  179. {
  180. Guard l(x_filtersWatches);
  181. f = m_filters.at(m_watches.at(_watchId).id).filter;
  182. }
  183. catch (...)
  184. {
  185. return LocalisedLogEntries();
  186. }
  187. return logs(f);
  188. }
  189. LocalisedLogEntries ClientBase::logs(LogFilter const& _f) const
  190. {
  191. LocalisedLogEntries ret;
  192. unsigned begin = min(bc().number() + 1, (unsigned)numberFromHash(_f.latest()));
  193. unsigned end = min(bc().number(), min(begin, (unsigned)numberFromHash(_f.earliest())));
  194. // Handle pending transactions differently as they're not on the block chain.
  195. if (begin > bc().number())
  196. {
  197. Block temp = postSeal();
  198. for (unsigned i = 0; i < temp.pending().size(); ++i)
  199. {
  200. // Might have a transaction that contains a matching log.
  201. TransactionReceipt const& tr = temp.receipt(i);
  202. LogEntries le = _f.matches(tr);
  203. for (unsigned j = 0; j < le.size(); ++j)
  204. ret.insert(ret.begin(), LocalisedLogEntry(le[j]));
  205. }
  206. begin = bc().number();
  207. }
  208. // Handle reverted blocks
  209. // There are not so many, so let's iterate over them
  210. h256s blocks;
  211. h256 ancestor;
  212. unsigned ancestorIndex;
  213. tie(blocks, ancestor, ancestorIndex) = bc().treeRoute(_f.earliest(), _f.latest(), false);
  214. for (size_t i = 0; i < ancestorIndex; i++)
  215. prependLogsFromBlock(_f, blocks[i], BlockPolarity::Dead, ret);
  216. // cause end is our earliest block, let's compare it with our ancestor
  217. // if ancestor is smaller let's move our end to it
  218. // example:
  219. //
  220. // 3b -> 2b -> 1b
  221. // -> g
  222. // 3a -> 2a -> 1a
  223. //
  224. // if earliest is at 2a and latest is a 3b, coverting them to numbers
  225. // will give us pair (2, 3)
  226. // and we want to get all logs from 1 (ancestor + 1) to 3
  227. // so we have to move 2a to g + 1
  228. end = min(end, (unsigned)numberFromHash(ancestor) + 1);
  229. // Handle blocks from main chain
  230. set<unsigned> matchingBlocks;
  231. if (!_f.isRangeFilter())
  232. for (auto const& i: _f.bloomPossibilities())
  233. for (auto u: bc().withBlockBloom(i, end, begin))
  234. matchingBlocks.insert(u);
  235. else
  236. // if it is a range filter, we want to get all logs from all blocks in given range
  237. for (unsigned i = end; i <= begin; i++)
  238. matchingBlocks.insert(i);
  239. for (auto n: matchingBlocks)
  240. prependLogsFromBlock(_f, bc().numberHash(n), BlockPolarity::Live, ret);
  241. reverse(ret.begin(), ret.end());
  242. return ret;
  243. }
  244. void ClientBase::prependLogsFromBlock(LogFilter const& _f, h256 const& _blockHash, BlockPolarity _polarity, LocalisedLogEntries& io_logs) const
  245. {
  246. auto receipts = bc().receipts(_blockHash).receipts;
  247. for (size_t i = 0; i < receipts.size(); i++)
  248. {
  249. TransactionReceipt receipt = receipts[i];
  250. auto th = transaction(_blockHash, i).sha3();
  251. LogEntries le = _f.matches(receipt);
  252. for (unsigned j = 0; j < le.size(); ++j)
  253. io_logs.insert(io_logs.begin(), LocalisedLogEntry(le[j], _blockHash, (BlockNumber)bc().number(_blockHash), th, i, 0, _polarity));
  254. }
  255. }
  256. unsigned ClientBase::installWatch(LogFilter const& _f, Reaping _r)
  257. {
  258. h256 h = _f.sha3();
  259. {
  260. Guard l(x_filtersWatches);
  261. if (!m_filters.count(h))
  262. {
  263. cwatch << "FFF" << _f << h;
  264. m_filters.insert(make_pair(h, _f));
  265. }
  266. }
  267. return installWatch(h, _r);
  268. }
  269. unsigned ClientBase::installWatch(h256 _h, Reaping _r)
  270. {
  271. unsigned ret;
  272. {
  273. Guard l(x_filtersWatches);
  274. ret = m_watches.size() ? m_watches.rbegin()->first + 1 : 0;
  275. m_watches[ret] = ClientWatch(_h, _r);
  276. cwatch << "+++" << ret << _h;
  277. }
  278. #if INITIAL_STATE_AS_CHANGES
  279. auto ch = logs(ret);
  280. if (ch.empty())
  281. ch.push_back(InitialChange);
  282. {
  283. Guard l(x_filtersWatches);
  284. swap(m_watches[ret].changes, ch);
  285. }
  286. #endif
  287. return ret;
  288. }
  289. bool ClientBase::uninstallWatch(unsigned _i)
  290. {
  291. cwatch << "XXX" << _i;
  292. Guard l(x_filtersWatches);
  293. auto it = m_watches.find(_i);
  294. if (it == m_watches.end())
  295. return false;
  296. auto id = it->second.id;
  297. m_watches.erase(it);
  298. auto fit = m_filters.find(id);
  299. if (fit != m_filters.end())
  300. if (!--fit->second.refCount)
  301. {
  302. cwatch << "*X*" << fit->first << ":" << fit->second.filter;
  303. m_filters.erase(fit);
  304. }
  305. return true;
  306. }
  307. LocalisedLogEntries ClientBase::peekWatch(unsigned _watchId) const
  308. {
  309. Guard l(x_filtersWatches);
  310. // cwatch << "peekWatch" << _watchId;
  311. auto& w = m_watches.at(_watchId);
  312. // cwatch << "lastPoll updated to " << chrono::duration_cast<chrono::seconds>(chrono::system_clock::now().time_since_epoch()).count();
  313. if (w.lastPoll != chrono::system_clock::time_point::max())
  314. w.lastPoll = chrono::system_clock::now();
  315. return w.changes;
  316. }
  317. LocalisedLogEntries ClientBase::checkWatch(unsigned _watchId)
  318. {
  319. Guard l(x_filtersWatches);
  320. LocalisedLogEntries ret;
  321. // cwatch << "checkWatch" << _watchId;
  322. auto& w = m_watches.at(_watchId);
  323. // cwatch << "lastPoll updated to " << chrono::duration_cast<chrono::seconds>(chrono::system_clock::now().time_since_epoch()).count();
  324. std::swap(ret, w.changes);
  325. if (w.lastPoll != chrono::system_clock::time_point::max())
  326. w.lastPoll = chrono::system_clock::now();
  327. return ret;
  328. }
  329. BlockHeader ClientBase::blockInfo(h256 _hash) const
  330. {
  331. if (_hash == PendingBlockHash)
  332. return preSeal().info();
  333. return BlockHeader(bc().block(_hash));
  334. }
  335. BlockDetails ClientBase::blockDetails(h256 _hash) const
  336. {
  337. return bc().details(_hash);
  338. }
  339. Transaction ClientBase::transaction(h256 _transactionHash) const
  340. {
  341. return Transaction(bc().transaction(_transactionHash), CheckTransaction::Cheap);
  342. }
  343. LocalisedTransaction ClientBase::localisedTransaction(h256 const& _transactionHash) const
  344. {
  345. std::pair<h256, unsigned> tl = bc().transactionLocation(_transactionHash);
  346. return localisedTransaction(tl.first, tl.second);
  347. }
  348. Transaction ClientBase::transaction(h256 _blockHash, unsigned _i) const
  349. {
  350. auto bl = bc().block(_blockHash);
  351. RLP b(bl);
  352. if (_i < b[1].itemCount())
  353. return Transaction(b[1][_i].data(), CheckTransaction::Cheap);
  354. else
  355. return Transaction();
  356. }
  357. LocalisedTransaction ClientBase::localisedTransaction(h256 const& _blockHash, unsigned _i) const
  358. {
  359. Transaction t = Transaction(bc().transaction(_blockHash, _i), CheckTransaction::Cheap);
  360. return LocalisedTransaction(t, _blockHash, _i, numberFromHash(_blockHash));
  361. }
  362. TransactionReceipt ClientBase::transactionReceipt(h256 const& _transactionHash) const
  363. {
  364. return bc().transactionReceipt(_transactionHash);
  365. }
  366. LocalisedTransactionReceipt ClientBase::localisedTransactionReceipt(h256 const& _transactionHash) const
  367. {
  368. std::pair<h256, unsigned> tl = bc().transactionLocation(_transactionHash);
  369. Transaction t = Transaction(bc().transaction(tl.first, tl.second), CheckTransaction::Cheap);
  370. TransactionReceipt tr = bc().transactionReceipt(tl.first, tl.second);
  371. return LocalisedTransactionReceipt(
  372. tr,
  373. t.sha3(),
  374. tl.first,
  375. numberFromHash(tl.first),
  376. tl.second,
  377. toAddress(t.from(), t.nonce()));
  378. }
  379. pair<h256, unsigned> ClientBase::transactionLocation(h256 const& _transactionHash) const
  380. {
  381. return bc().transactionLocation(_transactionHash);
  382. }
  383. Transactions ClientBase::transactions(h256 _blockHash) const
  384. {
  385. auto bl = bc().block(_blockHash);
  386. RLP b(bl);
  387. Transactions res;
  388. for (unsigned i = 0; i < b[1].itemCount(); i++)
  389. res.emplace_back(b[1][i].data(), CheckTransaction::Cheap);
  390. return res;
  391. }
  392. TransactionHashes ClientBase::transactionHashes(h256 _blockHash) const
  393. {
  394. return bc().transactionHashes(_blockHash);
  395. }
  396. BlockHeader ClientBase::uncle(h256 _blockHash, unsigned _i) const
  397. {
  398. auto bl = bc().block(_blockHash);
  399. RLP b(bl);
  400. if (_i < b[2].itemCount())
  401. return BlockHeader(b[2][_i].data(), HeaderData);
  402. else
  403. return BlockHeader();
  404. }
  405. UncleHashes ClientBase::uncleHashes(h256 _blockHash) const
  406. {
  407. return bc().uncleHashes(_blockHash);
  408. }
  409. unsigned ClientBase::transactionCount(h256 _blockHash) const
  410. {
  411. auto bl = bc().block(_blockHash);
  412. RLP b(bl);
  413. return b[1].itemCount();
  414. }
  415. unsigned ClientBase::uncleCount(h256 _blockHash) const
  416. {
  417. auto bl = bc().block(_blockHash);
  418. RLP b(bl);
  419. return b[2].itemCount();
  420. }
  421. unsigned ClientBase::number() const
  422. {
  423. return bc().number();
  424. }
  425. Transactions ClientBase::pending() const
  426. {
  427. return postSeal().pending();
  428. }
  429. h256s ClientBase::pendingHashes() const
  430. {
  431. return h256s() + postSeal().pendingHashes();
  432. }
  433. BlockHeader ClientBase::pendingInfo() const
  434. {
  435. return postSeal().info();
  436. }
  437. BlockDetails ClientBase::pendingDetails() const
  438. {
  439. auto pm = postSeal().info();
  440. auto li = Interface::blockDetails(LatestBlock);
  441. return BlockDetails((unsigned)pm.number(), li.totalDifficulty + pm.difficulty(), pm.parentHash(), h256s{});
  442. }
  443. Addresses ClientBase::addresses(BlockNumber _block) const
  444. {
  445. Addresses ret;
  446. for (auto const& i: block(_block).addresses())
  447. ret.push_back(i.first);
  448. return ret;
  449. }
  450. u256 ClientBase::gasLimitRemaining() const
  451. {
  452. return postSeal().gasLimitRemaining();
  453. }
  454. Address ClientBase::author() const
  455. {
  456. return preSeal().author();
  457. }
  458. h256 ClientBase::hashFromNumber(BlockNumber _number) const
  459. {
  460. if (_number == PendingBlock)
  461. return h256();
  462. if (_number == LatestBlock)
  463. return bc().currentHash();
  464. return bc().numberHash(_number);
  465. }
  466. BlockNumber ClientBase::numberFromHash(h256 _blockHash) const
  467. {
  468. if (_blockHash == PendingBlockHash)
  469. return bc().number() + 1;
  470. else if (_blockHash == LatestBlockHash)
  471. return bc().number();
  472. else if (_blockHash == EarliestBlockHash)
  473. return 0;
  474. return bc().number(_blockHash);
  475. }
  476. int ClientBase::compareBlockHashes(h256 _h1, h256 _h2) const
  477. {
  478. BlockNumber n1 = numberFromHash(_h1);
  479. BlockNumber n2 = numberFromHash(_h2);
  480. if (n1 > n2)
  481. return 1;
  482. else if (n1 == n2)
  483. return 0;
  484. return -1;
  485. }
  486. bool ClientBase::isKnown(h256 const& _hash) const
  487. {
  488. return _hash == PendingBlockHash ||
  489. _hash == LatestBlockHash ||
  490. _hash == EarliestBlockHash ||
  491. bc().isKnown(_hash);
  492. }
  493. bool ClientBase::isKnown(BlockNumber _block) const
  494. {
  495. return _block == PendingBlock ||
  496. _block == LatestBlock ||
  497. bc().numberHash(_block) != h256();
  498. }
  499. bool ClientBase::isKnownTransaction(h256 const& _transactionHash) const
  500. {
  501. return bc().isKnownTransaction(_transactionHash);
  502. }
  503. bool ClientBase::isKnownTransaction(h256 const& _blockHash, unsigned _i) const
  504. {
  505. return isKnown(_blockHash) && block(_blockHash).pending().size() > _i;
  506. }
  507. Block ClientBase::block(BlockNumber _h) const
  508. {
  509. if (_h == PendingBlock)
  510. return postSeal();
  511. else if (_h == LatestBlock)
  512. return preSeal();
  513. return block(bc().numberHash(_h));
  514. }