mirror of
https://github.com/ethereum/solidity
synced 2023-10-03 13:03:40 +00:00
Merge branch 'develop' into whisper
This commit is contained in:
commit
2afad75469
@ -25,6 +25,7 @@ add_subdirectory(libethereum)
|
||||
add_subdirectory(libevm)
|
||||
add_subdirectory(libnatspec)
|
||||
add_subdirectory(libp2p)
|
||||
add_subdirectory(external-dependencies)
|
||||
|
||||
if (JSCONSOLE)
|
||||
add_subdirectory(libjsengine)
|
||||
|
98
GasMeter.cpp
98
GasMeter.cpp
@ -1,98 +0,0 @@
|
||||
/*
|
||||
This file is part of cpp-ethereum.
|
||||
|
||||
cpp-ethereum is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
cpp-ethereum is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
/**
|
||||
* @author Christian <c@ethdev.com>
|
||||
* @date 2015
|
||||
* Unit tests for the gas estimator.
|
||||
*/
|
||||
|
||||
#include <test/libsolidity/solidityExecutionFramework.h>
|
||||
#include <libsolidity/AST.h>
|
||||
#include <libsolidity/StructuralGasEstimator.h>
|
||||
#include <libsolidity/SourceReferenceFormatter.h>
|
||||
|
||||
using namespace std;
|
||||
using namespace dev::eth;
|
||||
using namespace dev::solidity;
|
||||
|
||||
namespace dev
|
||||
{
|
||||
namespace solidity
|
||||
{
|
||||
namespace test
|
||||
{
|
||||
|
||||
class GasMeterTestFramework: public ExecutionFramework
|
||||
{
|
||||
public:
|
||||
GasMeterTestFramework() { }
|
||||
void compile(string const& _sourceCode)
|
||||
{
|
||||
m_compiler.setSource(_sourceCode);
|
||||
ETH_TEST_REQUIRE_NO_THROW(m_compiler.compile(), "Compiling contract failed");
|
||||
|
||||
StructuralGasEstimator estimator;
|
||||
AssemblyItems const* items = m_compiler.getRuntimeAssemblyItems("");
|
||||
ASTNode const& sourceUnit = m_compiler.getAST();
|
||||
BOOST_REQUIRE(items != nullptr);
|
||||
m_gasCosts = estimator.breakToStatementLevel(
|
||||
estimator.performEstimation(*items, vector<ASTNode const*>({&sourceUnit})),
|
||||
{&sourceUnit}
|
||||
);
|
||||
}
|
||||
|
||||
protected:
|
||||
dev::solidity::CompilerStack m_compiler;
|
||||
map<ASTNode const*, eth::GasMeter::GasConsumption> m_gasCosts;
|
||||
};
|
||||
|
||||
BOOST_FIXTURE_TEST_SUITE(GasMeterTests, GasMeterTestFramework)
|
||||
|
||||
BOOST_AUTO_TEST_CASE(non_overlapping_filtered_costs)
|
||||
{
|
||||
char const* sourceCode = R"(
|
||||
contract test {
|
||||
bytes x;
|
||||
function f(uint a) returns (uint b) {
|
||||
x.length = a;
|
||||
for (; a < 200; ++a) {
|
||||
x[a] = 9;
|
||||
b = a * a;
|
||||
}
|
||||
return f(a - 1);
|
||||
}
|
||||
}
|
||||
)";
|
||||
compile(sourceCode);
|
||||
for (auto first = m_gasCosts.cbegin(); first != m_gasCosts.cend(); ++first)
|
||||
{
|
||||
auto second = first;
|
||||
for (++second; second != m_gasCosts.cend(); ++second)
|
||||
if (first->first->getLocation().intersects(second->first->getLocation()))
|
||||
{
|
||||
BOOST_CHECK_MESSAGE(false, "Source locations should not overlap!");
|
||||
SourceReferenceFormatter::printSourceLocation(cout, first->first->getLocation(), m_compiler.getScanner());
|
||||
SourceReferenceFormatter::printSourceLocation(cout, second->first->getLocation(), m_compiler.getScanner());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_SUITE_END()
|
||||
|
||||
}
|
||||
}
|
||||
}
|
128
TestHelper.cpp
128
TestHelper.cpp
@ -288,7 +288,7 @@ void ImportTest::checkExpectedState(State const& _stateExpect, State const& _sta
|
||||
{
|
||||
addressOptions = _expectedStateOptions.at(a.first);
|
||||
}
|
||||
catch(std::out_of_range)
|
||||
catch(std::out_of_range const&)
|
||||
{
|
||||
BOOST_ERROR("expectedStateOptions map does not match expectedState in checkExpectedState!");
|
||||
break;
|
||||
@ -327,7 +327,8 @@ void ImportTest::checkExpectedState(State const& _stateExpect, State const& _sta
|
||||
void ImportTest::exportTest(bytes const& _output, State const& _statePost)
|
||||
{
|
||||
// export output
|
||||
m_TestObject["out"] = toHex(_output, 2, HexPrefix::Add);
|
||||
|
||||
m_TestObject["out"] = (_output.size() > 4096 && !Options::get().fulloutput) ? "#" + toString(_output.size()) : toHex(_output, 2, HexPrefix::Add);
|
||||
|
||||
// export logs
|
||||
m_TestObject["logs"] = exportLog(_statePost.pending().size() ? _statePost.log(0) : LogEntries());
|
||||
@ -489,7 +490,11 @@ LogEntries importLog(json_spirit::mArray& _a)
|
||||
void checkOutput(bytes const& _output, json_spirit::mObject& _o)
|
||||
{
|
||||
int j = 0;
|
||||
if (_o["out"].type() == json_spirit::array_type)
|
||||
|
||||
if (_o["out"].get_str().find("#") == 0)
|
||||
BOOST_CHECK((u256)_output.size() == toInt(_o["out"].get_str().substr(1)));
|
||||
|
||||
else if (_o["out"].type() == json_spirit::array_type)
|
||||
for (auto const& d: _o["out"].get_array())
|
||||
{
|
||||
BOOST_CHECK_MESSAGE(_output[j] == toInt(d), "Output byte [" << j << "] different!");
|
||||
@ -549,58 +554,53 @@ void checkCallCreates(eth::Transactions _resultCallCreates, eth::Transactions _e
|
||||
}
|
||||
}
|
||||
|
||||
void userDefinedTest(string testTypeFlag, std::function<void(json_spirit::mValue&, bool)> doTests)
|
||||
void userDefinedTest(std::function<void(json_spirit::mValue&, bool)> doTests)
|
||||
{
|
||||
Options::get(); // parse command line options, e.g. to enable JIT
|
||||
if (!Options::get().singleTest)
|
||||
return;
|
||||
|
||||
for (int i = 1; i < boost::unit_test::framework::master_test_suite().argc; ++i)
|
||||
if (Options::get().singleTestFile.empty() || Options::get().singleTestName.empty())
|
||||
{
|
||||
string arg = boost::unit_test::framework::master_test_suite().argv[i];
|
||||
if (arg == testTypeFlag)
|
||||
{
|
||||
if (boost::unit_test::framework::master_test_suite().argc <= i + 2)
|
||||
{
|
||||
cnote << "Missing filename\nUsage: testeth " << testTypeFlag << " <filename> <testname>\n";
|
||||
return;
|
||||
}
|
||||
string filename = boost::unit_test::framework::master_test_suite().argv[i + 1];
|
||||
string testname = boost::unit_test::framework::master_test_suite().argv[i + 2];
|
||||
int currentVerbosity = g_logVerbosity;
|
||||
g_logVerbosity = 12;
|
||||
try
|
||||
{
|
||||
cnote << "Testing user defined test: " << filename;
|
||||
json_spirit::mValue v;
|
||||
string s = asString(contents(filename));
|
||||
BOOST_REQUIRE_MESSAGE(s.length() > 0, "Contents of " + filename + " is empty. ");
|
||||
json_spirit::read_string(s, v);
|
||||
json_spirit::mObject oSingleTest;
|
||||
|
||||
json_spirit::mObject::const_iterator pos = v.get_obj().find(testname);
|
||||
if (pos == v.get_obj().end())
|
||||
{
|
||||
cnote << "Could not find test: " << testname << " in " << filename << "\n";
|
||||
return;
|
||||
}
|
||||
else
|
||||
oSingleTest[pos->first] = pos->second;
|
||||
|
||||
json_spirit::mValue v_singleTest(oSingleTest);
|
||||
doTests(v_singleTest, false);
|
||||
}
|
||||
catch (Exception const& _e)
|
||||
{
|
||||
BOOST_ERROR("Failed Test with Exception: " << diagnostic_information(_e));
|
||||
g_logVerbosity = currentVerbosity;
|
||||
}
|
||||
catch (std::exception const& _e)
|
||||
{
|
||||
BOOST_ERROR("Failed Test with Exception: " << _e.what());
|
||||
g_logVerbosity = currentVerbosity;
|
||||
}
|
||||
g_logVerbosity = currentVerbosity;
|
||||
}
|
||||
cnote << "Missing user test specification\nUsage: testeth --singletest <filename> <testname>\n";
|
||||
return;
|
||||
}
|
||||
|
||||
auto& filename = Options::get().singleTestFile;
|
||||
auto& testname = Options::get().singleTestName;
|
||||
int currentVerbosity = g_logVerbosity;
|
||||
g_logVerbosity = 12;
|
||||
try
|
||||
{
|
||||
cnote << "Testing user defined test: " << filename;
|
||||
json_spirit::mValue v;
|
||||
string s = asString(contents(filename));
|
||||
BOOST_REQUIRE_MESSAGE(s.length() > 0, "Contents of " + filename + " is empty. ");
|
||||
json_spirit::read_string(s, v);
|
||||
json_spirit::mObject oSingleTest;
|
||||
|
||||
json_spirit::mObject::const_iterator pos = v.get_obj().find(testname);
|
||||
if (pos == v.get_obj().end())
|
||||
{
|
||||
cnote << "Could not find test: " << testname << " in " << filename << "\n";
|
||||
return;
|
||||
}
|
||||
else
|
||||
oSingleTest[pos->first] = pos->second;
|
||||
|
||||
json_spirit::mValue v_singleTest(oSingleTest);
|
||||
doTests(v_singleTest, test::Options::get().fillTests);
|
||||
}
|
||||
catch (Exception const& _e)
|
||||
{
|
||||
BOOST_ERROR("Failed Test with Exception: " << diagnostic_information(_e));
|
||||
g_logVerbosity = currentVerbosity;
|
||||
}
|
||||
catch (std::exception const& _e)
|
||||
{
|
||||
BOOST_ERROR("Failed Test with Exception: " << _e.what());
|
||||
g_logVerbosity = currentVerbosity;
|
||||
}
|
||||
g_logVerbosity = currentVerbosity;
|
||||
}
|
||||
|
||||
void executeTests(const string& _name, const string& _testPathAppendix, const boost::filesystem::path _pathToFiller, std::function<void(json_spirit::mValue&, bool)> doTests)
|
||||
@ -707,10 +707,9 @@ Options::Options()
|
||||
{
|
||||
auto arg = std::string{argv[i]};
|
||||
if (arg == "--jit")
|
||||
{
|
||||
jit = true;
|
||||
eth::VMFactory::setKind(eth::VMKind::JIT);
|
||||
}
|
||||
else if (arg == "--vm=smart")
|
||||
eth::VMFactory::setKind(eth::VMKind::Smart);
|
||||
else if (arg == "--vmtrace")
|
||||
vmtrace = true;
|
||||
else if (arg == "--filltests")
|
||||
@ -732,6 +731,8 @@ Options::Options()
|
||||
bigData = true;
|
||||
else if (arg == "--checkstate")
|
||||
checkState = true;
|
||||
else if (arg == "--wallet")
|
||||
wallet = true;
|
||||
else if (arg == "--all")
|
||||
{
|
||||
performance = true;
|
||||
@ -739,12 +740,28 @@ Options::Options()
|
||||
memory = true;
|
||||
inputLimits = true;
|
||||
bigData = true;
|
||||
wallet= true;
|
||||
}
|
||||
else if (arg == "--singletest" && i + 1 < argc)
|
||||
{
|
||||
singleTest = true;
|
||||
singleTestName = argv[i + 1];
|
||||
auto name1 = std::string{argv[i + 1]};
|
||||
if (i + 1 < argc) // two params
|
||||
{
|
||||
auto name2 = std::string{argv[i + 2]};
|
||||
if (name2[0] == '-') // not param, another option
|
||||
singleTestName = std::move(name1);
|
||||
else
|
||||
{
|
||||
singleTestFile = std::move(name1);
|
||||
singleTestName = std::move(name2);
|
||||
}
|
||||
}
|
||||
else
|
||||
singleTestName = std::move(name1);
|
||||
}
|
||||
else if (arg == "--fulloutput")
|
||||
fulloutput = true;
|
||||
}
|
||||
}
|
||||
|
||||
@ -754,7 +771,6 @@ Options const& Options::get()
|
||||
return instance;
|
||||
}
|
||||
|
||||
|
||||
LastHashes lastHashes(u256 _currentBlockNumber)
|
||||
{
|
||||
LastHashes ret;
|
||||
|
@ -157,7 +157,7 @@ void checkLog(eth::LogEntries _resultLogs, eth::LogEntries _expectedLogs);
|
||||
void checkCallCreates(eth::Transactions _resultCallCreates, eth::Transactions _expectedCallCreates);
|
||||
|
||||
void executeTests(const std::string& _name, const std::string& _testPathAppendix, const boost::filesystem::path _pathToFiller, std::function<void(json_spirit::mValue&, bool)> doTests);
|
||||
void userDefinedTest(std::string testTypeFlag, std::function<void(json_spirit::mValue&, bool)> doTests);
|
||||
void userDefinedTest(std::function<void(json_spirit::mValue&, bool)> doTests);
|
||||
RLPStream createRLPStreamFromTransactionFields(json_spirit::mObject& _tObj);
|
||||
eth::LastHashes lastHashes(u256 _currentBlockNumber);
|
||||
json_spirit::mObject fillJsonWithState(eth::State _state);
|
||||
@ -179,22 +179,24 @@ void checkAddresses(mapType& _expectedAddrs, mapType& _resultAddrs)
|
||||
class Options
|
||||
{
|
||||
public:
|
||||
bool jit = false; ///< Use JIT
|
||||
bool vmtrace = false; ///< Create EVM execution tracer // TODO: Link with log verbosity?
|
||||
bool fillTests = false; ///< Create JSON test files from execution results
|
||||
bool stats = false; ///< Execution time stats
|
||||
std::string statsOutFile; ///< Stats output file. "out" for standard output
|
||||
bool checkState = false;///< Throw error when checking test states
|
||||
bool fulloutput = false;///< Replace large output to just it's length
|
||||
|
||||
/// Test selection
|
||||
/// @{
|
||||
bool singleTest = false;
|
||||
std::string singleTestFile;
|
||||
std::string singleTestName;
|
||||
bool performance = false;
|
||||
bool quadratic = false;
|
||||
bool memory = false;
|
||||
bool inputLimits = false;
|
||||
bool bigData = false;
|
||||
bool wallet = false;
|
||||
/// @}
|
||||
|
||||
/// Get reference to options
|
||||
|
235
libsolidity/GasMeter.cpp
Normal file
235
libsolidity/GasMeter.cpp
Normal file
@ -0,0 +1,235 @@
|
||||
/*
|
||||
This file is part of cpp-ethereum.
|
||||
|
||||
cpp-ethereum is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
cpp-ethereum is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
/**
|
||||
* @author Christian <c@ethdev.com>
|
||||
* @date 2015
|
||||
* Unit tests for the gas estimator.
|
||||
*/
|
||||
|
||||
#include <test/libsolidity/solidityExecutionFramework.h>
|
||||
#include <libevmasm/GasMeter.h>
|
||||
#include <libevmasm/KnownState.h>
|
||||
#include <libevmasm/PathGasMeter.h>
|
||||
#include <libsolidity/AST.h>
|
||||
#include <libsolidity/GasEstimator.h>
|
||||
#include <libsolidity/SourceReferenceFormatter.h>
|
||||
|
||||
using namespace std;
|
||||
using namespace dev::eth;
|
||||
using namespace dev::solidity;
|
||||
|
||||
namespace dev
|
||||
{
|
||||
namespace solidity
|
||||
{
|
||||
namespace test
|
||||
{
|
||||
|
||||
class GasMeterTestFramework: public ExecutionFramework
|
||||
{
|
||||
public:
|
||||
GasMeterTestFramework() { }
|
||||
void compile(string const& _sourceCode)
|
||||
{
|
||||
m_compiler.setSource(_sourceCode);
|
||||
ETH_TEST_REQUIRE_NO_THROW(m_compiler.compile(), "Compiling contract failed");
|
||||
|
||||
AssemblyItems const* items = m_compiler.getRuntimeAssemblyItems("");
|
||||
ASTNode const& sourceUnit = m_compiler.getAST();
|
||||
BOOST_REQUIRE(items != nullptr);
|
||||
m_gasCosts = GasEstimator::breakToStatementLevel(
|
||||
GasEstimator::structuralEstimation(*items, vector<ASTNode const*>({&sourceUnit})),
|
||||
{&sourceUnit}
|
||||
);
|
||||
}
|
||||
|
||||
void testCreationTimeGas(string const& _sourceCode)
|
||||
{
|
||||
compileAndRun(_sourceCode);
|
||||
auto state = make_shared<KnownState>();
|
||||
PathGasMeter meter(*m_compiler.getAssemblyItems());
|
||||
GasMeter::GasConsumption gas = meter.estimateMax(0, state);
|
||||
u256 bytecodeSize(m_compiler.getRuntimeBytecode().size());
|
||||
gas += bytecodeSize * c_createDataGas;
|
||||
BOOST_REQUIRE(!gas.isInfinite);
|
||||
BOOST_CHECK(gas.value == m_gasUsed);
|
||||
}
|
||||
|
||||
/// Compares the gas computed by PathGasMeter for the given signature (but unknown arguments)
|
||||
/// against the actual gas usage computed by the VM on the given set of argument variants.
|
||||
void testRunTimeGas(string const& _sig, vector<bytes> _argumentVariants)
|
||||
{
|
||||
u256 gasUsed = 0;
|
||||
FixedHash<4> hash(dev::sha3(_sig));
|
||||
for (bytes const& arguments: _argumentVariants)
|
||||
{
|
||||
sendMessage(hash.asBytes() + arguments, false, 0);
|
||||
gasUsed = max(gasUsed, m_gasUsed);
|
||||
}
|
||||
|
||||
GasMeter::GasConsumption gas = GasEstimator::functionalEstimation(
|
||||
*m_compiler.getRuntimeAssemblyItems(),
|
||||
_sig
|
||||
);
|
||||
BOOST_REQUIRE(!gas.isInfinite);
|
||||
BOOST_CHECK(gas.value == m_gasUsed);
|
||||
}
|
||||
|
||||
protected:
|
||||
map<ASTNode const*, eth::GasMeter::GasConsumption> m_gasCosts;
|
||||
};
|
||||
|
||||
BOOST_FIXTURE_TEST_SUITE(GasMeterTests, GasMeterTestFramework)
|
||||
|
||||
BOOST_AUTO_TEST_CASE(non_overlapping_filtered_costs)
|
||||
{
|
||||
char const* sourceCode = R"(
|
||||
contract test {
|
||||
bytes x;
|
||||
function f(uint a) returns (uint b) {
|
||||
x.length = a;
|
||||
for (; a < 200; ++a) {
|
||||
x[a] = 9;
|
||||
b = a * a;
|
||||
}
|
||||
return f(a - 1);
|
||||
}
|
||||
}
|
||||
)";
|
||||
compile(sourceCode);
|
||||
for (auto first = m_gasCosts.cbegin(); first != m_gasCosts.cend(); ++first)
|
||||
{
|
||||
auto second = first;
|
||||
for (++second; second != m_gasCosts.cend(); ++second)
|
||||
if (first->first->getLocation().intersects(second->first->getLocation()))
|
||||
{
|
||||
BOOST_CHECK_MESSAGE(false, "Source locations should not overlap!");
|
||||
SourceReferenceFormatter::printSourceLocation(cout, first->first->getLocation(), m_compiler.getScanner());
|
||||
SourceReferenceFormatter::printSourceLocation(cout, second->first->getLocation(), m_compiler.getScanner());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_CASE(simple_contract)
|
||||
{
|
||||
// Tests a simple "deploy contract" code without constructor. The actual contract is not relevant.
|
||||
char const* sourceCode = R"(
|
||||
contract test {
|
||||
bytes32 public shaValue;
|
||||
function f(uint a) {
|
||||
shaValue = sha3(a);
|
||||
}
|
||||
}
|
||||
)";
|
||||
testCreationTimeGas(sourceCode);
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_CASE(store_sha3)
|
||||
{
|
||||
char const* sourceCode = R"(
|
||||
contract test {
|
||||
bytes32 public shaValue;
|
||||
function test(uint a) {
|
||||
shaValue = sha3(a);
|
||||
}
|
||||
}
|
||||
)";
|
||||
testCreationTimeGas(sourceCode);
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_CASE(updating_store)
|
||||
{
|
||||
char const* sourceCode = R"(
|
||||
contract test {
|
||||
uint data;
|
||||
uint data2;
|
||||
function test() {
|
||||
data = 1;
|
||||
data = 2;
|
||||
data2 = 0;
|
||||
}
|
||||
}
|
||||
)";
|
||||
testCreationTimeGas(sourceCode);
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_CASE(branches)
|
||||
{
|
||||
char const* sourceCode = R"(
|
||||
contract test {
|
||||
uint data;
|
||||
uint data2;
|
||||
function f(uint x) {
|
||||
if (x > 7)
|
||||
data2 = 1;
|
||||
else
|
||||
data = 1;
|
||||
}
|
||||
}
|
||||
)";
|
||||
testCreationTimeGas(sourceCode);
|
||||
testRunTimeGas("f(uint256)", vector<bytes>{encodeArgs(2), encodeArgs(8)});
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_CASE(function_calls)
|
||||
{
|
||||
char const* sourceCode = R"(
|
||||
contract test {
|
||||
uint data;
|
||||
uint data2;
|
||||
function f(uint x) {
|
||||
if (x > 7)
|
||||
data2 = g(x**8) + 1;
|
||||
else
|
||||
data = 1;
|
||||
}
|
||||
function g(uint x) internal returns (uint) {
|
||||
return data2;
|
||||
}
|
||||
}
|
||||
)";
|
||||
testCreationTimeGas(sourceCode);
|
||||
testRunTimeGas("f(uint256)", vector<bytes>{encodeArgs(2), encodeArgs(8)});
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_CASE(multiple_external_functions)
|
||||
{
|
||||
char const* sourceCode = R"(
|
||||
contract test {
|
||||
uint data;
|
||||
uint data2;
|
||||
function f(uint x) {
|
||||
if (x > 7)
|
||||
data2 = g(x**8) + 1;
|
||||
else
|
||||
data = 1;
|
||||
}
|
||||
function g(uint x) returns (uint) {
|
||||
return data2;
|
||||
}
|
||||
}
|
||||
)";
|
||||
testCreationTimeGas(sourceCode);
|
||||
testRunTimeGas("f(uint256)", vector<bytes>{encodeArgs(2), encodeArgs(8)});
|
||||
testRunTimeGas("g(uint256)", vector<bytes>{encodeArgs(2)});
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_SUITE_END()
|
||||
|
||||
}
|
||||
}
|
||||
}
|
@ -525,6 +525,76 @@ BOOST_AUTO_TEST_CASE(constructor_abi)
|
||||
checkInterface(sourceCode, interface);
|
||||
}
|
||||
|
||||
|
||||
BOOST_AUTO_TEST_CASE(return_param_in_abi)
|
||||
{
|
||||
// bug #1801
|
||||
char const* sourceCode = R"(
|
||||
contract test {
|
||||
enum ActionChoices { GoLeft, GoRight, GoStraight, Sit }
|
||||
function test(ActionChoices param) {}
|
||||
function ret() returns(ActionChoices){
|
||||
ActionChoices action = ActionChoices.GoLeft;
|
||||
return action;
|
||||
}
|
||||
}
|
||||
)";
|
||||
|
||||
char const* interface = R"(
|
||||
[
|
||||
{
|
||||
"constant" : false,
|
||||
"inputs" : [],
|
||||
"name" : "ret",
|
||||
"outputs" : [
|
||||
{
|
||||
"name" : "",
|
||||
"type" : "uint8"
|
||||
}
|
||||
],
|
||||
"type" : "function"
|
||||
},
|
||||
{
|
||||
"inputs": [
|
||||
{
|
||||
"name": "param",
|
||||
"type": "uint8"
|
||||
}
|
||||
],
|
||||
"type": "constructor"
|
||||
}
|
||||
]
|
||||
)";
|
||||
checkInterface(sourceCode, interface);
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_CASE(strings_and_arrays)
|
||||
{
|
||||
// bug #1801
|
||||
char const* sourceCode = R"(
|
||||
contract test {
|
||||
function f(string a, bytes b, uint[] c) external {}
|
||||
}
|
||||
)";
|
||||
|
||||
char const* interface = R"(
|
||||
[
|
||||
{
|
||||
"constant" : false,
|
||||
"name": "f",
|
||||
"inputs": [
|
||||
{ "name": "a", "type": "string" },
|
||||
{ "name": "b", "type": "bytes" },
|
||||
{ "name": "c", "type": "uint256[]" }
|
||||
],
|
||||
"outputs": [],
|
||||
"type" : "function"
|
||||
}
|
||||
]
|
||||
)";
|
||||
checkInterface(sourceCode, interface);
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_SUITE_END()
|
||||
|
||||
}
|
||||
|
@ -1,193 +0,0 @@
|
||||
/*
|
||||
This file is part of cpp-ethereum.
|
||||
|
||||
cpp-ethereum is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
cpp-ethereum is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
/**
|
||||
* @author Christian <c@ethdev.com>
|
||||
* @date 2014
|
||||
* Unit tests for the solidity compiler.
|
||||
*/
|
||||
|
||||
#include <string>
|
||||
#include <iostream>
|
||||
#include <boost/test/unit_test.hpp>
|
||||
#include <libdevcore/Log.h>
|
||||
#include <libsolidity/Scanner.h>
|
||||
#include <libsolidity/Parser.h>
|
||||
#include <libsolidity/NameAndTypeResolver.h>
|
||||
#include <libsolidity/Compiler.h>
|
||||
#include <libsolidity/AST.h>
|
||||
|
||||
using namespace std;
|
||||
using namespace dev::eth;
|
||||
|
||||
namespace dev
|
||||
{
|
||||
namespace solidity
|
||||
{
|
||||
namespace test
|
||||
{
|
||||
|
||||
namespace
|
||||
{
|
||||
|
||||
bytes compileContract(const string& _sourceCode)
|
||||
{
|
||||
Parser parser;
|
||||
ASTPointer<SourceUnit> sourceUnit;
|
||||
BOOST_REQUIRE_NO_THROW(sourceUnit = parser.parse(make_shared<Scanner>(CharStream(_sourceCode))));
|
||||
NameAndTypeResolver resolver({});
|
||||
resolver.registerDeclarations(*sourceUnit);
|
||||
for (ASTPointer<ASTNode> const& node: sourceUnit->getNodes())
|
||||
if (ContractDefinition* contract = dynamic_cast<ContractDefinition*>(node.get()))
|
||||
{
|
||||
BOOST_REQUIRE_NO_THROW(resolver.resolveNamesAndTypes(*contract));
|
||||
}
|
||||
for (ASTPointer<ASTNode> const& node: sourceUnit->getNodes())
|
||||
if (ContractDefinition* contract = dynamic_cast<ContractDefinition*>(node.get()))
|
||||
{
|
||||
BOOST_REQUIRE_NO_THROW(resolver.checkTypeRequirements(*contract));
|
||||
}
|
||||
for (ASTPointer<ASTNode> const& node: sourceUnit->getNodes())
|
||||
if (ContractDefinition* contract = dynamic_cast<ContractDefinition*>(node.get()))
|
||||
{
|
||||
Compiler compiler;
|
||||
compiler.compileContract(*contract, map<ContractDefinition const*, bytes const*>{});
|
||||
|
||||
// debug
|
||||
//compiler.streamAssembly(cout);
|
||||
return compiler.getAssembledBytecode();
|
||||
}
|
||||
BOOST_FAIL("No contract found in source.");
|
||||
return bytes();
|
||||
}
|
||||
|
||||
/// Checks that @a _compiledCode is present starting from offset @a _offset in @a _expectation.
|
||||
/// This is necessary since the compiler will add boilerplate add the beginning that is not
|
||||
/// tested here.
|
||||
void checkCodePresentAt(bytes const& _compiledCode, bytes const& _expectation, unsigned _offset)
|
||||
{
|
||||
BOOST_REQUIRE(_compiledCode.size() >= _offset + _expectation.size());
|
||||
auto checkStart = _compiledCode.begin() + _offset;
|
||||
BOOST_CHECK_EQUAL_COLLECTIONS(checkStart, checkStart + _expectation.size(),
|
||||
_expectation.begin(), _expectation.end());
|
||||
}
|
||||
|
||||
} // end anonymous namespace
|
||||
|
||||
BOOST_AUTO_TEST_SUITE(SolidityCompiler)
|
||||
|
||||
BOOST_AUTO_TEST_CASE(smoke_test)
|
||||
{
|
||||
char const* sourceCode = "contract test {\n"
|
||||
" function f() { var x = 2; }\n"
|
||||
"}\n";
|
||||
bytes code = compileContract(sourceCode);
|
||||
|
||||
unsigned boilerplateSize = 73;
|
||||
bytes expectation({byte(Instruction::JUMPDEST),
|
||||
byte(Instruction::PUSH1), 0x0, // initialize local variable x
|
||||
byte(Instruction::PUSH1), 0x2,
|
||||
byte(Instruction::SWAP1),
|
||||
byte(Instruction::POP),
|
||||
byte(Instruction::JUMPDEST),
|
||||
byte(Instruction::POP),
|
||||
byte(Instruction::JUMP)});
|
||||
checkCodePresentAt(code, expectation, boilerplateSize);
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_CASE(ifStatement)
|
||||
{
|
||||
char const* sourceCode = "contract test {\n"
|
||||
" function f() { bool x; if (x) 77; else if (!x) 78; else 79; }"
|
||||
"}\n";
|
||||
bytes code = compileContract(sourceCode);
|
||||
unsigned shift = 60;
|
||||
unsigned boilerplateSize = 73;
|
||||
bytes expectation({byte(Instruction::JUMPDEST),
|
||||
byte(Instruction::PUSH1), 0x0,
|
||||
byte(Instruction::DUP1),
|
||||
byte(Instruction::PUSH1), byte(0x1b + shift), // "true" target
|
||||
byte(Instruction::JUMPI),
|
||||
// new check "else if" condition
|
||||
byte(Instruction::DUP1),
|
||||
byte(Instruction::ISZERO),
|
||||
byte(Instruction::PUSH1), byte(0x13 + shift),
|
||||
byte(Instruction::JUMPI),
|
||||
// "else" body
|
||||
byte(Instruction::PUSH1), 0x4f,
|
||||
byte(Instruction::POP),
|
||||
byte(Instruction::PUSH1), byte(0x17 + shift), // exit path of second part
|
||||
byte(Instruction::JUMP),
|
||||
// "else if" body
|
||||
byte(Instruction::JUMPDEST),
|
||||
byte(Instruction::PUSH1), 0x4e,
|
||||
byte(Instruction::POP),
|
||||
byte(Instruction::JUMPDEST),
|
||||
byte(Instruction::PUSH1), byte(0x1f + shift),
|
||||
byte(Instruction::JUMP),
|
||||
// "if" body
|
||||
byte(Instruction::JUMPDEST),
|
||||
byte(Instruction::PUSH1), 0x4d,
|
||||
byte(Instruction::POP),
|
||||
byte(Instruction::JUMPDEST),
|
||||
byte(Instruction::JUMPDEST),
|
||||
byte(Instruction::POP),
|
||||
byte(Instruction::JUMP)});
|
||||
checkCodePresentAt(code, expectation, boilerplateSize);
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_CASE(loops)
|
||||
{
|
||||
char const* sourceCode = "contract test {\n"
|
||||
" function f() { while(true){1;break;2;continue;3;return;4;} }"
|
||||
"}\n";
|
||||
bytes code = compileContract(sourceCode);
|
||||
unsigned shift = 60;
|
||||
unsigned boilerplateSize = 73;
|
||||
bytes expectation({byte(Instruction::JUMPDEST),
|
||||
byte(Instruction::JUMPDEST),
|
||||
byte(Instruction::PUSH1), 0x1,
|
||||
byte(Instruction::ISZERO),
|
||||
byte(Instruction::PUSH1), byte(0x21 + shift),
|
||||
byte(Instruction::JUMPI),
|
||||
byte(Instruction::PUSH1), 0x1,
|
||||
byte(Instruction::POP),
|
||||
byte(Instruction::PUSH1), byte(0x21 + shift),
|
||||
byte(Instruction::JUMP), // break
|
||||
byte(Instruction::PUSH1), 0x2,
|
||||
byte(Instruction::POP),
|
||||
byte(Instruction::PUSH1), byte(0x2 + shift),
|
||||
byte(Instruction::JUMP), // continue
|
||||
byte(Instruction::PUSH1), 0x3,
|
||||
byte(Instruction::POP),
|
||||
byte(Instruction::PUSH1), byte(0x22 + shift),
|
||||
byte(Instruction::JUMP), // return
|
||||
byte(Instruction::PUSH1), 0x4,
|
||||
byte(Instruction::POP),
|
||||
byte(Instruction::PUSH1), byte(0x2 + shift),
|
||||
byte(Instruction::JUMP),
|
||||
byte(Instruction::JUMPDEST),
|
||||
byte(Instruction::JUMPDEST),
|
||||
byte(Instruction::JUMP)});
|
||||
|
||||
checkCodePresentAt(code, expectation, boilerplateSize);
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_SUITE_END()
|
||||
|
||||
}
|
||||
}
|
||||
} // end namespaces
|
@ -24,7 +24,7 @@
|
||||
#include <string>
|
||||
#include <tuple>
|
||||
#include <boost/test/unit_test.hpp>
|
||||
#include <libdevcrypto/SHA3.h>
|
||||
#include <libdevcore/Hash.h>
|
||||
#include <test/libsolidity/solidityExecutionFramework.h>
|
||||
|
||||
using namespace std;
|
||||
@ -1501,9 +1501,7 @@ BOOST_AUTO_TEST_CASE(sha256)
|
||||
compileAndRun(sourceCode);
|
||||
auto f = [&](u256 const& _input) -> u256
|
||||
{
|
||||
h256 ret;
|
||||
dev::sha256(dev::ref(toBigEndian(_input)), bytesRef(&ret[0], 32));
|
||||
return ret;
|
||||
return dev::sha256(dev::ref(toBigEndian(_input)));
|
||||
};
|
||||
testSolidityAgainstCpp("a(bytes32)", f, u256(4));
|
||||
testSolidityAgainstCpp("a(bytes32)", f, u256(5));
|
||||
@ -1520,9 +1518,7 @@ BOOST_AUTO_TEST_CASE(ripemd)
|
||||
compileAndRun(sourceCode);
|
||||
auto f = [&](u256 const& _input) -> u256
|
||||
{
|
||||
h256 ret;
|
||||
dev::ripemd160(dev::ref(toBigEndian(_input)), bytesRef(&ret[0], 32));
|
||||
return u256(ret);
|
||||
return h256(dev::ripemd160(h256(_input).ref()), h256::AlignLeft); // This should be aligned right. i guess it's fixed elsewhere?
|
||||
};
|
||||
testSolidityAgainstCpp("a(bytes32)", f, u256(4));
|
||||
testSolidityAgainstCpp("a(bytes32)", f, u256(5));
|
||||
@ -2558,6 +2554,37 @@ BOOST_AUTO_TEST_CASE(generic_call)
|
||||
BOOST_CHECK_EQUAL(m_state.balance(m_contractAddress), 50 - 2);
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_CASE(generic_callcode)
|
||||
{
|
||||
char const* sourceCode = R"**(
|
||||
contract receiver {
|
||||
uint public received;
|
||||
function receive(uint256 x) { received = x; }
|
||||
}
|
||||
contract sender {
|
||||
uint public received;
|
||||
function doSend(address rec) returns (uint d)
|
||||
{
|
||||
bytes4 signature = bytes4(bytes32(sha3("receive(uint256)")));
|
||||
rec.callcode.value(2)(signature, 23);
|
||||
return receiver(rec).received();
|
||||
}
|
||||
}
|
||||
)**";
|
||||
compileAndRun(sourceCode, 0, "receiver");
|
||||
u160 const c_receiverAddress = m_contractAddress;
|
||||
compileAndRun(sourceCode, 50, "sender");
|
||||
u160 const c_senderAddress = m_contractAddress;
|
||||
BOOST_CHECK(callContractFunction("doSend(address)", c_receiverAddress) == encodeArgs(0));
|
||||
BOOST_CHECK(callContractFunction("received()") == encodeArgs(23));
|
||||
m_contractAddress = c_receiverAddress;
|
||||
BOOST_CHECK(callContractFunction("received()") == encodeArgs(0));
|
||||
BOOST_CHECK(m_state.storage(c_receiverAddress).empty());
|
||||
BOOST_CHECK(!m_state.storage(c_senderAddress).empty());
|
||||
BOOST_CHECK_EQUAL(m_state.balance(c_receiverAddress), 0);
|
||||
BOOST_CHECK_EQUAL(m_state.balance(c_senderAddress), 50);
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_CASE(store_bytes)
|
||||
{
|
||||
// this test just checks that the copy loop does not mess up the stack
|
||||
@ -3996,6 +4023,154 @@ BOOST_AUTO_TEST_CASE(overwriting_inheritance)
|
||||
BOOST_CHECK(callContractFunction("checkOk()") == encodeArgs(6));
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_CASE(struct_assign_reference_to_struct)
|
||||
{
|
||||
char const* sourceCode = R"(
|
||||
contract test {
|
||||
struct testStruct
|
||||
{
|
||||
uint m_value;
|
||||
}
|
||||
testStruct data1;
|
||||
testStruct data2;
|
||||
testStruct data3;
|
||||
function test()
|
||||
{
|
||||
data1.m_value = 2;
|
||||
}
|
||||
function assign() returns (uint ret_local, uint ret_global, uint ret_global3, uint ret_global1)
|
||||
{
|
||||
testStruct x = data1; //x is a reference data1.m_value == 2 as well as x.m_value = 2
|
||||
data2 = data1; // should copy data. data2.m_value == 2
|
||||
|
||||
ret_local = x.m_value; // = 2
|
||||
ret_global = data2.m_value; // = 2
|
||||
|
||||
x.m_value = 3;
|
||||
data3 = x; //should copy the data. data3.m_value == 3
|
||||
ret_global3 = data3.m_value; // = 3
|
||||
ret_global1 = data1.m_value; // = 3. Changed due to the assignment to x.m_value
|
||||
}
|
||||
}
|
||||
)";
|
||||
compileAndRun(sourceCode, 0, "test");
|
||||
BOOST_CHECK(callContractFunction("assign()") == encodeArgs(2, 2, 3, 3));
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_CASE(struct_delete_member)
|
||||
{
|
||||
char const* sourceCode = R"(
|
||||
contract test {
|
||||
struct testStruct
|
||||
{
|
||||
uint m_value;
|
||||
}
|
||||
testStruct data1;
|
||||
function test()
|
||||
{
|
||||
data1.m_value = 2;
|
||||
}
|
||||
function deleteMember() returns (uint ret_value)
|
||||
{
|
||||
testStruct x = data1; //should not copy the data. data1.m_value == 2 but x.m_value = 0
|
||||
x.m_value = 4;
|
||||
delete x.m_value;
|
||||
ret_value = data1.m_value;
|
||||
}
|
||||
}
|
||||
)";
|
||||
compileAndRun(sourceCode, 0, "test");
|
||||
BOOST_CHECK(callContractFunction("deleteMember()") == encodeArgs(0));
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_CASE(struct_delete_struct_in_mapping)
|
||||
{
|
||||
char const* sourceCode = R"(
|
||||
contract test {
|
||||
struct testStruct
|
||||
{
|
||||
uint m_value;
|
||||
}
|
||||
mapping (uint => testStruct) campaigns;
|
||||
|
||||
function test()
|
||||
{
|
||||
campaigns[0].m_value = 2;
|
||||
}
|
||||
function deleteIt() returns (uint)
|
||||
{
|
||||
delete campaigns[0];
|
||||
return campaigns[0].m_value;
|
||||
}
|
||||
}
|
||||
)";
|
||||
compileAndRun(sourceCode, 0, "test");
|
||||
BOOST_CHECK(callContractFunction("deleteIt()") == encodeArgs(0));
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_CASE(evm_exceptions_out_of_band_access)
|
||||
{
|
||||
char const* sourceCode = R"(
|
||||
contract A {
|
||||
uint[3] arr;
|
||||
bool public test = false;
|
||||
function getElement(uint i) returns (uint)
|
||||
{
|
||||
return arr[i];
|
||||
}
|
||||
function testIt() returns (bool)
|
||||
{
|
||||
uint i = this.getElement(5);
|
||||
test = true;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
)";
|
||||
compileAndRun(sourceCode, 0, "A");
|
||||
BOOST_CHECK(callContractFunction("test()") == encodeArgs(false));
|
||||
BOOST_CHECK(callContractFunction("testIt()") == encodeArgs());
|
||||
BOOST_CHECK(callContractFunction("test()") == encodeArgs(false));
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_CASE(evm_exceptions_in_constructor_call_fail)
|
||||
{
|
||||
char const* sourceCode = R"(
|
||||
contract A {
|
||||
function A()
|
||||
{
|
||||
this.call("123");
|
||||
}
|
||||
}
|
||||
contract B {
|
||||
uint public test = 1;
|
||||
function testIt()
|
||||
{
|
||||
A a = new A();
|
||||
++test;
|
||||
}
|
||||
}
|
||||
)";
|
||||
compileAndRun(sourceCode, 0, "B");
|
||||
|
||||
BOOST_CHECK(callContractFunction("testIt()") == encodeArgs());
|
||||
BOOST_CHECK(callContractFunction("test()") == encodeArgs(2));
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_CASE(evm_exceptions_in_constructor_out_of_baund)
|
||||
{
|
||||
char const* sourceCode = R"(
|
||||
contract A {
|
||||
uint public test = 1;
|
||||
uint[3] arr;
|
||||
function A()
|
||||
{
|
||||
test = arr[5];
|
||||
++test;
|
||||
}
|
||||
}
|
||||
)";
|
||||
BOOST_CHECK(compileAndRunWthoutCheck(sourceCode, 0, "A").empty());
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_SUITE_END()
|
||||
|
||||
|
@ -23,7 +23,7 @@
|
||||
#include <string>
|
||||
|
||||
#include <libdevcore/Log.h>
|
||||
#include <libdevcrypto/SHA3.h>
|
||||
#include <libdevcore/SHA3.h>
|
||||
#include <libsolidity/Scanner.h>
|
||||
#include <libsolidity/Parser.h>
|
||||
#include <libsolidity/NameAndTypeResolver.h>
|
||||
@ -508,6 +508,28 @@ BOOST_AUTO_TEST_CASE(function_external_types)
|
||||
}
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_CASE(enum_external_type)
|
||||
{
|
||||
// bug #1801
|
||||
ASTPointer<SourceUnit> sourceUnit;
|
||||
char const* text = R"(
|
||||
contract Test {
|
||||
enum ActionChoices { GoLeft, GoRight, GoStraight, Sit }
|
||||
function boo(ActionChoices enumArg) external returns (uint ret) {
|
||||
ret = 5;
|
||||
}
|
||||
})";
|
||||
ETH_TEST_REQUIRE_NO_THROW(sourceUnit = parseTextAndResolveNames(text), "Parsing and name Resolving failed");
|
||||
for (ASTPointer<ASTNode> const& node: sourceUnit->getNodes())
|
||||
if (ContractDefinition* contract = dynamic_cast<ContractDefinition*>(node.get()))
|
||||
{
|
||||
auto functions = contract->getDefinedFunctions();
|
||||
if (functions.empty())
|
||||
continue;
|
||||
BOOST_CHECK_EQUAL("boo(uint8)", functions[0]->externalSignature());
|
||||
}
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_CASE(function_external_call_allowed_conversion)
|
||||
{
|
||||
char const* text = R"(
|
||||
@ -1761,6 +1783,39 @@ BOOST_AUTO_TEST_CASE(uninitialized_var)
|
||||
BOOST_CHECK_THROW(parseTextAndResolveNames(sourceCode), TypeError);
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_CASE(string)
|
||||
{
|
||||
char const* sourceCode = R"(
|
||||
contract C {
|
||||
string s;
|
||||
function f(string x) external { s = x; }
|
||||
}
|
||||
)";
|
||||
BOOST_CHECK_NO_THROW(parseTextAndResolveNames(sourceCode));
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_CASE(string_index)
|
||||
{
|
||||
char const* sourceCode = R"(
|
||||
contract C {
|
||||
string s;
|
||||
function f() { var a = s[2]; }
|
||||
}
|
||||
)";
|
||||
BOOST_CHECK_THROW(parseTextAndResolveNames(sourceCode), TypeError);
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_CASE(string_length)
|
||||
{
|
||||
char const* sourceCode = R"(
|
||||
contract C {
|
||||
string s;
|
||||
function f() { var a = s.length; }
|
||||
}
|
||||
)";
|
||||
BOOST_CHECK_THROW(parseTextAndResolveNames(sourceCode), TypeError);
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_SUITE_END()
|
||||
|
||||
}
|
||||
|
@ -29,6 +29,7 @@
|
||||
#include <libevmasm/CommonSubexpressionEliminator.h>
|
||||
#include <libevmasm/ControlFlowGraph.h>
|
||||
#include <libevmasm/Assembly.h>
|
||||
#include <libevmasm/BlockDeduplicator.h>
|
||||
|
||||
using namespace std;
|
||||
using namespace dev::eth;
|
||||
@ -96,7 +97,7 @@ public:
|
||||
{
|
||||
eth::KnownState state;
|
||||
for (auto const& item: addDummyLocations(_input))
|
||||
state.feedItem(item);
|
||||
state.feedItem(item, true);
|
||||
return state;
|
||||
}
|
||||
|
||||
@ -125,7 +126,7 @@ public:
|
||||
BOOST_CHECK_EQUAL_COLLECTIONS(_expectation.begin(), _expectation.end(), output.begin(), output.end());
|
||||
}
|
||||
|
||||
void checkCFG(AssemblyItems const& _input, AssemblyItems const& _expectation)
|
||||
AssemblyItems getCFG(AssemblyItems const& _input)
|
||||
{
|
||||
AssemblyItems output = _input;
|
||||
// Running it four times should be enough for these tests.
|
||||
@ -138,6 +139,12 @@ public:
|
||||
back_inserter(optItems));
|
||||
output = move(optItems);
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
void checkCFG(AssemblyItems const& _input, AssemblyItems const& _expectation)
|
||||
{
|
||||
AssemblyItems output = getCFG(_input);
|
||||
BOOST_CHECK_EQUAL_COLLECTIONS(_expectation.begin(), _expectation.end(), output.begin(), output.end());
|
||||
}
|
||||
|
||||
@ -251,6 +258,106 @@ BOOST_AUTO_TEST_CASE(function_calls)
|
||||
compareVersions("f(uint256)", 36);
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_CASE(storage_write_in_loops)
|
||||
{
|
||||
char const* sourceCode = R"(
|
||||
contract test {
|
||||
uint d;
|
||||
function f(uint a) returns (uint r) {
|
||||
var x = d;
|
||||
for (uint i = 1; i < a * a; i++) {
|
||||
r = d;
|
||||
d = i;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
)";
|
||||
compileBothVersions(sourceCode);
|
||||
compareVersions("f(uint256)", 0);
|
||||
compareVersions("f(uint256)", 10);
|
||||
compareVersions("f(uint256)", 36);
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_CASE(retain_information_in_branches)
|
||||
{
|
||||
// This tests that the optimizer knows that we already have "z == sha3(y)" inside both branches.
|
||||
char const* sourceCode = R"(
|
||||
contract c {
|
||||
bytes32 d;
|
||||
uint a;
|
||||
function f(uint x, bytes32 y) returns (uint r_a, bytes32 r_d) {
|
||||
bytes32 z = sha3(y);
|
||||
if (x > 8) {
|
||||
z = sha3(y);
|
||||
a = x;
|
||||
} else {
|
||||
z = sha3(y);
|
||||
a = x;
|
||||
}
|
||||
r_a = a;
|
||||
r_d = d;
|
||||
}
|
||||
}
|
||||
)";
|
||||
compileBothVersions(sourceCode);
|
||||
compareVersions("f(uint256,bytes32)", 0, "abc");
|
||||
compareVersions("f(uint256,bytes32)", 8, "def");
|
||||
compareVersions("f(uint256,bytes32)", 10, "ghi");
|
||||
|
||||
m_optimize = true;
|
||||
bytes optimizedBytecode = compileAndRun(sourceCode, 0, "c");
|
||||
size_t numSHA3s = 0;
|
||||
eth::eachInstruction(optimizedBytecode, [&](Instruction _instr, u256 const&) {
|
||||
if (_instr == eth::Instruction::SHA3)
|
||||
numSHA3s++;
|
||||
});
|
||||
BOOST_CHECK_EQUAL(1, numSHA3s);
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_CASE(store_tags_as_unions)
|
||||
{
|
||||
// This calls the same function from two sources and both calls have a certain sha3 on
|
||||
// the stack at the same position.
|
||||
// Without storing tags as unions, the return from the shared function would not know where to
|
||||
// jump and thus all jumpdests are forced to clear their state and we do not know about the
|
||||
// sha3 anymore.
|
||||
// Note that, for now, this only works if the functions have the same number of return
|
||||
// parameters since otherwise, the return jump addresses are at different stack positions
|
||||
// which triggers the "unknown jump target" situation.
|
||||
char const* sourceCode = R"(
|
||||
contract test {
|
||||
bytes32 data;
|
||||
function f(uint x, bytes32 y) external returns (uint r_a, bytes32 r_d) {
|
||||
r_d = sha3(y);
|
||||
shared(y);
|
||||
r_d = sha3(y);
|
||||
r_a = 5;
|
||||
}
|
||||
function g(uint x, bytes32 y) external returns (uint r_a, bytes32 r_d) {
|
||||
r_d = sha3(y);
|
||||
shared(y);
|
||||
r_d = bytes32(uint(sha3(y)) + 2);
|
||||
r_a = 7;
|
||||
}
|
||||
function shared(bytes32 y) internal {
|
||||
data = sha3(y);
|
||||
}
|
||||
}
|
||||
)";
|
||||
compileBothVersions(sourceCode);
|
||||
compareVersions("f()", 7, "abc");
|
||||
|
||||
m_optimize = true;
|
||||
bytes optimizedBytecode = compileAndRun(sourceCode, 0, "test");
|
||||
size_t numSHA3s = 0;
|
||||
eth::eachInstruction(optimizedBytecode, [&](Instruction _instr, u256 const&) {
|
||||
if (_instr == eth::Instruction::SHA3)
|
||||
numSHA3s++;
|
||||
});
|
||||
BOOST_CHECK_EQUAL(2, numSHA3s);
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_CASE(cse_intermediate_swap)
|
||||
{
|
||||
eth::KnownState state;
|
||||
@ -868,6 +975,67 @@ BOOST_AUTO_TEST_CASE(control_flow_graph_do_not_remove_returned_to)
|
||||
checkCFG(input, {u256(2)});
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_CASE(block_deduplicator)
|
||||
{
|
||||
AssemblyItems input{
|
||||
AssemblyItem(PushTag, 2),
|
||||
AssemblyItem(PushTag, 1),
|
||||
AssemblyItem(PushTag, 3),
|
||||
u256(6),
|
||||
eth::Instruction::SWAP3,
|
||||
eth::Instruction::JUMP,
|
||||
AssemblyItem(Tag, 1),
|
||||
u256(6),
|
||||
eth::Instruction::SWAP3,
|
||||
eth::Instruction::JUMP,
|
||||
AssemblyItem(Tag, 2),
|
||||
u256(6),
|
||||
eth::Instruction::SWAP3,
|
||||
eth::Instruction::JUMP,
|
||||
AssemblyItem(Tag, 3)
|
||||
};
|
||||
BlockDeduplicator dedup(input);
|
||||
dedup.deduplicate();
|
||||
|
||||
set<u256> pushTags;
|
||||
for (AssemblyItem const& item: input)
|
||||
if (item.type() == PushTag)
|
||||
pushTags.insert(item.data());
|
||||
BOOST_CHECK_EQUAL(pushTags.size(), 2);
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_CASE(block_deduplicator_loops)
|
||||
{
|
||||
AssemblyItems input{
|
||||
u256(0),
|
||||
eth::Instruction::SLOAD,
|
||||
AssemblyItem(PushTag, 1),
|
||||
AssemblyItem(PushTag, 2),
|
||||
eth::Instruction::JUMPI,
|
||||
eth::Instruction::JUMP,
|
||||
AssemblyItem(Tag, 1),
|
||||
u256(5),
|
||||
u256(6),
|
||||
eth::Instruction::SSTORE,
|
||||
AssemblyItem(PushTag, 1),
|
||||
eth::Instruction::JUMP,
|
||||
AssemblyItem(Tag, 2),
|
||||
u256(5),
|
||||
u256(6),
|
||||
eth::Instruction::SSTORE,
|
||||
AssemblyItem(PushTag, 2),
|
||||
eth::Instruction::JUMP,
|
||||
};
|
||||
BlockDeduplicator dedup(input);
|
||||
dedup.deduplicate();
|
||||
|
||||
set<u256> pushTags;
|
||||
for (AssemblyItem const& item: input)
|
||||
if (item.type() == PushTag)
|
||||
pushTags.insert(item.data());
|
||||
BOOST_CHECK_EQUAL(pushTags.size(), 1);
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_SUITE_END()
|
||||
|
||||
}
|
||||
|
@ -42,21 +42,25 @@ class ExecutionFramework
|
||||
public:
|
||||
ExecutionFramework() { g_logVerbosity = 0; }
|
||||
|
||||
bytes const& compileAndRunWthoutCheck(std::string const& _sourceCode, u256 const& _value = 0, std::string const& _contractName = "")
|
||||
{
|
||||
m_compiler.reset(false, m_addStandardSources);
|
||||
m_compiler.addSource("", _sourceCode);
|
||||
ETH_TEST_REQUIRE_NO_THROW(m_compiler.compile(m_optimize), "Compiling contract failed");
|
||||
bytes code = m_compiler.getBytecode(_contractName);
|
||||
sendMessage(code, true, _value);
|
||||
return m_output;
|
||||
}
|
||||
|
||||
bytes const& compileAndRun(std::string const& _sourceCode, u256 const& _value = 0, std::string const& _contractName = "")
|
||||
{
|
||||
dev::solidity::CompilerStack compiler(m_addStandardSources);
|
||||
compiler.addSource("", _sourceCode);
|
||||
ETH_TEST_REQUIRE_NO_THROW(compiler.compile(m_optimize), "Compiling contract failed");
|
||||
|
||||
bytes code = compiler.getBytecode(_contractName);
|
||||
sendMessage(code, true, _value);
|
||||
compileAndRunWthoutCheck(_sourceCode, _value, _contractName);
|
||||
BOOST_REQUIRE(!m_output.empty());
|
||||
return m_output;
|
||||
}
|
||||
|
||||
template <class... Args>
|
||||
bytes const& callContractFunctionWithValue(std::string _sig, u256 const& _value,
|
||||
Args const&... _arguments)
|
||||
bytes const& callContractFunctionWithValue(std::string _sig, u256 const& _value, Args const&... _arguments)
|
||||
{
|
||||
FixedHash<4> hash(dev::sha3(_sig));
|
||||
sendMessage(hash.asBytes() + encodeArgs(_arguments...), false, _value);
|
||||
@ -74,21 +78,30 @@ public:
|
||||
{
|
||||
bytes solidityResult = callContractFunction(_sig, _arguments...);
|
||||
bytes cppResult = callCppAndEncodeResult(_cppFunction, _arguments...);
|
||||
BOOST_CHECK_MESSAGE(solidityResult == cppResult, "Computed values do not match."
|
||||
"\nSolidity: " + toHex(solidityResult) + "\nC++: " + toHex(cppResult));
|
||||
BOOST_CHECK_MESSAGE(
|
||||
solidityResult == cppResult,
|
||||
"Computed values do not match.\nSolidity: " +
|
||||
toHex(solidityResult) +
|
||||
"\nC++: " +
|
||||
toHex(cppResult));
|
||||
}
|
||||
|
||||
template <class CppFunction, class... Args>
|
||||
void testSolidityAgainstCppOnRange(std::string _sig, CppFunction const& _cppFunction,
|
||||
u256 const& _rangeStart, u256 const& _rangeEnd)
|
||||
void testSolidityAgainstCppOnRange(std::string _sig, CppFunction const& _cppFunction, u256 const& _rangeStart, u256 const& _rangeEnd)
|
||||
{
|
||||
for (u256 argument = _rangeStart; argument < _rangeEnd; ++argument)
|
||||
{
|
||||
bytes solidityResult = callContractFunction(_sig, argument);
|
||||
bytes cppResult = callCppAndEncodeResult(_cppFunction, argument);
|
||||
BOOST_CHECK_MESSAGE(solidityResult == cppResult, "Computed values do not match."
|
||||
"\nSolidity: " + toHex(solidityResult) + "\nC++: " + toHex(cppResult) +
|
||||
"\nArgument: " + toHex(encode(argument)));
|
||||
BOOST_CHECK_MESSAGE(
|
||||
solidityResult == cppResult,
|
||||
"Computed values do not match.\nSolidity: " +
|
||||
toHex(solidityResult) +
|
||||
"\nC++: " +
|
||||
toHex(cppResult) +
|
||||
"\nArgument: " +
|
||||
toHex(encode(argument))
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@ -135,8 +148,10 @@ protected:
|
||||
{
|
||||
m_state.addBalance(m_sender, _value); // just in case
|
||||
eth::Executive executive(m_state, eth::LastHashes(), 0);
|
||||
eth::Transaction t = _isCreation ? eth::Transaction(_value, m_gasPrice, m_gas, _data, 0, KeyPair::create().sec())
|
||||
: eth::Transaction(_value, m_gasPrice, m_gas, m_contractAddress, _data, 0, KeyPair::create().sec());
|
||||
eth::Transaction t =
|
||||
_isCreation ?
|
||||
eth::Transaction(_value, m_gasPrice, m_gas, _data, 0, KeyPair::create().sec()) :
|
||||
eth::Transaction(_value, m_gasPrice, m_gas, m_contractAddress, _data, 0, KeyPair::create().sec());
|
||||
bytes transactionRLP = t.rlp();
|
||||
try
|
||||
{
|
||||
@ -155,17 +170,19 @@ protected:
|
||||
else
|
||||
{
|
||||
BOOST_REQUIRE(m_state.addressHasCode(m_contractAddress));
|
||||
BOOST_REQUIRE(!executive.call(m_contractAddress, m_contractAddress, m_sender, _value, m_gasPrice, &_data, m_gas, m_sender));
|
||||
BOOST_REQUIRE(!executive.call(m_contractAddress, m_sender, _value, m_gasPrice, &_data, m_gas));
|
||||
}
|
||||
BOOST_REQUIRE(executive.go());
|
||||
m_state.noteSending(m_sender);
|
||||
executive.finalize();
|
||||
m_gasUsed = executive.gasUsed();
|
||||
m_output = executive.out().toVector();
|
||||
m_logs = executive.logs();
|
||||
}
|
||||
|
||||
bool m_optimize = false;
|
||||
bool m_addStandardSources = false;
|
||||
dev::solidity::CompilerStack m_compiler;
|
||||
Address m_sender;
|
||||
Address m_contractAddress;
|
||||
eth::State m_state;
|
||||
@ -173,6 +190,7 @@ protected:
|
||||
u256 const m_gas = 100000000;
|
||||
bytes m_output;
|
||||
eth::LogEntries m_logs;
|
||||
u256 m_gasUsed;
|
||||
};
|
||||
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user