Executive.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  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 Executive.cpp
  15. * @author Gav Wood <i@gavwood.com>
  16. * @date 2014
  17. */
  18. #include "Executive.h"
  19. #include <boost/timer.hpp>
  20. #include <json/json.h>
  21. #include <libdevcore/CommonIO.h>
  22. #include <libevm/VMFactory.h>
  23. #include <libevm/VM.h>
  24. #include <libethcore/CommonJS.h>
  25. #include "Interface.h"
  26. #include "State.h"
  27. #include "ExtVM.h"
  28. #include "BlockChain.h"
  29. #include "Block.h"
  30. using namespace std;
  31. using namespace dev;
  32. using namespace dev::eth;
  33. const char* VMTraceChannel::name() { return "EVM"; }
  34. const char* ExecutiveWarnChannel::name() { return WarnChannel::name(); }
  35. StandardTrace::StandardTrace():
  36. m_trace(Json::arrayValue)
  37. {}
  38. bool changesMemory(Instruction _inst)
  39. {
  40. return
  41. _inst == Instruction::MSTORE ||
  42. _inst == Instruction::MSTORE8 ||
  43. _inst == Instruction::MLOAD ||
  44. _inst == Instruction::CREATE ||
  45. _inst == Instruction::CALL ||
  46. _inst == Instruction::CALLCODE ||
  47. _inst == Instruction::SHA3 ||
  48. _inst == Instruction::CALLDATACOPY ||
  49. _inst == Instruction::CODECOPY ||
  50. _inst == Instruction::EXTCODECOPY ||
  51. _inst == Instruction::DELEGATECALL;
  52. }
  53. bool changesStorage(Instruction _inst)
  54. {
  55. return _inst == Instruction::SSTORE;
  56. }
  57. void StandardTrace::operator()(uint64_t _steps, uint64_t PC, Instruction inst, bigint newMemSize, bigint gasCost, bigint gas, VM* voidVM, ExtVMFace const* voidExt)
  58. {
  59. (void)_steps;
  60. ExtVM const& ext = dynamic_cast<ExtVM const&>(*voidExt);
  61. VM& vm = *voidVM;
  62. Json::Value r(Json::objectValue);
  63. Json::Value stack(Json::arrayValue);
  64. if (!m_options.disableStack)
  65. {
  66. for (auto const& i: vm.stack())
  67. stack.append("0x" + toHex(toCompactBigEndian(i, 1)));
  68. r["stack"] = stack;
  69. }
  70. bool newContext = false;
  71. Instruction lastInst = Instruction::STOP;
  72. if (m_lastInst.size() == ext.depth)
  73. {
  74. // starting a new context
  75. assert(m_lastInst.size() == ext.depth);
  76. m_lastInst.push_back(inst);
  77. newContext = true;
  78. }
  79. else if (m_lastInst.size() == ext.depth + 2)
  80. {
  81. m_lastInst.pop_back();
  82. lastInst = m_lastInst.back();
  83. }
  84. else if (m_lastInst.size() == ext.depth + 1)
  85. {
  86. // continuing in previous context
  87. lastInst = m_lastInst.back();
  88. m_lastInst.back() = inst;
  89. }
  90. else
  91. {
  92. cwarn << "GAA!!! Tracing VM and more than one new/deleted stack frame between steps!";
  93. cwarn << "Attmepting naive recovery...";
  94. m_lastInst.resize(ext.depth + 1);
  95. }
  96. Json::Value memJson(Json::arrayValue);
  97. if (!m_options.disableMemory && (changesMemory(lastInst) || newContext))
  98. {
  99. for (unsigned i = 0; i < vm.memory().size(); i += 32)
  100. {
  101. bytesConstRef memRef(vm.memory().data() + i, 32);
  102. memJson.append(toHex(memRef, 2, HexPrefix::DontAdd));
  103. }
  104. r["memory"] = memJson;
  105. }
  106. if (!m_options.disableStorage && (m_options.fullStorage || changesStorage(lastInst) || newContext))
  107. {
  108. Json::Value storage(Json::objectValue);
  109. for (auto const& i: ext.state().storage(ext.myAddress))
  110. storage["0x" + toHex(toCompactBigEndian(i.first, 1))] = "0x" + toHex(toCompactBigEndian(i.second, 1));
  111. r["storage"] = storage;
  112. }
  113. if (m_showMnemonics)
  114. r["op"] = instructionInfo(inst).name;
  115. r["pc"] = toString(PC);
  116. r["gas"] = toString(gas);
  117. r["gasCost"] = toString(gasCost);
  118. if (!!newMemSize)
  119. r["memexpand"] = toString(newMemSize);
  120. m_trace.append(r);
  121. }
  122. string StandardTrace::json(bool _styled) const
  123. {
  124. if (!_styled)
  125. {
  126. Json::StreamWriterBuilder wbuilder;
  127. wbuilder["indentation"] = "";
  128. return Json::writeString(wbuilder, m_trace);
  129. }
  130. else
  131. {
  132. Json::StreamWriterBuilder wbuilder;
  133. wbuilder["indentation"] = "";
  134. wbuilder["commentStyle"] = "All";
  135. return Json::writeString(wbuilder, m_trace);
  136. }
  137. // return _styled ? Json::StyledWriter().write(m_trace) : Json::FastWriter().write(m_trace);
  138. }
  139. Executive::Executive(Block& _s, BlockChain const& _bc, unsigned _level):
  140. m_s(_s.mutableState()),
  141. m_envInfo(_s.info(), _bc.lastHashes(_s.info().parentHash())),
  142. m_depth(_level),
  143. m_sealEngine(*_bc.sealEngine())
  144. {
  145. }
  146. Executive::Executive(Block& _s, LastHashes const& _lh, unsigned _level):
  147. m_s(_s.mutableState()),
  148. m_envInfo(_s.info(), _lh),
  149. m_depth(_level),
  150. m_sealEngine(*_s.sealEngine())
  151. {
  152. }
  153. Executive::Executive(State& _s, Block const& _block, unsigned _txIndex, BlockChain const& _bc, unsigned _level):
  154. m_s(_s = _block.fromPending(_txIndex)),
  155. m_envInfo(_block.info(), _bc.lastHashes(_block.info().parentHash()), _txIndex ? _block.receipt(_txIndex - 1).gasUsed() : 0),
  156. m_depth(_level),
  157. m_sealEngine(*_bc.sealEngine())
  158. {
  159. }
  160. u256 Executive::gasUsed() const
  161. {
  162. return m_t.gas() - m_gas;
  163. }
  164. u256 Executive::gasUsedNoRefunds() const
  165. {
  166. return m_t.gas() - m_gas + m_refunded;
  167. }
  168. void Executive::accrueSubState(SubState& _parentContext)
  169. {
  170. if (m_ext)
  171. _parentContext += m_ext->sub;
  172. }
  173. void Executive::initialize(Transaction const& _transaction)
  174. {
  175. m_t = _transaction;
  176. // Avoid transactions that would take us beyond the block gas limit.
  177. u256 startGasUsed = m_envInfo.gasUsed();
  178. if (startGasUsed + (bigint)m_t.gas() > m_envInfo.gasLimit())
  179. {
  180. clog(ExecutiveWarnChannel) << "Too much gas used in this block: Require <" << (m_envInfo.gasLimit() - startGasUsed) << " Got" << m_t.gas();
  181. m_excepted = TransactionException::BlockGasLimitReached;
  182. BOOST_THROW_EXCEPTION(BlockGasLimitReached() << RequirementError((bigint)(m_envInfo.gasLimit() - startGasUsed), (bigint)m_t.gas()));
  183. }
  184. // Check gas cost is enough.
  185. m_baseGasRequired = m_t.gasRequired(m_sealEngine.evmSchedule(m_envInfo));
  186. if (m_baseGasRequired > m_t.gas())
  187. {
  188. clog(ExecutiveWarnChannel) << "Not enough gas to pay for the transaction: Require >" << m_baseGasRequired << " Got" << m_t.gas();
  189. m_excepted = TransactionException::OutOfGasBase;
  190. BOOST_THROW_EXCEPTION(OutOfGasBase() << RequirementError(m_baseGasRequired, (bigint)m_t.gas()));
  191. }
  192. // Avoid invalid transactions.
  193. u256 nonceReq;
  194. try
  195. {
  196. nonceReq = m_s.getNonce(m_t.sender());
  197. }
  198. catch (...)
  199. {
  200. clog(ExecutiveWarnChannel) << "Invalid Signature";
  201. m_excepted = TransactionException::InvalidSignature;
  202. throw;
  203. }
  204. if (m_t.nonce() != nonceReq)
  205. {
  206. clog(ExecutiveWarnChannel) << "Invalid Nonce: Require" << nonceReq << " Got" << m_t.nonce();
  207. m_excepted = TransactionException::InvalidNonce;
  208. BOOST_THROW_EXCEPTION(InvalidNonce() << RequirementError((bigint)nonceReq, (bigint)m_t.nonce()));
  209. }
  210. // Avoid unaffordable transactions.
  211. m_gasCost = (bigint)m_t.gas() * m_t.gasPrice();
  212. bigint totalCost = m_t.value() + m_gasCost;
  213. if (m_s.balance(m_t.sender()) < totalCost)
  214. {
  215. clog(ExecutiveWarnChannel) << "Not enough cash: Require >" << totalCost << "=" << m_t.gas() << "*" << m_t.gasPrice() << "+" << m_t.value() << " Got" << m_s.balance(m_t.sender()) << "for sender: " << m_t.sender();
  216. m_excepted = TransactionException::NotEnoughCash;
  217. BOOST_THROW_EXCEPTION(NotEnoughCash() << RequirementError(totalCost, (bigint)m_s.balance(m_t.sender())) << errinfo_comment(m_t.sender().abridged()));
  218. }
  219. }
  220. bool Executive::execute()
  221. {
  222. // Entry point for a user-executed transaction.
  223. // Pay...
  224. clog(StateDetail) << "Paying" << formatBalance(u256(m_gasCost)) << "from sender for gas (" << m_t.gas() << "gas at" << formatBalance(m_t.gasPrice()) << ")";
  225. m_s.subBalance(m_t.sender(), m_gasCost);
  226. if (m_t.isCreation())
  227. return create(m_t.sender(), m_t.value(), m_t.gasPrice(), m_t.gas() - (u256)m_baseGasRequired, &m_t.data(), m_t.sender());
  228. else
  229. return call(m_t.receiveAddress(), m_t.sender(), m_t.value(), m_t.gasPrice(), bytesConstRef(&m_t.data()), m_t.gas() - (u256)m_baseGasRequired);
  230. }
  231. bool Executive::call(Address _receiveAddress, Address _senderAddress, u256 _value, u256 _gasPrice, bytesConstRef _data, u256 _gas)
  232. {
  233. CallParameters params{_senderAddress, _receiveAddress, _receiveAddress, _value, _value, _gas, _data, {}, {}};
  234. return call(params, _gasPrice, _senderAddress);
  235. }
  236. bool Executive::call(CallParameters const& _p, u256 const& _gasPrice, Address const& _origin)
  237. {
  238. m_isCreation = false;
  239. // If external transaction.
  240. if (m_t)
  241. // Increment associated nonce for sender.
  242. m_s.incNonce(_p.senderAddress);
  243. if (m_sealEngine.isPrecompiled(_p.codeAddress))
  244. {
  245. bigint g = m_sealEngine.costOfPrecompiled(_p.codeAddress, _p.data);
  246. if (_p.gas < g)
  247. {
  248. m_excepted = TransactionException::OutOfGasBase;
  249. // Bail from exception.
  250. return true; // true actually means "all finished - nothing more to be done regarding go().
  251. }
  252. else
  253. {
  254. m_gas = (u256)(_p.gas - g);
  255. m_sealEngine.executePrecompiled(_p.codeAddress, _p.data, _p.out);
  256. }
  257. }
  258. else
  259. {
  260. m_gas = _p.gas;
  261. if (m_s.addressHasCode(_p.codeAddress))
  262. {
  263. m_outRef = _p.out; // Save ref to expected output buffer to be used in go()
  264. bytes const& c = m_s.code(_p.codeAddress);
  265. h256 codeHash = m_s.codeHash(_p.codeAddress);
  266. m_ext = make_shared<ExtVM>(m_s, m_envInfo, m_sealEngine, _p.receiveAddress, _p.senderAddress, _origin, _p.apparentValue, _gasPrice, _p.data, &c, codeHash, m_depth);
  267. }
  268. }
  269. m_s.transferBalance(_p.senderAddress, _p.receiveAddress, _p.valueTransfer);
  270. return !m_ext;
  271. }
  272. bool Executive::create(Address _sender, u256 _endowment, u256 _gasPrice, u256 _gas, bytesConstRef _init, Address _origin)
  273. {
  274. m_isCreation = true;
  275. u256 nonce = m_s.getNonce(_sender);
  276. m_s.incNonce(_sender);
  277. // We can allow for the reverted state (i.e. that with which m_ext is constructed) to contain the m_newAddress, since
  278. // we delete it explicitly if we decide we need to revert.
  279. m_newAddress = right160(sha3(rlpList(_sender, nonce)));
  280. m_gas = _gas;
  281. // Execute _init.
  282. if (!_init.empty())
  283. m_ext = make_shared<ExtVM>(m_s, m_envInfo, m_sealEngine, m_newAddress, _sender, _origin, _endowment, _gasPrice, bytesConstRef(), _init, sha3(_init), m_depth);
  284. bool incrementNonce = m_envInfo.number() >= m_sealEngine.chainParams().u256Param("EIP158ForkBlock");
  285. m_s.createContract(m_newAddress, incrementNonce);
  286. m_s.transferBalance(_sender, m_newAddress, _endowment);
  287. if (_init.empty())
  288. m_s.setCode(m_newAddress, {});
  289. return !m_ext;
  290. }
  291. OnOpFunc Executive::simpleTrace()
  292. {
  293. return [](uint64_t steps, uint64_t PC, Instruction inst, bigint newMemSize, bigint gasCost, bigint gas, VM* voidVM, ExtVMFace const* voidExt)
  294. {
  295. ExtVM const& ext = *static_cast<ExtVM const*>(voidExt);
  296. VM& vm = *voidVM;
  297. ostringstream o;
  298. o << endl << " STACK" << endl;
  299. for (auto i: vm.stack())
  300. o << (h256)i << endl;
  301. o << " MEMORY" << endl << ((vm.memory().size() > 1000) ? " mem size greater than 1000 bytes " : memDump(vm.memory()));
  302. o << " STORAGE" << endl;
  303. for (auto const& i: ext.state().storage(ext.myAddress))
  304. o << showbase << hex << i.first << ": " << i.second << endl;
  305. dev::LogOutputStream<VMTraceChannel, false>() << o.str();
  306. dev::LogOutputStream<VMTraceChannel, false>() << " < " << dec << ext.depth << " : " << ext.myAddress << " : #" << steps << " : " << hex << setw(4) << setfill('0') << PC << " : " << instructionInfo(inst).name << " : " << dec << gas << " : -" << dec << gasCost << " : " << newMemSize << "x32" << " >";
  307. };
  308. }
  309. bool Executive::go(OnOpFunc const& _onOp)
  310. {
  311. if (m_ext)
  312. {
  313. #if ETH_TIMED_EXECUTIONS
  314. Timer t;
  315. #endif
  316. try
  317. {
  318. // Create VM instance. Force Interpreter if tracing requested.
  319. auto vm = _onOp ? VMFactory::create(VMKind::Interpreter) : VMFactory::create();
  320. if (m_isCreation)
  321. {
  322. auto out = vm->exec(m_gas, *m_ext, _onOp);
  323. if (m_res)
  324. {
  325. m_res->gasForDeposit = m_gas;
  326. m_res->depositSize = out.size();
  327. }
  328. if (out.size() > m_ext->evmSchedule().maxCodeSize)
  329. BOOST_THROW_EXCEPTION(OutOfGas());
  330. else if (out.size() * m_ext->evmSchedule().createDataGas <= m_gas)
  331. {
  332. if (m_res)
  333. m_res->codeDeposit = CodeDeposit::Success;
  334. m_gas -= out.size() * m_ext->evmSchedule().createDataGas;
  335. }
  336. else
  337. {
  338. if (m_ext->evmSchedule().exceptionalFailedCodeDeposit)
  339. BOOST_THROW_EXCEPTION(OutOfGas());
  340. else
  341. {
  342. if (m_res)
  343. m_res->codeDeposit = CodeDeposit::Failed;
  344. out.clear();
  345. }
  346. }
  347. if (m_res)
  348. m_res->output = out; // copy output to execution result
  349. m_s.setCode(m_newAddress, std::move(out));
  350. }
  351. else
  352. {
  353. if (m_res)
  354. {
  355. m_res->output = vm->exec(m_gas, *m_ext, _onOp); // take full output
  356. bytesConstRef{&m_res->output}.copyTo(m_outRef);
  357. }
  358. else
  359. vm->exec(m_gas, *m_ext, m_outRef, _onOp); // take only expected output
  360. }
  361. }
  362. catch (VMException const& _e)
  363. {
  364. clog(StateSafeExceptions) << "Safe VM Exception. " << diagnostic_information(_e);
  365. m_gas = 0;
  366. m_excepted = toTransactionException(_e);
  367. m_ext->revert();
  368. if (m_isCreation)
  369. m_newAddress = Address();
  370. }
  371. catch (Exception const& _e)
  372. {
  373. // TODO: AUDIT: check that this can never reasonably happen. Consider what to do if it does.
  374. cwarn << "Unexpected exception in VM. There may be a bug in this implementation. " << diagnostic_information(_e);
  375. exit(1);
  376. // Another solution would be to reject this transaction, but that also
  377. // has drawbacks. Essentially, the amount of ram has to be increased here.
  378. }
  379. catch (std::exception const& _e)
  380. {
  381. // TODO: AUDIT: check that this can never reasonably happen. Consider what to do if it does.
  382. cwarn << "Unexpected std::exception in VM. Not enough RAM? " << _e.what();
  383. exit(1);
  384. // Another solution would be to reject this transaction, but that also
  385. // has drawbacks. Essentially, the amount of ram has to be increased here.
  386. }
  387. #if ETH_TIMED_EXECUTIONS
  388. cnote << "VM took:" << t.elapsed() << "; gas used: " << (sgas - m_endGas);
  389. #endif
  390. }
  391. return true;
  392. }
  393. void Executive::finalize()
  394. {
  395. // Accumulate refunds for suicides.
  396. if (m_ext)
  397. m_ext->sub.refunds += m_ext->evmSchedule().suicideRefundGas * m_ext->sub.suicides.size();
  398. // SSTORE refunds...
  399. // must be done before the miner gets the fees.
  400. m_refunded = m_ext ? min((m_t.gas() - m_gas) / 2, m_ext->sub.refunds) : 0;
  401. m_gas += m_refunded;
  402. if (m_t)
  403. {
  404. m_s.addBalance(m_t.sender(), m_gas * m_t.gasPrice());
  405. u256 feesEarned = (m_t.gas() - m_gas) * m_t.gasPrice();
  406. m_s.addBalance(m_envInfo.author(), feesEarned);
  407. }
  408. // Suicides...
  409. if (m_ext)
  410. for (auto a: m_ext->sub.suicides)
  411. m_s.kill(a);
  412. // Logs..
  413. if (m_ext)
  414. m_logs = m_ext->sub.logs;
  415. // cwarn << "m_gas" << m_gas << "m_refunded" << m_refunded << "gasUsed()" << gasUsed();
  416. if (m_res) // Collect results
  417. {
  418. m_res->gasUsed = gasUsed();
  419. m_res->excepted = m_excepted; // TODO: m_except is used only in ExtVM::call
  420. m_res->newAddress = m_newAddress;
  421. m_res->gasRefunded = m_ext ? m_ext->sub.refunds : 0;
  422. }
  423. }