Merge remote-tracking branch 'upstream/develop' into feature/vm_gas_counter_refactor

Conflicts:
	libethereum/Executive.h
This commit is contained in:
Paweł Bylica 2015-06-02 11:57:13 +02:00
commit 6a64d18780
10 changed files with 279 additions and 220 deletions

View File

@ -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)

View File

@ -328,7 +328,7 @@ void ImportTest::exportTest(bytes const& _output, State const& _statePost)
{
// export output
m_TestObject["out"] = _output.size() > 4096 ? "#" + toString(_output.size()) : 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());
@ -588,7 +588,7 @@ void userDefinedTest(std::function<void(json_spirit::mValue&, bool)> doTests)
oSingleTest[pos->first] = pos->second;
json_spirit::mValue v_singleTest(oSingleTest);
doTests(v_singleTest, false);
doTests(v_singleTest, test::Options::get().fillTests);
}
catch (Exception const& _e)
{
@ -760,6 +760,8 @@ Options::Options()
else
singleTestName = std::move(name1);
}
else if (arg == "--fulloutput")
fulloutput = true;
}
}
@ -769,7 +771,6 @@ Options const& Options::get()
return instance;
}
LastHashes lastHashes(u256 _currentBlockNumber)
{
LastHashes ret;

View File

@ -184,6 +184,7 @@ public:
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
/// @{

View File

@ -23,8 +23,9 @@
#include <test/libsolidity/solidityExecutionFramework.h>
#include <libevmasm/GasMeter.h>
#include <libevmasm/KnownState.h>
#include <libevmasm/PathGasMeter.h>
#include <libsolidity/AST.h>
#include <libsolidity/StructuralGasEstimator.h>
#include <libsolidity/GasEstimator.h>
#include <libsolidity/SourceReferenceFormatter.h>
using namespace std;
@ -47,30 +48,47 @@ public:
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})),
m_gasCosts = GasEstimator::breakToStatementLevel(
GasEstimator::structuralEstimation(*items, vector<ASTNode const*>({&sourceUnit})),
{&sourceUnit}
);
}
void testCreationTimeGas(string const& _sourceCode, string const& _contractName = "")
void testCreationTimeGas(string const& _sourceCode)
{
compileAndRun(_sourceCode);
auto state = make_shared<KnownState>();
GasMeter meter(state);
GasMeter::GasConsumption gas;
for (AssemblyItem const& item: *m_compiler.getAssemblyItems(_contractName))
gas += meter.estimateMax(item);
u256 bytecodeSize(m_compiler.getRuntimeBytecode(_contractName).size());
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;
};
@ -149,6 +167,67 @@ BOOST_AUTO_TEST_CASE(updating_store)
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()
}

View File

@ -568,6 +568,33 @@ BOOST_AUTO_TEST_CASE(return_param_in_abi)
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()
}

View File

@ -1,192 +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::ISZERO),
byte(Instruction::PUSH1), byte(0x0f + shift), // "false" target
byte(Instruction::JUMPI),
// "if" body
byte(Instruction::PUSH1), 0x4d,
byte(Instruction::POP),
byte(Instruction::PUSH1), byte(0x21 + shift),
byte(Instruction::JUMP),
// new check "else if" condition
byte(Instruction::JUMPDEST),
byte(Instruction::DUP1),
byte(Instruction::ISZERO),
byte(Instruction::ISZERO),
byte(Instruction::PUSH1), byte(0x1c + shift),
byte(Instruction::JUMPI),
// "else if" body
byte(Instruction::PUSH1), 0x4e,
byte(Instruction::POP),
byte(Instruction::PUSH1), byte(0x20 + shift),
byte(Instruction::JUMP),
// "else" body
byte(Instruction::JUMPDEST),
byte(Instruction::PUSH1), 0x4f,
byte(Instruction::POP),
});
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

View File

@ -4080,7 +4080,6 @@ BOOST_AUTO_TEST_CASE(struct_delete_member)
}
)";
compileAndRun(sourceCode, 0, "test");
auto res = callContractFunction("deleteMember()");
BOOST_CHECK(callContractFunction("deleteMember()") == encodeArgs(0));
}
@ -4106,10 +4105,73 @@ BOOST_AUTO_TEST_CASE(struct_delete_struct_in_mapping)
}
)";
compileAndRun(sourceCode, 0, "test");
auto res = callContractFunction("deleteIt()");
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()
}

View File

@ -1783,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()
}

View File

@ -1004,6 +1004,38 @@ BOOST_AUTO_TEST_CASE(block_deduplicator)
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()
}

View File

@ -42,21 +42,25 @@ class ExecutionFramework
public:
ExecutionFramework() { g_logVerbosity = 0; }
bytes const& compileAndRun(std::string const& _sourceCode, u256 const& _value = 0, std::string const& _contractName = "")
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 = "")
{
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
{