TestHelper.cpp 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333
  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 TestHelper.cpp
  15. * @author Marko Simovic <markobarko@gmail.com>
  16. * @date 2014
  17. */
  18. #include "TestHelper.h"
  19. #include <thread>
  20. #include <chrono>
  21. #include <fstream>
  22. #if !defined(_WIN32)
  23. #include <stdio.h>
  24. #endif
  25. #include <boost/algorithm/string/trim.hpp>
  26. #include <libethashseal/EthashAux.h>
  27. #include <libethashseal/Ethash.h>
  28. #include <libethashseal/GenesisInfo.h>
  29. #include <libethcore/BasicAuthority.h>
  30. #include <libethereum/Client.h>
  31. #include <libevm/ExtVMFace.h>
  32. #include <libevm/VMFactory.h>
  33. #include "Stats.h"
  34. using namespace std;
  35. using namespace dev::eth;
  36. namespace dev
  37. {
  38. namespace eth
  39. {
  40. void printHelp()
  41. {
  42. cout << "Usage: " << std::endl;
  43. cout << std::left;
  44. cout << std::endl << "Setting test suite" << std::endl;
  45. cout << setw(30) << "-t <TestSuite>" << setw(25) << "Execute test operations" << std::endl;
  46. cout << setw(30) << "-t <TestSuite>/<TestCase>" << std::endl;
  47. cout << std::endl << "Debugging" << std::endl;
  48. cout << setw(30) << "--singletest <TestName>" << setw(25) << "Run on a single test" << std::endl;
  49. cout << setw(30) << "--singletest <TestFile> <TestName>" << std::endl;
  50. cout << setw(30) << "--verbosity <level>" << setw(25) << "Set logs verbosity. 0 - silent, 1 - only errors, 2 - informative, >2 - detailed" << std::endl;
  51. cout << setw(30) << "--vm <interpreter|jit|smart>" << setw(25) << "Set VM type for VMTests suite" << std::endl;
  52. cout << setw(30) << "--vmtrace" << setw(25) << "Enable VM trace for the test. (Require build with VMTRACE=1)" << std::endl;
  53. cout << setw(30) << "--stats <OutFile>" << setw(25) << "Output debug stats to the file" << std::endl;
  54. cout << setw(30) << "--filltest <FileData>" << setw(25) << "Try fill tests from the given json stream" << std::endl;
  55. cout << setw(30) << "--checktest <FileData>" << setw(25) << "Try run tests from the given json stream" << std::endl;
  56. cout << std::endl << "Additional Tests" << std::endl;
  57. cout << setw(30) << "--performance" << setw(25) << "Enable perfomance tests" << std::endl;
  58. cout << setw(30) << "--quadratic" << setw(25) << "Enable quadratic complexity tests" << std::endl;
  59. cout << setw(30) << "--memory" << setw(25) << "Enable memory consuming tests" << std::endl;
  60. cout << setw(30) << "--inputLimits" << setw(25) << "Enable inputLimits tests" << std::endl;
  61. cout << setw(30) << "--bigdata" << setw(25) << "Enable bigdata tests" << std::endl;
  62. cout << setw(30) << "--wallet" << setw(25) << "Enable wallet tests" << std::endl;
  63. cout << setw(30) << "--all" << setw(25) << "Enable all tests" << std::endl;
  64. cout << std::endl << "Test Creation" << std::endl;
  65. cout << setw(30) << "--filltests" << setw(25) << "Run test fillers" << std::endl;
  66. cout << setw(30) << "--checkstate" << setw(25) << "Enable expect section state checks" << std::endl;
  67. cout << setw(30) << "--sealengine <Frontier|Homestead>" << setw(25) << "Set internal seal engine" << std::endl;
  68. cout << setw(30) << "--createRandomTest" << setw(25) << "Create random test and output it to the console" << std::endl;
  69. //cout << setw(30) << "--fulloutput" << setw(25) << "Disable address compression in the output field" << std::endl;
  70. cout << setw(30) << "--help" << setw(25) << "Display list of command arguments" << std::endl;
  71. }
  72. string netIdToString(eth::Network _netId)
  73. {
  74. switch(_netId)
  75. {
  76. case eth::Network::FrontierTest: return "Frontier";
  77. case eth::Network::HomesteadTest: return "Homestead";
  78. case eth::Network::EIP150Test: return "EIP150";
  79. case eth::Network::EIP158Test: return "EIP158";
  80. default: return "other";
  81. }
  82. return "unknown";
  83. }
  84. void mine(Client& c, int numBlocks)
  85. {
  86. auto startBlock = c.blockChain().details().number;
  87. c.startSealing();
  88. while(c.blockChain().details().number < startBlock + numBlocks)
  89. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  90. c.stopSealing();
  91. }
  92. void connectClients(Client& c1, Client& c2)
  93. {
  94. (void)c1;
  95. (void)c2;
  96. // TODO: Move to WebThree. eth::Client no longer handles networking.
  97. #if 0
  98. short c1Port = 20000;
  99. short c2Port = 21000;
  100. c1.startNetwork(c1Port);
  101. c2.startNetwork(c2Port);
  102. c2.connect("127.0.0.1", c1Port);
  103. #endif
  104. }
  105. void mine(Block& s, BlockChain const& _bc, SealEngineFace* _sealer)
  106. {
  107. s.commitToSeal(_bc, s.info().extraData());
  108. Notified<bytes> sealed;
  109. _sealer->onSealGenerated([&](bytes const& sealedHeader){ sealed = sealedHeader; });
  110. _sealer->generateSeal(s.info());
  111. sealed.waitNot({});
  112. _sealer->onSealGenerated([](bytes const&){});
  113. s.sealBlock(sealed);
  114. }
  115. void mine(BlockHeader& _bi, SealEngineFace* _sealer, bool _verify)
  116. {
  117. Notified<bytes> sealed;
  118. _sealer->onSealGenerated([&](bytes const& sealedHeader){ sealed = sealedHeader; });
  119. _sealer->generateSeal(_bi);
  120. sealed.waitNot({});
  121. _sealer->onSealGenerated([](bytes const&){});
  122. _bi = BlockHeader(sealed, HeaderData);
  123. // cdebug << "Block mined" << Ethash::boundary(_bi).hex() << Ethash::nonce(_bi) << _bi.hash(WithoutSeal).hex();
  124. if (_verify) //sometimes it is needed to mine incorrect blockheaders for testing
  125. _sealer->verify(JustSeal, _bi);
  126. }
  127. }
  128. namespace test
  129. {
  130. struct ValueTooLarge: virtual Exception {};
  131. struct MissingFields : virtual Exception {};
  132. bigint const c_max256plus1 = bigint(1) << 256;
  133. ImportTest::ImportTest(json_spirit::mObject& _o, bool isFiller, testType testTemplate):
  134. m_statePre(0, OverlayDB(), eth::BaseState::Empty),
  135. m_statePost(0, OverlayDB(), eth::BaseState::Empty),
  136. m_testObject(_o),
  137. m_testType(testTemplate)
  138. {
  139. if (testTemplate == testType::StateTests || m_testType == testType::GeneralStateTest)
  140. {
  141. importEnv(_o["env"].get_obj());
  142. importTransaction(_o["transaction"].get_obj());
  143. importState(_o["pre"].get_obj(), m_statePre);
  144. if (!isFiller && m_testType == testType::StateTests)
  145. {
  146. if (_o.count("post"))
  147. importState(_o["post"].get_obj(), m_statePost);
  148. else
  149. importState(_o["postState"].get_obj(), m_statePost);
  150. m_logsExpected = importLog(_o["logs"].get_array());
  151. }
  152. }
  153. }
  154. bytes ImportTest::executeTest()
  155. {
  156. if (m_testType == testType::StateTests)
  157. {
  158. eth::Network network = eth::Network::FrontierTest;
  159. if (m_envInfo.number() >= dev::test::c_testHomesteadBlock)
  160. network = eth::Network::HomesteadTest;
  161. std::pair<eth::State, ImportTest::execOutput> out = executeTransaction(network, m_envInfo, m_statePre, m_transaction);
  162. m_statePost = out.first;
  163. m_logs = out.second.second.log();
  164. return out.second.first.output;
  165. }
  166. else if (m_testType == testType::GeneralStateTest)
  167. {
  168. vector<eth::Network> networks;
  169. if (!Options::get().singleTestNet.empty())
  170. {
  171. if (netIdToString(eth::Network::FrontierTest) == Options::get().singleTestNet)
  172. networks.push_back(eth::Network::FrontierTest);
  173. else if (netIdToString(eth::Network::HomesteadTest) == Options::get().singleTestNet)
  174. networks.push_back(eth::Network::HomesteadTest);
  175. else if (netIdToString(eth::Network::EIP150Test) == Options::get().singleTestNet)
  176. networks.push_back(eth::Network::EIP150Test);
  177. else if (netIdToString(eth::Network::EIP158Test) == Options::get().singleTestNet)
  178. networks.push_back(eth::Network::EIP158Test);
  179. }
  180. else
  181. {
  182. networks.push_back(eth::Network::FrontierTest);
  183. networks.push_back(eth::Network::HomesteadTest);
  184. networks.push_back(eth::Network::EIP150Test);
  185. networks.push_back(eth::Network::EIP158Test);
  186. }
  187. vector<transactionToExecute> transactionResults;
  188. for (size_t j = 0; j < networks.size(); j++)
  189. {
  190. for (size_t i = 0; i < m_transactions.size(); i++)
  191. {
  192. eth::Network network = networks[j];
  193. std::pair<eth::State, ImportTest::execOutput> out = executeTransaction(network, m_envInfo, m_statePre, m_transactions[i].transaction);
  194. m_transactions[i].postState = out.first;
  195. m_transactions[i].netId = network;
  196. transactionResults.push_back(m_transactions[i]);
  197. }
  198. }
  199. m_transactions.clear();
  200. m_transactions = transactionResults;
  201. return bytes();
  202. }
  203. BOOST_ERROR("Error when executing test ImportTest::executeTest()");
  204. return bytes();
  205. }
  206. std::pair<eth::State, ImportTest::execOutput> ImportTest::executeTransaction(eth::Network const _sealEngineNetwork, eth::EnvInfo const& _env, eth::State const& _preState, eth::Transaction const& _tr)
  207. {
  208. eth::State initialState = _preState;
  209. try
  210. {
  211. unique_ptr<SealEngineFace> se(ChainParams(genesisInfo(_sealEngineNetwork)).createSealEngine());
  212. bool removeEmptyAccounts = m_envInfo.number() >= se->chainParams().u256Param("EIP158ForkBlock");
  213. ImportTest::execOutput execOut = initialState.execute(_env, *se.get(), _tr);
  214. initialState.commit(removeEmptyAccounts ? State::CommitBehaviour::RemoveEmptyAccounts : State::CommitBehaviour::KeepEmptyAccounts);
  215. return std::pair<eth::State, ImportTest::execOutput>(initialState, execOut);
  216. }
  217. catch (Exception const& _e)
  218. {
  219. cnote << "Exception: " << diagnostic_information(_e);
  220. }
  221. catch (std::exception const& _e)
  222. {
  223. cnote << "state execution exception: " << _e.what();
  224. }
  225. initialState.commit(State::CommitBehaviour::KeepEmptyAccounts);
  226. ExecutionResult emptyRes;
  227. LogEntries emptyLogs;
  228. ImportTest::execOutput execOut = make_pair(emptyRes, TransactionReceipt(h256(), u256(), emptyLogs));
  229. return std::pair<eth::State, ImportTest::execOutput>(initialState, execOut);
  230. }
  231. json_spirit::mObject& ImportTest::makeAllFieldsHex(json_spirit::mObject& _o)
  232. {
  233. static const set<string> hashes {"bloom" , "coinbase", "hash", "mixHash", "parentHash", "receiptTrie",
  234. "stateRoot", "transactionsTrie", "uncleHash", "currentCoinbase",
  235. "previousHash", "to", "address", "caller", "origin", "secretKey", "data"};
  236. for (auto& i: _o)
  237. {
  238. std::string key = i.first;
  239. if (hashes.count(key))
  240. continue;
  241. std::string str;
  242. json_spirit::mValue value = i.second;
  243. if (value.type() == json_spirit::int_type)
  244. str = toString(value.get_int());
  245. else if (value.type() == json_spirit::str_type)
  246. str = value.get_str();
  247. else continue;
  248. _o[key] = (str.substr(0, 2) == "0x") ? str : toCompactHex(toInt(str), HexPrefix::Add, 1);
  249. }
  250. return _o;
  251. }
  252. void ImportTest::importEnv(json_spirit::mObject& _o)
  253. {
  254. BOOST_REQUIRE(_o.count("currentGasLimit") > 0);
  255. BOOST_REQUIRE(_o.count("currentDifficulty") > 0);
  256. BOOST_REQUIRE(_o.count("currentNumber") > 0);
  257. BOOST_REQUIRE(_o.count("currentTimestamp") > 0);
  258. BOOST_REQUIRE(_o.count("currentCoinbase") > 0);
  259. auto gasLimit = toInt(_o["currentGasLimit"]);
  260. BOOST_REQUIRE(gasLimit <= std::numeric_limits<int64_t>::max());
  261. m_envInfo.setGasLimit(gasLimit.convert_to<int64_t>());
  262. m_envInfo.setDifficulty(toInt(_o["currentDifficulty"]));
  263. m_envInfo.setNumber(toInt(_o["currentNumber"]));
  264. m_envInfo.setTimestamp(toInt(_o["currentTimestamp"]));
  265. m_envInfo.setAuthor(Address(_o["currentCoinbase"].get_str()));
  266. m_envInfo.setLastHashes( lastHashes( m_envInfo.number() ) );
  267. }
  268. // import state from not fully declared json_spirit::mObject, writing to _stateOptionsMap which fields were defined in json
  269. void replaceLLLinState(json_spirit::mObject& _o)
  270. {
  271. for (auto& account: _o.count("alloc") ? _o["alloc"].get_obj() : _o.count("accounts") ? _o["accounts"].get_obj() : _o)
  272. {
  273. auto obj = account.second.get_obj();
  274. if (obj.count("code") && obj["code"].type() == json_spirit::str_type)
  275. {
  276. string code = obj["code"].get_str();
  277. obj["code"] = compileLLL(code);
  278. }
  279. account.second = obj;
  280. }
  281. }
  282. void ImportTest::importState(json_spirit::mObject const& _o, State& _state, AccountMaskMap& o_mask)
  283. {
  284. //Compile LLL code of the test Fillers using external call to lllc
  285. json_spirit::mObject o = _o;
  286. replaceLLLinState(o);
  287. std::string jsondata = json_spirit::write_string((json_spirit::mValue)o, false);
  288. _state.populateFrom(jsonToAccountMap(jsondata, 0, &o_mask));
  289. }
  290. void ImportTest::importState(json_spirit::mObject const& _o, State& _state)
  291. {
  292. AccountMaskMap mask;
  293. importState(_o, _state, mask);
  294. for (auto const& i: mask)
  295. //check that every parameter was declared in state object
  296. if (!i.second.allSet())
  297. BOOST_THROW_EXCEPTION(MissingFields() << errinfo_comment("Import State: Missing state fields!"));
  298. }
  299. void ImportTest::importTransaction (json_spirit::mObject const& _o, eth::Transaction& o_tr)
  300. {
  301. if (_o.count("secretKey") > 0)
  302. {
  303. BOOST_REQUIRE(_o.count("nonce") > 0);
  304. BOOST_REQUIRE(_o.count("gasPrice") > 0);
  305. BOOST_REQUIRE(_o.count("gasLimit") > 0);
  306. BOOST_REQUIRE(_o.count("to") > 0);
  307. BOOST_REQUIRE(_o.count("value") > 0);
  308. BOOST_REQUIRE(_o.count("data") > 0);
  309. if (bigint(_o.at("nonce").get_str()) >= c_max256plus1)
  310. BOOST_THROW_EXCEPTION(ValueTooLarge() << errinfo_comment("Transaction 'nonce' is equal or greater than 2**256") );
  311. if (bigint(_o.at("gasPrice").get_str()) >= c_max256plus1)
  312. BOOST_THROW_EXCEPTION(ValueTooLarge() << errinfo_comment("Transaction 'gasPrice' is equal or greater than 2**256") );
  313. if (bigint(_o.at("gasLimit").get_str()) >= c_max256plus1)
  314. BOOST_THROW_EXCEPTION(ValueTooLarge() << errinfo_comment("Transaction 'gasLimit' is equal or greater than 2**256") );
  315. if (bigint(_o.at("value").get_str()) >= c_max256plus1)
  316. BOOST_THROW_EXCEPTION(ValueTooLarge() << errinfo_comment("Transaction 'value' is equal or greater than 2**256") );
  317. o_tr = _o.at("to").get_str().empty() ?
  318. Transaction(toInt(_o.at("value")), toInt(_o.at("gasPrice")), toInt(_o.at("gasLimit")), importData(_o), toInt(_o.at("nonce")), Secret(_o.at("secretKey").get_str())) :
  319. Transaction(toInt(_o.at("value")), toInt(_o.at("gasPrice")), toInt(_o.at("gasLimit")), Address(_o.at("to").get_str()), importData(_o), toInt(_o.at("nonce")), Secret(_o.at("secretKey").get_str()));
  320. }
  321. else
  322. {
  323. BOOST_REQUIRE(_o.count("nonce"));
  324. BOOST_REQUIRE(_o.count("gasPrice"));
  325. BOOST_REQUIRE(_o.count("gasLimit"));
  326. BOOST_REQUIRE(_o.count("to"));
  327. BOOST_REQUIRE(_o.count("value"));
  328. BOOST_REQUIRE(_o.count("data"));
  329. BOOST_REQUIRE(_o.count("v"));
  330. BOOST_REQUIRE(_o.count("r"));
  331. BOOST_REQUIRE(_o.count("s"));
  332. RLPStream transactionRLPStream = createRLPStreamFromTransactionFields(_o);
  333. RLP transactionRLP(transactionRLPStream.out());
  334. try
  335. {
  336. o_tr = Transaction(transactionRLP.data(), CheckTransaction::Everything);
  337. }
  338. catch (InvalidSignature)
  339. {
  340. // create unsigned transaction
  341. o_tr = _o.at("to").get_str().empty() ?
  342. Transaction(toInt(_o.at("value")), toInt(_o.at("gasPrice")), toInt(_o.at("gasLimit")), importData(_o), toInt(_o.at("nonce"))) :
  343. Transaction(toInt(_o.at("value")), toInt(_o.at("gasPrice")), toInt(_o.at("gasLimit")), Address(_o.at("to").get_str()), importData(_o), toInt(_o.at("nonce")));
  344. }
  345. catch (Exception& _e)
  346. {
  347. cnote << "invalid transaction" << boost::diagnostic_information(_e);
  348. }
  349. }
  350. }
  351. void ImportTest::importTransaction(json_spirit::mObject const& o_tr)
  352. {
  353. if (m_testType == testType::StateTests) //Import a single transaction
  354. importTransaction(o_tr, m_transaction);
  355. else if (m_testType == testType::GeneralStateTest) //Parse extended transaction
  356. {
  357. BOOST_REQUIRE(o_tr.count("gasLimit") > 0);
  358. size_t dataVectorSize = o_tr.at("data").get_array().size();
  359. size_t gasVectorSize = o_tr.at("gasLimit").get_array().size();
  360. size_t valueVectorSize = o_tr.at("value").get_array().size();
  361. for (size_t d = 0; d < dataVectorSize; d++)
  362. for (size_t g = 0; g < gasVectorSize; g++)
  363. for (size_t v = 0; v < valueVectorSize; v++)
  364. {
  365. json_spirit::mValue gas = o_tr.at("gasLimit").get_array().at(g);
  366. json_spirit::mValue value = o_tr.at("value").get_array().at(v);
  367. json_spirit::mValue data = o_tr.at("data").get_array().at(d);
  368. json_spirit::mObject o_tr_tmp = o_tr;
  369. o_tr_tmp["data"] = data;
  370. o_tr_tmp["gasLimit"] = gas;
  371. o_tr_tmp["value"] = value;
  372. importTransaction(o_tr_tmp, m_transaction);
  373. transactionToExecute execData(d, g, v, m_transaction);
  374. m_transactions.push_back(execData);
  375. }
  376. }
  377. }
  378. int ImportTest::compareStates(State const& _stateExpect, State const& _statePost, AccountMaskMap const _expectedStateOptions, WhenError _throw)
  379. {
  380. bool wasError = false;
  381. #define CHECK(a,b) \
  382. { \
  383. if (_throw == WhenError::Throw) \
  384. { \
  385. BOOST_CHECK_MESSAGE(a, b); \
  386. if (!a) \
  387. return 1; \
  388. } \
  389. else \
  390. { \
  391. BOOST_WARN_MESSAGE(a,b); \
  392. if (!a) \
  393. wasError = true; \
  394. } \
  395. }
  396. for (auto const& a: _stateExpect.addresses())
  397. {
  398. AccountMask addressOptions(true);
  399. if(_expectedStateOptions.size())
  400. {
  401. try
  402. {
  403. addressOptions = _expectedStateOptions.at(a.first);
  404. }
  405. catch(std::out_of_range const&)
  406. {
  407. BOOST_ERROR(TestOutputHelper::testName() + "expectedStateOptions map does not match expectedState in checkExpectedState!");
  408. break;
  409. }
  410. }
  411. if (addressOptions.shouldExist())
  412. {
  413. CHECK(_statePost.addressInUse(a.first), TestOutputHelper::testName() + "Compare States: " << a.first << " missing expected address!");
  414. }
  415. else
  416. {
  417. CHECK(!_statePost.addressInUse(a.first), TestOutputHelper::testName() + "Compare States: " << a.first << " address not expected to exist!");
  418. }
  419. if (_statePost.addressInUse(a.first))
  420. {
  421. if (addressOptions.hasBalance())
  422. CHECK((_stateExpect.balance(a.first) == _statePost.balance(a.first)),
  423. TestOutputHelper::testName() + "Check State: " << a.first << ": incorrect balance " << _statePost.balance(a.first) << ", expected " << _stateExpect.balance(a.first));
  424. if (addressOptions.hasNonce())
  425. CHECK((_stateExpect.getNonce(a.first) == _statePost.getNonce(a.first)),
  426. TestOutputHelper::testName() + "Check State: " << a.first << ": incorrect nonce " << _statePost.getNonce(a.first) << ", expected " << _stateExpect.getNonce(a.first));
  427. if (addressOptions.hasStorage())
  428. {
  429. map<u256, u256> stateStorage = _statePost.storage(a.first);
  430. for (auto const& s: _stateExpect.storage(a.first))
  431. CHECK((stateStorage[s.first] == s.second),
  432. TestOutputHelper::testName() + "Check State: " << a.first << ": incorrect storage [" << s.first << "] = " << toHex(stateStorage[s.first]) << ", expected [" << s.first << "] = " << toHex(s.second));
  433. //Check for unexpected storage values
  434. stateStorage = _stateExpect.storage(a.first);
  435. for (auto const& s: _statePost.storage(a.first))
  436. CHECK((stateStorage[s.first] == s.second),
  437. TestOutputHelper::testName() + "Check State: " << a.first << ": incorrect storage [" << s.first << "] = " << toHex(s.second) << ", expected [" << s.first << "] = " << toHex(stateStorage[s.first]));
  438. }
  439. if (addressOptions.hasCode())
  440. CHECK((_stateExpect.code(a.first) == _statePost.code(a.first)),
  441. TestOutputHelper::testName() + "Check State: " << a.first << ": incorrect code '" << toHex(_statePost.code(a.first)) << "', expected '" << toHex(_stateExpect.code(a.first)) << "'");
  442. }
  443. }
  444. return wasError;
  445. }
  446. void parseJsonStrValueIntoVector(json_spirit::mValue const& _json, vector<string>& _out)
  447. {
  448. if (_json.type() == json_spirit::array_type)
  449. {
  450. for (auto const& val: _json.get_array())
  451. _out.push_back(val.get_str());
  452. }
  453. else
  454. _out.push_back(_json.get_str());
  455. }
  456. void parseJsonIntValueIntoVector(json_spirit::mValue const& _json, vector<int>& _out)
  457. {
  458. if (_json.type() == json_spirit::array_type)
  459. {
  460. for (auto const& val: _json.get_array())
  461. _out.push_back(val.get_int());
  462. }
  463. else
  464. _out.push_back(_json.get_int());
  465. }
  466. template<class T>
  467. bool inArray(vector<T> const& _array, const T _val)
  468. {
  469. for (size_t i = 0; i < _array.size(); i++)
  470. if (_array[i] == _val)
  471. return true;
  472. return false;
  473. }
  474. void ImportTest::checkGeneralTestSection(json_spirit::mObject const& _expects, vector<size_t>& _errorTransactions, string const& _network) const
  475. {
  476. vector<int> d;
  477. vector<int> g;
  478. vector<int> v;
  479. vector<string> network;
  480. if (_network.empty())
  481. parseJsonStrValueIntoVector(_expects.at("network"), network);
  482. else
  483. network.push_back(_network);
  484. BOOST_CHECK_MESSAGE(network.size() > 0, TestOutputHelper::testName() + "Network array not set!");
  485. vector<string> allowednetworks = {netIdToString(eth::Network::FrontierTest), netIdToString(eth::Network::HomesteadTest),
  486. netIdToString(eth::Network::EIP150Test), netIdToString(eth::Network::EIP158Test), "ALL"};
  487. for(size_t i=0; i<network.size(); i++)
  488. BOOST_CHECK_MESSAGE(inArray(allowednetworks, network.at(i)), TestOutputHelper::testName() + "Specified Network not found: " + network.at(i));
  489. if (_expects.count("indexes"))
  490. {
  491. json_spirit::mObject const& indexes = _expects.at("indexes").get_obj();
  492. parseJsonIntValueIntoVector(indexes.at("data"), d);
  493. parseJsonIntValueIntoVector(indexes.at("gas"), g);
  494. parseJsonIntValueIntoVector(indexes.at("value"), v);
  495. BOOST_CHECK_MESSAGE(d.size() > 0 && g.size() > 0 && v.size() > 0, TestOutputHelper::testName() + "Indexes arrays not set!");
  496. }
  497. else
  498. BOOST_ERROR(TestOutputHelper::testName() + "indexes section not set!");
  499. bool foundResults = false;
  500. for(size_t i = 0; i < m_transactions.size(); i++)
  501. {
  502. transactionToExecute t = m_transactions[i];
  503. if (inArray(network, netIdToString(t.netId)) || network[0] == "ALL")
  504. if ((inArray(d, t.dataInd) || d[0] == -1) && (inArray(g, t.gasInd) || g[0] == -1) && (inArray(v, t.valInd) || v[0] == -1))
  505. {
  506. string trInfo = netIdToString(t.netId) + " data: " + toString(t.dataInd) + " gas: " + toString(t.gasInd) + " val: " + toString(t.valInd);
  507. if (_expects.count("result"))
  508. {
  509. State postState = t.postState;
  510. eth::AccountMaskMap stateMap;
  511. State expectState(0, OverlayDB(), eth::BaseState::Empty);
  512. importState(_expects.at("result").get_obj(), expectState, stateMap);
  513. int errcode = compareStates(expectState, postState, stateMap, Options::get().checkState ? WhenError::Throw : WhenError::DontThrow);
  514. if (errcode > 0)
  515. {
  516. cerr << trInfo << std::endl;
  517. _errorTransactions.push_back(i);
  518. }
  519. }
  520. else if (_expects.count("hash"))
  521. BOOST_CHECK_MESSAGE(_expects.at("hash").get_str() == toHex(t.postState.rootHash().asBytes()), TestOutputHelper::testName() + "Expected another postState hash! " + trInfo);
  522. else
  523. BOOST_ERROR(TestOutputHelper::testName() + "Expect section or postState missing some fields!");
  524. foundResults = true;
  525. //if a single transaction check then stop once found
  526. if (network[0] != "ALL" && d[0] != -1 && g[0] != -1 && v[0] != -1)
  527. if (d.size() == 1 && g.size() == 1 && v.size() == 1)
  528. break;
  529. }
  530. }
  531. BOOST_CHECK_MESSAGE(foundResults, TestOutputHelper::testName() + "Expect results was not found in test execution!");
  532. }
  533. int ImportTest::exportTest(bytes const& _output)
  534. {
  535. int err = 0;
  536. if (m_testType == testType::GeneralStateTest)
  537. {
  538. vector<size_t> stateIndexesToPrint;
  539. if (m_testObject.count("expect") > 0)
  540. {
  541. for (auto const& exp: m_testObject["expect"].get_array())
  542. checkGeneralTestSection(exp.get_obj(), stateIndexesToPrint);
  543. m_testObject.erase(m_testObject.find("expect"));
  544. }
  545. size_t k = 0;
  546. std::map<string, json_spirit::mArray> postState;
  547. for(size_t i = 0; i < m_transactions.size(); i++)
  548. {
  549. json_spirit::mObject obj;
  550. json_spirit::mObject obj2;
  551. obj["data"] = m_transactions[i].dataInd;
  552. obj["gas"] = m_transactions[i].gasInd;
  553. obj["value"] = m_transactions[i].valInd;
  554. obj2["indexes"] = obj;
  555. obj2["hash"] = toHex(m_transactions[i].postState.rootHash().asBytes());
  556. if (stateIndexesToPrint.size())
  557. if (i == stateIndexesToPrint[k] && Options::get().checkState)
  558. {
  559. obj2["postState"] = fillJsonWithState(m_transactions[i].postState);
  560. k++;
  561. }
  562. postState[netIdToString(m_transactions[i].netId)].push_back(obj2);
  563. }
  564. json_spirit::mObject obj;
  565. for(std::map<string, json_spirit::mArray>::iterator it = postState.begin(); it != postState.end(); ++it)
  566. obj[it->first] = it->second;
  567. m_testObject["post"] = obj;
  568. }
  569. else
  570. {
  571. // export output
  572. m_testObject["out"] = (_output.size() > 4096 && !Options::get().fulloutput) ? "#" + toString(_output.size()) : toHex(_output, 2, HexPrefix::Add);
  573. // compare expected output with post output
  574. if (m_testObject.count("expectOut") > 0)
  575. {
  576. std::string warning = "Check State: Error! Unexpected output: " + m_testObject["out"].get_str() + " Expected: " + m_testObject["expectOut"].get_str();
  577. if (Options::get().checkState)
  578. {
  579. bool statement = (m_testObject["out"].get_str() == m_testObject["expectOut"].get_str());
  580. BOOST_CHECK_MESSAGE(statement, warning);
  581. if (!statement)
  582. err = 1;
  583. }
  584. else
  585. BOOST_WARN_MESSAGE(m_testObject["out"].get_str() == m_testObject["expectOut"].get_str(), warning);
  586. m_testObject.erase(m_testObject.find("expectOut"));
  587. }
  588. // export logs
  589. m_testObject["logs"] = exportLog(m_logs);
  590. // compare expected state with post state
  591. if (m_testObject.count("expect") > 0)
  592. {
  593. eth::AccountMaskMap stateMap;
  594. State expectState(0, OverlayDB(), eth::BaseState::Empty);
  595. importState(m_testObject["expect"].get_obj(), expectState, stateMap);
  596. compareStates(expectState, m_statePost, stateMap, Options::get().checkState ? WhenError::Throw : WhenError::DontThrow);
  597. m_testObject.erase(m_testObject.find("expect"));
  598. }
  599. // export post state
  600. m_testObject["post"] = fillJsonWithState(m_statePost);
  601. m_testObject["postStateRoot"] = toHex(m_statePost.rootHash().asBytes());
  602. }
  603. // export pre state
  604. m_testObject["pre"] = fillJsonWithState(m_statePre);
  605. m_testObject["env"] = makeAllFieldsHex(m_testObject["env"].get_obj());
  606. m_testObject["transaction"] = makeAllFieldsHex(m_testObject["transaction"].get_obj());
  607. return err;
  608. }
  609. json_spirit::mObject fillJsonWithTransaction(Transaction const& _txn)
  610. {
  611. json_spirit::mObject txObject;
  612. txObject["nonce"] = toCompactHex(_txn.nonce(), HexPrefix::Add, 1);
  613. txObject["data"] = toHex(_txn.data(), 2, HexPrefix::Add);
  614. txObject["gasLimit"] = toCompactHex(_txn.gas(), HexPrefix::Add, 1);
  615. txObject["gasPrice"] = toCompactHex(_txn.gasPrice(), HexPrefix::Add, 1);
  616. txObject["r"] = toCompactHex(_txn.signature().r, HexPrefix::Add, 1);
  617. txObject["s"] = toCompactHex(_txn.signature().s, HexPrefix::Add, 1);
  618. txObject["v"] = toCompactHex(_txn.signature().v + 27, HexPrefix::Add, 1);
  619. txObject["to"] = _txn.isCreation() ? "" : toString(_txn.receiveAddress());
  620. txObject["value"] = toCompactHex(_txn.value(), HexPrefix::Add, 1);
  621. return txObject;
  622. }
  623. json_spirit::mObject fillJsonWithState(State const& _state)
  624. {
  625. json_spirit::mObject oState;
  626. for (auto const& a: _state.addresses())
  627. {
  628. json_spirit::mObject o;
  629. o["balance"] = toCompactHex(_state.balance(a.first), HexPrefix::Add, 1);
  630. o["nonce"] = toCompactHex(_state.getNonce(a.first), HexPrefix::Add, 1);
  631. {
  632. json_spirit::mObject store;
  633. for (auto const& s: _state.storage(a.first))
  634. store[toCompactHex(s.first, HexPrefix::Add, 1)] = toCompactHex(s.second, HexPrefix::Add, 1);
  635. o["storage"] = store;
  636. }
  637. o["code"] = toHex(_state.code(a.first), 2, HexPrefix::Add);
  638. oState[toString(a.first)] = o;
  639. }
  640. return oState;
  641. }
  642. json_spirit::mArray exportLog(eth::LogEntries _logs)
  643. {
  644. json_spirit::mArray ret;
  645. if (_logs.size() == 0) return ret;
  646. for (LogEntry const& l: _logs)
  647. {
  648. json_spirit::mObject o;
  649. o["address"] = toString(l.address);
  650. json_spirit::mArray topics;
  651. for (auto const& t: l.topics)
  652. topics.push_back(toString(t));
  653. o["topics"] = topics;
  654. o["data"] = toHex(l.data, 2, HexPrefix::Add);
  655. o["bloom"] = toString(l.bloom());
  656. ret.push_back(o);
  657. }
  658. return ret;
  659. }
  660. u256 toInt(json_spirit::mValue const& _v)
  661. {
  662. switch (_v.type())
  663. {
  664. case json_spirit::str_type: return u256(_v.get_str());
  665. case json_spirit::int_type: return (u256)_v.get_uint64();
  666. case json_spirit::bool_type: return (u256)(uint64_t)_v.get_bool();
  667. case json_spirit::real_type: return (u256)(uint64_t)_v.get_real();
  668. default: cwarn << "Bad type for scalar: " << _v.type();
  669. }
  670. return 0;
  671. }
  672. byte toByte(json_spirit::mValue const& _v)
  673. {
  674. switch (_v.type())
  675. {
  676. case json_spirit::str_type: return (byte)stoi(_v.get_str());
  677. case json_spirit::int_type: return (byte)_v.get_uint64();
  678. case json_spirit::bool_type: return (byte)_v.get_bool();
  679. case json_spirit::real_type: return (byte)_v.get_real();
  680. default: cwarn << "Bad type for scalar: " << _v.type();
  681. }
  682. return 0;
  683. }
  684. bytes importByteArray(std::string const& _str)
  685. {
  686. return fromHex(_str.substr(0, 2) == "0x" ? _str.substr(2) : _str, WhenError::Throw);
  687. }
  688. bytes importData(json_spirit::mObject const& _o)
  689. {
  690. bytes data;
  691. if (_o.at("data").type() == json_spirit::str_type)
  692. data = importByteArray(_o.at("data").get_str());
  693. else
  694. for (auto const& j: _o.at("data").get_array())
  695. data.push_back(toByte(j));
  696. return data;
  697. }
  698. string compileLLL(string const& _code)
  699. {
  700. if (_code == "")
  701. return "0x";
  702. if (_code.substr(0,2) == "0x" && _code.size() >= 2)
  703. return _code;
  704. #if defined(_WIN32)
  705. BOOST_ERROR("LLL compilation only supported on posix systems.");
  706. return "";
  707. #else
  708. char input[1024];
  709. boost::filesystem::path path(boost::filesystem::temp_directory_path() / boost::filesystem::unique_path());
  710. string cmd = string("lllc ") + path.string();
  711. writeFile(path.string(), _code);
  712. FILE *fp = popen(cmd.c_str(), "r");
  713. if (fp == NULL)
  714. BOOST_ERROR("Failed to run lllc");
  715. if (fgets(input, sizeof(input) - 1, fp) == NULL)
  716. BOOST_ERROR("Reading empty file for lllc");
  717. pclose(fp);
  718. boost::filesystem::remove(path);
  719. string result(input);
  720. result = "0x" + boost::trim_copy(result);
  721. return result;
  722. #endif
  723. }
  724. bytes importCode(json_spirit::mObject& _o)
  725. {
  726. bytes code;
  727. if (_o["code"].type() == json_spirit::str_type)
  728. if (_o["code"].get_str().find("0x") != 0)
  729. code = fromHex(compileLLL(_o["code"].get_str()));
  730. else
  731. code = fromHex(_o["code"].get_str().substr(2));
  732. else if (_o["code"].type() == json_spirit::array_type)
  733. {
  734. code.clear();
  735. for (auto const& j: _o["code"].get_array())
  736. code.push_back(toByte(j));
  737. }
  738. return code;
  739. }
  740. LogEntries importLog(json_spirit::mArray& _a)
  741. {
  742. LogEntries logEntries;
  743. for (auto const& l: _a)
  744. {
  745. json_spirit::mObject o = l.get_obj();
  746. BOOST_REQUIRE(o.count("address") > 0);
  747. BOOST_REQUIRE(o.count("topics") > 0);
  748. BOOST_REQUIRE(o.count("data") > 0);
  749. BOOST_REQUIRE(o.count("bloom") > 0);
  750. LogEntry log;
  751. log.address = Address(o["address"].get_str());
  752. for (auto const& t: o["topics"].get_array())
  753. log.topics.push_back(h256(t.get_str()));
  754. log.data = importData(o);
  755. logEntries.push_back(log);
  756. }
  757. return logEntries;
  758. }
  759. void checkOutput(bytes const& _output, json_spirit::mObject& _o)
  760. {
  761. int j = 0;
  762. if (_o["out"].get_str().find("#") == 0)
  763. BOOST_CHECK((u256)_output.size() == toInt(_o["out"].get_str().substr(1)));
  764. else if (_o["out"].type() == json_spirit::array_type)
  765. for (auto const& d: _o["out"].get_array())
  766. {
  767. BOOST_CHECK_MESSAGE(_output[j] == toInt(d), "Output byte [" << j << "] different!");
  768. ++j;
  769. }
  770. else if (_o["out"].get_str().find("0x") == 0)
  771. BOOST_CHECK(_output == fromHex(_o["out"].get_str().substr(2)));
  772. else
  773. BOOST_CHECK(_output == fromHex(_o["out"].get_str()));
  774. }
  775. void checkStorage(map<u256, u256> _expectedStore, map<u256, u256> _resultStore, Address _expectedAddr)
  776. {
  777. _expectedAddr = _expectedAddr; //unsed parametr when macro
  778. for (auto&& expectedStorePair : _expectedStore)
  779. {
  780. auto& expectedStoreKey = expectedStorePair.first;
  781. auto resultStoreIt = _resultStore.find(expectedStoreKey);
  782. if (resultStoreIt == _resultStore.end())
  783. BOOST_ERROR(_expectedAddr << ": missing store key " << expectedStoreKey);
  784. else
  785. {
  786. auto& expectedStoreValue = expectedStorePair.second;
  787. auto& resultStoreValue = resultStoreIt->second;
  788. BOOST_CHECK_MESSAGE(expectedStoreValue == resultStoreValue, _expectedAddr << ": store[" << expectedStoreKey << "] = " << resultStoreValue << ", expected " << expectedStoreValue);
  789. }
  790. }
  791. BOOST_CHECK_EQUAL(_resultStore.size(), _expectedStore.size());
  792. for (auto&& resultStorePair: _resultStore)
  793. {
  794. if (!_expectedStore.count(resultStorePair.first))
  795. BOOST_ERROR(_expectedAddr << ": unexpected store key " << resultStorePair.first);
  796. }
  797. }
  798. void checkLog(LogEntries _resultLogs, LogEntries _expectedLogs)
  799. {
  800. BOOST_REQUIRE_EQUAL(_resultLogs.size(), _expectedLogs.size());
  801. for (size_t i = 0; i < _resultLogs.size(); ++i)
  802. {
  803. BOOST_CHECK_EQUAL(_resultLogs[i].address, _expectedLogs[i].address);
  804. BOOST_CHECK_EQUAL(_resultLogs[i].topics, _expectedLogs[i].topics);
  805. BOOST_CHECK(_resultLogs[i].data == _expectedLogs[i].data);
  806. }
  807. }
  808. void checkCallCreates(eth::Transactions _resultCallCreates, eth::Transactions _expectedCallCreates)
  809. {
  810. BOOST_REQUIRE_EQUAL(_resultCallCreates.size(), _expectedCallCreates.size());
  811. for (size_t i = 0; i < _resultCallCreates.size(); ++i)
  812. {
  813. BOOST_CHECK(_resultCallCreates[i].data() == _expectedCallCreates[i].data());
  814. BOOST_CHECK(_resultCallCreates[i].receiveAddress() == _expectedCallCreates[i].receiveAddress());
  815. BOOST_CHECK(_resultCallCreates[i].gas() == _expectedCallCreates[i].gas());
  816. BOOST_CHECK(_resultCallCreates[i].value() == _expectedCallCreates[i].value());
  817. }
  818. }
  819. void userDefinedTest(std::function<void(json_spirit::mValue&, bool)> doTests)
  820. {
  821. if (!Options::get().singleTest)
  822. return;
  823. if (Options::get().singleTestFile.empty() || Options::get().singleTestName.empty())
  824. {
  825. cnote << "Missing user test specification\nUsage: testeth --singletest <filename> <testname>\n";
  826. return;
  827. }
  828. auto& filename = Options::get().singleTestFile;
  829. auto& testname = Options::get().singleTestName;
  830. if (g_logVerbosity != -1)
  831. VerbosityHolder sentinel(12);
  832. try
  833. {
  834. cnote << "Testing user defined test: " << filename;
  835. json_spirit::mValue v;
  836. string s = contentsString(filename);
  837. BOOST_REQUIRE_MESSAGE(s.length() > 0, "Contents of " + filename + " is empty. ");
  838. json_spirit::read_string(s, v);
  839. json_spirit::mObject oSingleTest;
  840. json_spirit::mObject::const_iterator pos = v.get_obj().find(testname);
  841. if (pos == v.get_obj().end())
  842. {
  843. cnote << "Could not find test: " << testname << " in " << filename << "\n";
  844. return;
  845. }
  846. else
  847. oSingleTest[pos->first] = pos->second;
  848. json_spirit::mValue v_singleTest(oSingleTest);
  849. doTests(v_singleTest, test::Options::get().fillTests);
  850. }
  851. catch (Exception const& _e)
  852. {
  853. BOOST_ERROR("Failed Test with Exception: " << diagnostic_information(_e));
  854. }
  855. catch (std::exception const& _e)
  856. {
  857. BOOST_ERROR("Failed Test with Exception: " << _e.what());
  858. }
  859. }
  860. void executeTests(const string& _name, const string& _testPathAppendix, const string& _fillerPathAppendix, std::function<void(json_spirit::mValue&, bool)> doTests, bool _addFillerSuffix)
  861. {
  862. string testPath = getTestPath() + _testPathAppendix;
  863. string testFillerPath = getTestPath() + "/src/" + _fillerPathAppendix;
  864. if (Options::get().stats)
  865. Listener::registerListener(Stats::get());
  866. string name = _name;
  867. if (_name.rfind("Filler.json") != std::string::npos)
  868. name = _name.substr(0, _name.rfind("Filler.json"));
  869. if (Options::get().fillTests)
  870. {
  871. try
  872. {
  873. cnote << "Populating tests...";
  874. json_spirit::mValue v;
  875. boost::filesystem::path p(__FILE__);
  876. string nameEnding = _addFillerSuffix ? "Filler.json" : ".json";
  877. string testfilename = testFillerPath + "/" + name + nameEnding;
  878. string s = asString(dev::contents(testfilename));
  879. BOOST_REQUIRE_MESSAGE(s.length() > 0, "Contents of " + testfilename + " is empty.");
  880. json_spirit::read_string(s, v);
  881. doTests(v, true);
  882. writeFile(testPath + "/" + name + ".json", asBytes(json_spirit::write_string(v, true)));
  883. }
  884. catch (Exception const& _e)
  885. {
  886. BOOST_ERROR(TestOutputHelper::testName() + "Failed filling test with Exception: " << diagnostic_information(_e));
  887. }
  888. catch (std::exception const& _e)
  889. {
  890. BOOST_ERROR(TestOutputHelper::testName() + "Failed filling test with Exception: " << _e.what());
  891. }
  892. }
  893. try
  894. {
  895. cnote << "TEST " << name << ":";
  896. json_spirit::mValue v;
  897. string s = asString(dev::contents(testPath + "/" + name + ".json"));
  898. BOOST_REQUIRE_MESSAGE(s.length() > 0, "Contents of " + testPath + "/" + name + ".json is empty. Have you cloned the 'tests' repo branch develop and set ETHEREUM_TEST_PATH to its path?");
  899. json_spirit::read_string(s, v);
  900. Listener::notifySuiteStarted(name);
  901. doTests(v, false);
  902. }
  903. catch (Exception const& _e)
  904. {
  905. BOOST_ERROR(TestOutputHelper::testName() + "Failed test with Exception: " << diagnostic_information(_e));
  906. }
  907. catch (std::exception const& _e)
  908. {
  909. BOOST_ERROR(TestOutputHelper::testName() + "Failed test with Exception: " << _e.what());
  910. }
  911. }
  912. void copyFile(std::string const& _source, std::string const& _destination)
  913. {
  914. std::ifstream src(_source, std::ios::binary);
  915. std::ofstream dst(_destination, std::ios::binary);
  916. dst << src.rdbuf();
  917. }
  918. RLPStream createRLPStreamFromTransactionFields(json_spirit::mObject const& _tObj)
  919. {
  920. //Construct Rlp of the given transaction
  921. RLPStream rlpStream;
  922. rlpStream.appendList(_tObj.size());
  923. if (_tObj.count("nonce"))
  924. rlpStream << bigint(_tObj.at("nonce").get_str());
  925. if (_tObj.count("gasPrice"))
  926. rlpStream << bigint(_tObj.at("gasPrice").get_str());
  927. if (_tObj.count("gasLimit"))
  928. rlpStream << bigint(_tObj.at("gasLimit").get_str());
  929. if (_tObj.count("to"))
  930. {
  931. if (_tObj.at("to").get_str().empty())
  932. rlpStream << "";
  933. else
  934. rlpStream << importByteArray(_tObj.at("to").get_str());
  935. }
  936. if (_tObj.count("value"))
  937. rlpStream << bigint(_tObj.at("value").get_str());
  938. if (_tObj.count("data"))
  939. rlpStream << importData(_tObj);
  940. if (_tObj.count("v"))
  941. rlpStream << bigint(_tObj.at("v").get_str());
  942. if (_tObj.count("r"))
  943. rlpStream << bigint(_tObj.at("r").get_str());
  944. if (_tObj.count("s"))
  945. rlpStream << bigint(_tObj.at("s").get_str());
  946. if (_tObj.count("extrafield"))
  947. rlpStream << bigint(_tObj.at("extrafield").get_str());
  948. return rlpStream;
  949. }
  950. Options::Options(int argc, char** argv)
  951. {
  952. for (auto i = 0; i < argc; ++i)
  953. {
  954. auto arg = std::string{argv[i]};
  955. if (arg == "--help")
  956. {
  957. printHelp();
  958. exit(0);
  959. }
  960. else
  961. if (arg == "--vm" && i + 1 < argc)
  962. {
  963. string vmKind = argv[++i];
  964. if (vmKind == "interpreter")
  965. VMFactory::setKind(VMKind::Interpreter);
  966. else if (vmKind == "jit")
  967. VMFactory::setKind(VMKind::JIT);
  968. else if (vmKind == "smart")
  969. VMFactory::setKind(VMKind::Smart);
  970. else
  971. cerr << "Unknown VM kind: " << vmKind << endl;
  972. }
  973. else if (arg == "--jit") // TODO: Remove deprecated option "--jit"
  974. VMFactory::setKind(VMKind::JIT);
  975. else if (arg == "--vmtrace")
  976. {
  977. vmtrace = true;
  978. g_logVerbosity = 13;
  979. }
  980. else if (arg == "--filltests")
  981. fillTests = true;
  982. else if (arg == "--stats" && i + 1 < argc)
  983. {
  984. stats = true;
  985. statsOutFile = argv[i + 1];
  986. }
  987. else if (arg == "--performance")
  988. performance = true;
  989. else if (arg == "--quadratic")
  990. quadratic = true;
  991. else if (arg == "--memory")
  992. memory = true;
  993. else if (arg == "--inputlimits")
  994. inputLimits = true;
  995. else if (arg == "--bigdata")
  996. bigData = true;
  997. else if (arg == "--checkstate")
  998. checkState = true;
  999. else if (arg == "--wallet")
  1000. wallet = true;
  1001. else if (arg == "--all")
  1002. {
  1003. performance = true;
  1004. quadratic = true;
  1005. memory = true;
  1006. inputLimits = true;
  1007. bigData = true;
  1008. wallet = true;
  1009. }
  1010. else if (arg == "--singletest" && i + 1 < argc)
  1011. {
  1012. singleTest = true;
  1013. auto name1 = std::string{argv[i + 1]};
  1014. if (i + 2 < argc) // two params
  1015. {
  1016. auto name2 = std::string{argv[i + 2]};
  1017. if (name2[0] == '-') // not param, another option
  1018. singleTestName = std::move(name1);
  1019. else
  1020. {
  1021. singleTestFile = std::move(name1);
  1022. singleTestName = std::move(name2);
  1023. }
  1024. }
  1025. else
  1026. singleTestName = std::move(name1);
  1027. }
  1028. else if (arg == "--singlenet" && i + 1 < argc)
  1029. singleTestNet = std::string{argv[i + 1]};
  1030. else if (arg == "--fulloutput")
  1031. fulloutput = true;
  1032. else if (arg == "--sealengine")
  1033. {
  1034. if (std::string{argv[i + 1]} == "Frontier")
  1035. sealEngineNetwork = eth::Network::FrontierTest;
  1036. else if (std::string{argv[i + 1]} == "Homestead")
  1037. sealEngineNetwork = eth::Network::HomesteadTest;
  1038. else
  1039. sealEngineNetwork = eth::Network::Test;
  1040. ++i;
  1041. }
  1042. else if (arg == "--verbosity" && i + 1 < argc)
  1043. {
  1044. static std::ostringstream strCout; //static string to redirect logs to
  1045. std::string indentLevel = std::string{argv[i + 1]};
  1046. if (indentLevel == "0")
  1047. {
  1048. logVerbosity = Verbosity::None;
  1049. std::cout.rdbuf(strCout.rdbuf());
  1050. std::cerr.rdbuf(strCout.rdbuf());
  1051. }
  1052. else if (indentLevel == "1")
  1053. logVerbosity = Verbosity::NiceReport;
  1054. else
  1055. logVerbosity = Verbosity::Full;
  1056. int indentLevelInt = atoi(argv[i + 1]);
  1057. if (indentLevelInt > g_logVerbosity)
  1058. g_logVerbosity = indentLevelInt;
  1059. }
  1060. else if (arg == "--createRandomTest")
  1061. createRandomTest = true;
  1062. else if (arg == "-t" && i + 1 < argc)
  1063. rCurrentTestSuite = std::string{argv[i + 1]};
  1064. else if (arg == "--checktest" || arg == "--filltest")
  1065. {
  1066. //read all line to the end
  1067. for (int j = i+1; j < argc; ++j)
  1068. rCheckTest += argv[j];
  1069. break;
  1070. }
  1071. else if (arg == "--nonetwork")
  1072. nonetwork = true;
  1073. }
  1074. //Default option
  1075. if (logVerbosity == Verbosity::NiceReport)
  1076. g_logVerbosity = -1; //disable cnote but leave cerr and cout
  1077. }
  1078. Options const& Options::get(int argc, char** argv)
  1079. {
  1080. static Options instance(argc, argv);
  1081. return instance;
  1082. }
  1083. LastHashes lastHashes(u256 _currentBlockNumber)
  1084. {
  1085. LastHashes ret;
  1086. for (u256 i = 1; i <= 256 && i <= _currentBlockNumber; ++i)
  1087. ret.push_back(sha3(toString(_currentBlockNumber - i)));
  1088. return ret;
  1089. }
  1090. dev::eth::BlockHeader constructHeader(
  1091. h256 const& _parentHash,
  1092. h256 const& _sha3Uncles,
  1093. Address const& _author,
  1094. h256 const& _stateRoot,
  1095. h256 const& _transactionsRoot,
  1096. h256 const& _receiptsRoot,
  1097. dev::eth::LogBloom const& _logBloom,
  1098. u256 const& _difficulty,
  1099. u256 const& _number,
  1100. u256 const& _gasLimit,
  1101. u256 const& _gasUsed,
  1102. u256 const& _timestamp,
  1103. bytes const& _extraData)
  1104. {
  1105. RLPStream rlpStream;
  1106. rlpStream.appendList(15);
  1107. rlpStream << _parentHash << _sha3Uncles << _author << _stateRoot << _transactionsRoot << _receiptsRoot << _logBloom
  1108. << _difficulty << _number << _gasLimit << _gasUsed << _timestamp << _extraData << h256{} << Nonce{};
  1109. return BlockHeader(rlpStream.out(), HeaderData);
  1110. }
  1111. void updateEthashSeal(dev::eth::BlockHeader& _header, h256 const& _mixHash, h64 const& _nonce)
  1112. {
  1113. Ethash::setNonce(_header, _nonce);
  1114. Ethash::setMixHash(_header, _mixHash);
  1115. }
  1116. namespace
  1117. {
  1118. Listener* g_listener;
  1119. }
  1120. void Listener::registerListener(Listener& _listener)
  1121. {
  1122. g_listener = &_listener;
  1123. }
  1124. void Listener::notifySuiteStarted(std::string const& _name)
  1125. {
  1126. if (g_listener)
  1127. g_listener->suiteStarted(_name);
  1128. }
  1129. void Listener::notifyTestStarted(std::string const& _name)
  1130. {
  1131. if (g_listener)
  1132. g_listener->testStarted(_name);
  1133. }
  1134. void Listener::notifyTestFinished(int64_t _gasUsed)
  1135. {
  1136. if (g_listener)
  1137. g_listener->testFinished(_gasUsed);
  1138. }
  1139. size_t TestOutputHelper::m_currTest = 0;
  1140. size_t TestOutputHelper::m_maxTests = 0;
  1141. string TestOutputHelper::m_currentTestName = "n/a";
  1142. string TestOutputHelper::m_currentTestCaseName = "n/a";
  1143. string TestOutputHelper::m_currentTestFileName = "n/a";
  1144. using namespace boost;
  1145. void TestOutputHelper::initTest(int _maxTests)
  1146. {
  1147. Ethash::init();
  1148. BasicAuthority::init();
  1149. NoProof::init();
  1150. m_currentTestCaseName = boost::unit_test::framework::current_test_case().p_name;
  1151. std::cout << "Test Case \"" + m_currentTestCaseName + "\": " << std::endl;
  1152. m_maxTests = _maxTests;
  1153. m_currTest = 0;
  1154. }
  1155. void TestOutputHelper::initTest(json_spirit::mValue& _v)
  1156. {
  1157. Ethash::init();
  1158. BasicAuthority::init();
  1159. NoProof::init();
  1160. m_currentTestCaseName = boost::unit_test::framework::current_test_case().p_name;
  1161. std::cout << "Test Case \"" + m_currentTestCaseName + "\": " << std::endl;
  1162. m_maxTests = _v.get_obj().size();
  1163. m_currTest = 0;
  1164. }
  1165. bool TestOutputHelper::passTest(json_spirit::mObject& _o, std::string& _testName)
  1166. {
  1167. m_currTest++;
  1168. int m_testsPerProgs = std::max(1, (int)(m_maxTests / 4));
  1169. if (m_currTest % m_testsPerProgs == 0 || m_currTest == m_maxTests)
  1170. {
  1171. int percent = int(m_currTest*100/m_maxTests);
  1172. std::cout << percent << "%";
  1173. if (percent != 100)
  1174. std::cout << "...";
  1175. std::cout << std::endl;
  1176. }
  1177. if (m_currentTestCaseName != "stRandom")
  1178. if (test::Options::get().singleTest && test::Options::get().singleTestName != _testName)
  1179. {
  1180. _o.clear();
  1181. return false;
  1182. }
  1183. cnote << _testName;
  1184. //_testName = (m_currentTestFileName == "n/a") ? "(" + _testName + ") " : "(" + m_currentTestFileName + "/" + _testName + ") ";
  1185. m_currentTestName = _testName + " ";
  1186. return true;
  1187. }
  1188. } } // namespaces