Browse Source

Padding for ABI types.

cl-refactor
Christian 10 years ago
parent
commit
de77918d05
  1. 13
      libsolidity/Compiler.cpp
  2. 19
      libsolidity/CompilerUtils.cpp
  3. 15
      libsolidity/CompilerUtils.h
  4. 27
      libsolidity/ExpressionCompiler.cpp
  5. 6
      libsolidity/ExpressionCompiler.h
  6. 3
      libsolidity/Types.h
  7. 135
      test/SolidityEndToEndTest.cpp
  8. 41
      test/solidityExecutionFramework.h

13
libsolidity/Compiler.cpp

@ -95,7 +95,7 @@ void Compiler::appendConstructorCall(FunctionDefinition const& _constructor)
// copy constructor arguments from code to memory and then to stack, they are supplied after the actual program // copy constructor arguments from code to memory and then to stack, they are supplied after the actual program
unsigned argumentSize = 0; unsigned argumentSize = 0;
for (ASTPointer<VariableDeclaration> const& var: _constructor.getParameters()) for (ASTPointer<VariableDeclaration> const& var: _constructor.getParameters())
argumentSize += var->getType()->getCalldataEncodedSize(); argumentSize += CompilerUtils::getPaddedSize(var->getType()->getCalldataEncodedSize());
if (argumentSize > 0) if (argumentSize > 0)
{ {
m_context << u256(argumentSize); m_context << u256(argumentSize);
@ -159,9 +159,9 @@ unsigned Compiler::appendCalldataUnpacker(FunctionDefinition const& _function, b
BOOST_THROW_EXCEPTION(CompilerError() BOOST_THROW_EXCEPTION(CompilerError()
<< errinfo_sourceLocation(var->getLocation()) << errinfo_sourceLocation(var->getLocation())
<< errinfo_comment("Type " + var->getType()->toString() + " not yet supported.")); << errinfo_comment("Type " + var->getType()->toString() + " not yet supported."));
bool leftAligned = var->getType()->getCategory() == Type::Category::STRING; bool const leftAligned = var->getType()->getCategory() == Type::Category::STRING;
CompilerUtils(m_context).loadFromMemory(dataOffset, numBytes, leftAligned, !_fromMemory); bool const padToWords = true;
dataOffset += numBytes; dataOffset += CompilerUtils(m_context).loadFromMemory(dataOffset, numBytes, leftAligned, !_fromMemory, padToWords);
} }
return dataOffset; return dataOffset;
} }
@ -181,10 +181,11 @@ void Compiler::appendReturnValuePacker(FunctionDefinition const& _function)
<< errinfo_sourceLocation(parameters[i]->getLocation()) << errinfo_sourceLocation(parameters[i]->getLocation())
<< errinfo_comment("Type " + paramType.toString() + " not yet supported.")); << errinfo_comment("Type " + paramType.toString() + " not yet supported."));
CompilerUtils(m_context).copyToStackTop(stackDepth, paramType); CompilerUtils(m_context).copyToStackTop(stackDepth, paramType);
ExpressionCompiler::appendTypeConversion(m_context, paramType, paramType, true);
bool const leftAligned = paramType.getCategory() == Type::Category::STRING; bool const leftAligned = paramType.getCategory() == Type::Category::STRING;
CompilerUtils(m_context).storeInMemory(dataOffset, numBytes, leftAligned); bool const padToWords = true;
dataOffset += CompilerUtils(m_context).storeInMemory(dataOffset, numBytes, leftAligned, padToWords);
stackDepth -= paramType.getSizeOnStack(); stackDepth -= paramType.getSizeOnStack();
dataOffset += numBytes;
} }
// note that the stack is not cleaned up here // note that the stack is not cleaned up here
m_context << u256(dataOffset) << u256(0) << eth::Instruction::RETURN; m_context << u256(dataOffset) << u256(0) << eth::Instruction::RETURN;

19
libsolidity/CompilerUtils.cpp

@ -33,17 +33,21 @@ namespace solidity
const unsigned int CompilerUtils::dataStartOffset = 4; const unsigned int CompilerUtils::dataStartOffset = 4;
void CompilerUtils::loadFromMemory(unsigned _offset, unsigned _bytes, bool _leftAligned, bool _fromCalldata) unsigned CompilerUtils::loadFromMemory(unsigned _offset, unsigned _bytes, bool _leftAligned,
bool _fromCalldata, bool _padToWordBoundaries)
{ {
if (_bytes == 0) if (_bytes == 0)
{ {
m_context << u256(0); m_context << u256(0);
return; return 0;
} }
eth::Instruction load = _fromCalldata ? eth::Instruction::CALLDATALOAD : eth::Instruction::MLOAD; eth::Instruction load = _fromCalldata ? eth::Instruction::CALLDATALOAD : eth::Instruction::MLOAD;
solAssert(_bytes <= 32, "Memory load of more than 32 bytes requested."); solAssert(_bytes <= 32, "Memory load of more than 32 bytes requested.");
if (_bytes == 32) if (_bytes == 32 || _padToWordBoundaries)
{
m_context << u256(_offset) << load; m_context << u256(_offset) << load;
return 32;
}
else else
{ {
// load data and add leading or trailing zeros by dividing/multiplying depending on alignment // load data and add leading or trailing zeros by dividing/multiplying depending on alignment
@ -54,21 +58,24 @@ void CompilerUtils::loadFromMemory(unsigned _offset, unsigned _bytes, bool _left
m_context << u256(_offset) << load << eth::Instruction::DIV; m_context << u256(_offset) << load << eth::Instruction::DIV;
if (_leftAligned) if (_leftAligned)
m_context << eth::Instruction::MUL; m_context << eth::Instruction::MUL;
return _bytes;
} }
} }
void CompilerUtils::storeInMemory(unsigned _offset, unsigned _bytes, bool _leftAligned) unsigned CompilerUtils::storeInMemory(unsigned _offset, unsigned _bytes, bool _leftAligned,
bool _padToWordBoundaries)
{ {
if (_bytes == 0) if (_bytes == 0)
{ {
m_context << eth::Instruction::POP; m_context << eth::Instruction::POP;
return; return 0;
} }
solAssert(_bytes <= 32, "Memory store of more than 32 bytes requested."); solAssert(_bytes <= 32, "Memory store of more than 32 bytes requested.");
if (_bytes != 32 && !_leftAligned) if (_bytes != 32 && !_leftAligned && !_padToWordBoundaries)
// shift the value accordingly before storing // shift the value accordingly before storing
m_context << (u256(1) << ((32 - _bytes) * 8)) << eth::Instruction::MUL; m_context << (u256(1) << ((32 - _bytes) * 8)) << eth::Instruction::MUL;
m_context << u256(_offset) << eth::Instruction::MSTORE; m_context << u256(_offset) << eth::Instruction::MSTORE;
return _padToWordBoundaries ? 32 : _bytes;
} }
void CompilerUtils::moveToStackVariable(VariableDeclaration const& _variable) void CompilerUtils::moveToStackVariable(VariableDeclaration const& _variable)

15
libsolidity/CompilerUtils.h

@ -40,12 +40,23 @@ public:
/// @param _bytes number of bytes to load /// @param _bytes number of bytes to load
/// @param _leftAligned if true, store left aligned on stack (otherwise right aligned) /// @param _leftAligned if true, store left aligned on stack (otherwise right aligned)
/// @param _fromCalldata if true, load from calldata, not from memory /// @param _fromCalldata if true, load from calldata, not from memory
void loadFromMemory(unsigned _offset, unsigned _bytes = 32, bool _leftAligned = false, bool _fromCalldata = false); /// @param _padToWordBoundaries if true, assume the data is padded to word (32 byte) boundaries
/// @returns the number of bytes consumed in memory (can be different from _bytes if
/// _padToWordBoundaries is true)
unsigned loadFromMemory(unsigned _offset, unsigned _bytes = 32, bool _leftAligned = false,
bool _fromCalldata = false, bool _padToWordBoundaries = false);
/// Stores data from stack in memory. /// Stores data from stack in memory.
/// @param _offset offset in memory /// @param _offset offset in memory
/// @param _bytes number of bytes to store /// @param _bytes number of bytes to store
/// @param _leftAligned if true, data is left aligned on stack (otherwise right aligned) /// @param _leftAligned if true, data is left aligned on stack (otherwise right aligned)
void storeInMemory(unsigned _offset, unsigned _bytes = 32, bool _leftAligned = false); /// @param _padToWordBoundaries if true, pad the data to word (32 byte) boundaries
/// @returns the number of bytes written to memory (can be different from _bytes if
/// _padToWordBoundaries is true)
unsigned storeInMemory(unsigned _offset, unsigned _bytes = 32, bool _leftAligned = false,
bool _padToWordBoundaries = false);
/// @returns _size rounded up to the next multiple of 32 (the number of bytes occupied in the
/// padded calldata)
static unsigned getPaddedSize(unsigned _size) { return ((_size + 31) / 32) * 32; }
/// Moves the value that is at the top of the stack to a stack variable. /// Moves the value that is at the top of the stack to a stack variable.
void moveToStackVariable(VariableDeclaration const& _variable); void moveToStackVariable(VariableDeclaration const& _variable);

27
libsolidity/ExpressionCompiler.cpp

@ -41,11 +41,11 @@ void ExpressionCompiler::compileExpression(CompilerContext& _context, Expression
_expression.accept(compiler); _expression.accept(compiler);
} }
void ExpressionCompiler::appendTypeConversion(CompilerContext& _context, void ExpressionCompiler::appendTypeConversion(CompilerContext& _context, Type const& _typeOnStack,
Type const& _typeOnStack, Type const& _targetType) Type const& _targetType, bool _cleanupNeeded)
{ {
ExpressionCompiler compiler(_context); ExpressionCompiler compiler(_context);
compiler.appendTypeConversion(_typeOnStack, _targetType); compiler.appendTypeConversion(_typeOnStack, _targetType, _cleanupNeeded);
} }
bool ExpressionCompiler::visit(Assignment const& _assignment) bool ExpressionCompiler::visit(Assignment const& _assignment)
@ -295,7 +295,6 @@ bool ExpressionCompiler::visit(FunctionCall const& _functionCall)
FunctionCallOptions options; FunctionCallOptions options;
options.bare = true; options.bare = true;
options.obtainAddress = [&]() { m_context << contractAddress; }; options.obtainAddress = [&]() { m_context << contractAddress; };
options.packDensely = false;
appendExternalFunctionCall(function, arguments, options); appendExternalFunctionCall(function, arguments, options);
break; break;
} }
@ -327,15 +326,15 @@ bool ExpressionCompiler::visit(NewExpression const& _newExpression)
for (unsigned i = 0; i < arguments.size(); ++i) for (unsigned i = 0; i < arguments.size(); ++i)
{ {
arguments[i]->accept(*this); arguments[i]->accept(*this);
appendTypeConversion(*arguments[i]->getType(), *types[i]); appendTypeConversion(*arguments[i]->getType(), *types[i], true);
unsigned const numBytes = types[i]->getCalldataEncodedSize(); unsigned const numBytes = types[i]->getCalldataEncodedSize();
if (numBytes > 32) if (numBytes > 32)
BOOST_THROW_EXCEPTION(CompilerError() BOOST_THROW_EXCEPTION(CompilerError()
<< errinfo_sourceLocation(arguments[i]->getLocation()) << errinfo_sourceLocation(arguments[i]->getLocation())
<< errinfo_comment("Type " + types[i]->toString() + " not yet supported.")); << errinfo_comment("Type " + types[i]->toString() + " not yet supported."));
bool const leftAligned = types[i]->getCategory() == Type::Category::STRING; bool const leftAligned = types[i]->getCategory() == Type::Category::STRING;
CompilerUtils(m_context).storeInMemory(dataOffset, numBytes, leftAligned); bool const padToWords = true;
dataOffset += numBytes; dataOffset += CompilerUtils(m_context).storeInMemory(dataOffset, numBytes, leftAligned, padToWords);
} }
// size, offset, endowment // size, offset, endowment
m_context << u256(dataOffset) << u256(0) << u256(0) << eth::Instruction::CREATE; m_context << u256(dataOffset) << u256(0) << u256(0) << eth::Instruction::CREATE;
@ -634,22 +633,20 @@ void ExpressionCompiler::appendExternalFunctionCall(FunctionType const& _functio
{ {
_arguments[i]->accept(*this); _arguments[i]->accept(*this);
Type const& type = *_functionType.getParameterTypes()[i]; Type const& type = *_functionType.getParameterTypes()[i];
appendTypeConversion(*_arguments[i]->getType(), type); appendTypeConversion(*_arguments[i]->getType(), type, true);
unsigned const numBytes = _options.packDensely ? type.getCalldataEncodedSize() : 32; unsigned const numBytes = type.getCalldataEncodedSize();
if (numBytes == 0 || numBytes > 32) if (numBytes == 0 || numBytes > 32)
BOOST_THROW_EXCEPTION(CompilerError() BOOST_THROW_EXCEPTION(CompilerError()
<< errinfo_sourceLocation(_arguments[i]->getLocation()) << errinfo_sourceLocation(_arguments[i]->getLocation())
<< errinfo_comment("Type " + type.toString() + " not yet supported.")); << errinfo_comment("Type " + type.toString() + " not yet supported."));
bool const leftAligned = type.getCategory() == Type::Category::STRING; bool const leftAligned = type.getCategory() == Type::Category::STRING;
CompilerUtils(m_context).storeInMemory(dataOffset, numBytes, leftAligned); bool const padToWords = true;
dataOffset += numBytes; dataOffset += CompilerUtils(m_context).storeInMemory(dataOffset, numBytes, leftAligned, padToWords);
} }
//@todo only return the first return value for now //@todo only return the first return value for now
Type const* firstType = _functionType.getReturnParameterTypes().empty() ? nullptr : Type const* firstType = _functionType.getReturnParameterTypes().empty() ? nullptr :
_functionType.getReturnParameterTypes().front().get(); _functionType.getReturnParameterTypes().front().get();
unsigned retSize = firstType ? firstType->getCalldataEncodedSize() : 0; unsigned retSize = firstType ? CompilerUtils::getPaddedSize(firstType->getCalldataEncodedSize()) : 0;
if (!_options.packDensely && retSize > 0)
retSize = 32;
// CALL arguments: outSize, outOff, inSize, inOff, value, addr, gas (stack top) // CALL arguments: outSize, outOff, inSize, inOff, value, addr, gas (stack top)
m_context << u256(retSize) << u256(0) << u256(dataOffset) << u256(0); m_context << u256(retSize) << u256(0) << u256(dataOffset) << u256(0);
if (_options.obtainValue) if (_options.obtainValue)
@ -666,7 +663,7 @@ void ExpressionCompiler::appendExternalFunctionCall(FunctionType const& _functio
if (retSize > 0) if (retSize > 0)
{ {
bool const leftAligned = firstType->getCategory() == Type::Category::STRING; bool const leftAligned = firstType->getCategory() == Type::Category::STRING;
CompilerUtils(m_context).loadFromMemory(0, retSize, leftAligned); CompilerUtils(m_context).loadFromMemory(0, retSize, leftAligned, false, true);
} }
} }

6
libsolidity/ExpressionCompiler.h

@ -51,7 +51,8 @@ public:
static void compileExpression(CompilerContext& _context, Expression const& _expression, bool _optimize = false); static void compileExpression(CompilerContext& _context, Expression const& _expression, bool _optimize = false);
/// Appends code to remove dirty higher order bits in case of an implicit promotion to a wider type. /// Appends code to remove dirty higher order bits in case of an implicit promotion to a wider type.
static void appendTypeConversion(CompilerContext& _context, Type const& _typeOnStack, Type const& _targetType); static void appendTypeConversion(CompilerContext& _context, Type const& _typeOnStack,
Type const& _targetType, bool _cleanupNeeded = false);
private: private:
explicit ExpressionCompiler(CompilerContext& _compilerContext, bool _optimize = false): explicit ExpressionCompiler(CompilerContext& _compilerContext, bool _optimize = false):
@ -96,9 +97,6 @@ private:
std::function<void()> obtainValue; std::function<void()> obtainValue;
/// If true, do not prepend function index to call data /// If true, do not prepend function index to call data
bool bare = false; bool bare = false;
/// If false, use calling convention that all arguments and return values are packed as
/// 32 byte values with padding.
bool packDensely = true;
}; };
/// Appends code to call a function of the given type with the given arguments. /// Appends code to call a function of the given type with the given arguments.

3
libsolidity/Types.h

@ -115,7 +115,8 @@ public:
virtual bool operator!=(Type const& _other) const { return !this->operator ==(_other); } virtual bool operator!=(Type const& _other) const { return !this->operator ==(_other); }
/// @returns number of bytes used by this type when encoded for CALL, or 0 if the encoding /// @returns number of bytes used by this type when encoded for CALL, or 0 if the encoding
/// is not a simple big-endian encoding or the type cannot be stored on the stack. /// is not a simple big-endian encoding or the type cannot be stored in calldata.
/// Note that irrespective of this size, each calldata element is padded to a multiple of 32 bytes.
virtual unsigned getCalldataEncodedSize() const { return 0; } virtual unsigned getCalldataEncodedSize() const { return 0; }
/// @returns number of bytes required to hold this value in storage. /// @returns number of bytes required to hold this value in storage.
/// For dynamically "allocated" types, it returns the size of the statically allocated head, /// For dynamically "allocated" types, it returns the size of the statically allocated head,

135
test/SolidityEndToEndTest.cpp

@ -331,10 +331,23 @@ BOOST_AUTO_TEST_CASE(packing_unpacking_types)
" }\n" " }\n"
"}\n"; "}\n";
compileAndRun(sourceCode); compileAndRun(sourceCode);
BOOST_CHECK(callContractFunction("run(bool,uint32,uint64)", fromHex("01""0f0f0f0f""f0f0f0f0f0f0f0f0")) BOOST_CHECK(callContractFunction("run(bool,uint32,uint64)", true, fromHex("0f0f0f0f"), fromHex("f0f0f0f0f0f0f0f0"))
== fromHex("00000000000000000000000000000000000000""01""f0f0f0f0""0f0f0f0f0f0f0f0f")); == fromHex("00000000000000000000000000000000000000""01""f0f0f0f0""0f0f0f0f0f0f0f0f"));
} }
BOOST_AUTO_TEST_CASE(packing_signed_types)
{
char const* sourceCode = "contract test {\n"
" function run() returns(int8 y) {\n"
" uint8 x = 0xfa;\n"
" return int8(x);\n"
" }\n"
"}\n";
compileAndRun(sourceCode);
BOOST_CHECK(callContractFunction("run()")
== fromHex("fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa"));
}
BOOST_AUTO_TEST_CASE(multiple_return_values) BOOST_AUTO_TEST_CASE(multiple_return_values)
{ {
char const* sourceCode = "contract test {\n" char const* sourceCode = "contract test {\n"
@ -343,8 +356,7 @@ BOOST_AUTO_TEST_CASE(multiple_return_values)
" }\n" " }\n"
"}\n"; "}\n";
compileAndRun(sourceCode); compileAndRun(sourceCode);
BOOST_CHECK(callContractFunction("run(bool,uint256)", bytes(1, 1) + toBigEndian(u256(0xcd))) BOOST_CHECK(callContractFunction("run(bool,uint256)", true, 0xcd) == encodeArgs(0xcd, true, 0));
== toBigEndian(u256(0xcd)) + bytes(1, 1) + toBigEndian(u256(0)));
} }
BOOST_AUTO_TEST_CASE(short_circuiting) BOOST_AUTO_TEST_CASE(short_circuiting)
@ -450,20 +462,8 @@ BOOST_AUTO_TEST_CASE(strings)
" }\n" " }\n"
"}\n"; "}\n";
compileAndRun(sourceCode); compileAndRun(sourceCode);
bytes expectation(32, 0); BOOST_CHECK(callContractFunction("fixed()") == encodeArgs(string("abc\0\xff__", 7)));
expectation[0] = byte('a'); BOOST_CHECK(callContractFunction("pipeThrough(string2,bool)", string("\0\x02", 2), true) == encodeArgs(string("\0\x2", 2), true));
expectation[1] = byte('b');
expectation[2] = byte('c');
expectation[3] = byte(0);
expectation[4] = byte(0xff);
expectation[5] = byte('_');
expectation[6] = byte('_');
BOOST_CHECK(callContractFunction("fixed()", bytes()) == expectation);
expectation = bytes(17, 0);
expectation[0] = 0;
expectation[1] = 2;
expectation[16] = 1;
BOOST_CHECK(callContractFunction("pipeThrough(string2,bool)", bytes({0x00, 0x02, 0x01})) == expectation);
} }
BOOST_AUTO_TEST_CASE(empty_string_on_stack) BOOST_AUTO_TEST_CASE(empty_string_on_stack)
@ -477,7 +477,7 @@ BOOST_AUTO_TEST_CASE(empty_string_on_stack)
" }\n" " }\n"
"}\n"; "}\n";
compileAndRun(sourceCode); compileAndRun(sourceCode);
BOOST_CHECK(callContractFunction("run(string0,uint8)", bytes(1, 0x02)) == bytes({0x00, 0x02, 0x61/*'a'*/, 0x62/*'b'*/, 0x63/*'c'*/, 0x00})); BOOST_CHECK(callContractFunction("run(string0,uint8)", string(), byte(0x02)) == encodeArgs(0x2, string(""), string("abc\0")));
} }
BOOST_AUTO_TEST_CASE(state_smoke_test) BOOST_AUTO_TEST_CASE(state_smoke_test)
@ -495,14 +495,14 @@ BOOST_AUTO_TEST_CASE(state_smoke_test)
" }\n" " }\n"
"}\n"; "}\n";
compileAndRun(sourceCode); compileAndRun(sourceCode);
BOOST_CHECK(callContractFunction("get(uint8)", bytes(1, 0x00)) == toBigEndian(u256(0))); BOOST_CHECK(callContractFunction("get(uint8)", byte(0x00)) == encodeArgs(0));
BOOST_CHECK(callContractFunction("get(uint8)", bytes(1, 0x01)) == toBigEndian(u256(0))); BOOST_CHECK(callContractFunction("get(uint8)", byte(0x01)) == encodeArgs(0));
BOOST_CHECK(callContractFunction("set(uint8,uint256)", bytes(1, 0x00) + toBigEndian(u256(0x1234))) == bytes()); BOOST_CHECK(callContractFunction("set(uint8,uint256)", byte(0x00), 0x1234) == encodeArgs());
BOOST_CHECK(callContractFunction("set(uint8,uint256)", bytes(1, 0x01) + toBigEndian(u256(0x8765))) == bytes()); BOOST_CHECK(callContractFunction("set(uint8,uint256)", byte(0x01), 0x8765) == encodeArgs());
BOOST_CHECK(callContractFunction("get(uint8)", bytes(1, 0x00)) == toBigEndian(u256(0x1234))); BOOST_CHECK(callContractFunction("get(uint8)", byte( 0x00)) == encodeArgs(0x1234));
BOOST_CHECK(callContractFunction("get(uint8)", bytes(1, 0x01)) == toBigEndian(u256(0x8765))); BOOST_CHECK(callContractFunction("get(uint8)", byte(0x01)) == encodeArgs(0x8765));
BOOST_CHECK(callContractFunction("set(uint8,uint256)", bytes(1, 0x00) + toBigEndian(u256(0x3))) == bytes()); BOOST_CHECK(callContractFunction("set(uint8,uint256)", byte(0x00), 0x3) == encodeArgs());
BOOST_CHECK(callContractFunction("get(uint8)", bytes(1, 0x00)) == toBigEndian(u256(0x3))); BOOST_CHECK(callContractFunction("get(uint8)", byte(0x00)) == encodeArgs(0x3));
} }
BOOST_AUTO_TEST_CASE(compound_assign) BOOST_AUTO_TEST_CASE(compound_assign)
@ -553,22 +553,21 @@ BOOST_AUTO_TEST_CASE(simple_mapping)
"}"; "}";
compileAndRun(sourceCode); compileAndRun(sourceCode);
// msvc seems to have problems with initializer-list, when there is only 1 param in the list BOOST_CHECK(callContractFunction("get(uint8)", byte(0)) == encodeArgs(byte(0x00)));
BOOST_CHECK(callContractFunction("get(uint8)", bytes(1, 0x00)) == bytes(1, 0x00)); BOOST_CHECK(callContractFunction("get(uint8)", byte(0x01)) == encodeArgs(byte(0x00)));
BOOST_CHECK(callContractFunction("get(uint8)", bytes(1, 0x01)) == bytes(1, 0x00)); BOOST_CHECK(callContractFunction("get(uint8)", byte(0xa7)) == encodeArgs(byte(0x00)));
BOOST_CHECK(callContractFunction("get(uint8)", bytes(1, 0xa7)) == bytes(1, 0x00)); callContractFunction("set(uint8,uint8)", byte(0x01), byte(0xa1));
callContractFunction("set(uint8,uint8)", bytes({0x01, 0xa1})); BOOST_CHECK(callContractFunction("get(uint8)", byte(0x00)) == encodeArgs(byte(0x00)));
BOOST_CHECK(callContractFunction("get(uint8)", bytes(1, 0x00)) == bytes(1, 0x00)); BOOST_CHECK(callContractFunction("get(uint8)", byte(0x01)) == encodeArgs(byte(0xa1)));
BOOST_CHECK(callContractFunction("get(uint8)", bytes(1, 0x01)) == bytes(1, 0xa1)); BOOST_CHECK(callContractFunction("get(uint8)", byte(0xa7)) == encodeArgs(byte(0x00)));
BOOST_CHECK(callContractFunction("get(uint8)", bytes(1, 0xa7)) == bytes(1, 0x00)); callContractFunction("set(uint8,uint8)", byte(0x00), byte(0xef));
callContractFunction("set(uint8,uint8)", bytes({0x00, 0xef})); BOOST_CHECK(callContractFunction("get(uint8)", byte(0x00)) == encodeArgs(byte(0xef)));
BOOST_CHECK(callContractFunction("get(uint8)", bytes(1, 0x00)) == bytes(1, 0xef)); BOOST_CHECK(callContractFunction("get(uint8)", byte(0x01)) == encodeArgs(byte(0xa1)));
BOOST_CHECK(callContractFunction("get(uint8)", bytes(1, 0x01)) == bytes(1, 0xa1)); BOOST_CHECK(callContractFunction("get(uint8)", byte(0xa7)) == encodeArgs(byte(0x00)));
BOOST_CHECK(callContractFunction("get(uint8)", bytes(1, 0xa7)) == bytes(1, 0x00)); callContractFunction("set(uint8,uint8)", byte(0x01), byte(0x05));
callContractFunction("set(uint8,uint8)", bytes({0x01, 0x05})); BOOST_CHECK(callContractFunction("get(uint8)", byte(0x00)) == encodeArgs(byte(0xef)));
BOOST_CHECK(callContractFunction("get(uint8)", bytes(1, 0x00)) == bytes(1, 0xef)); BOOST_CHECK(callContractFunction("get(uint8)", byte(0x01)) == encodeArgs(byte(0x05)));
BOOST_CHECK(callContractFunction("get(uint8)", bytes(1, 0x01)) == bytes(1, 0x05)); BOOST_CHECK(callContractFunction("get(uint8)", byte(0xa7)) == encodeArgs(byte(0x00)));
BOOST_CHECK(callContractFunction("get(uint8)", bytes(1, 0xa7)) == bytes(1, 0x00));
} }
BOOST_AUTO_TEST_CASE(mapping_state) BOOST_AUTO_TEST_CASE(mapping_state)
@ -736,9 +735,9 @@ BOOST_AUTO_TEST_CASE(structs)
" }\n" " }\n"
"}\n"; "}\n";
compileAndRun(sourceCode); compileAndRun(sourceCode);
BOOST_CHECK(callContractFunction("check()") == bytes(1, 0x00)); BOOST_CHECK(callContractFunction("check()") == encodeArgs(false));
BOOST_CHECK(callContractFunction("set()") == bytes()); BOOST_CHECK(callContractFunction("set()") == bytes());
BOOST_CHECK(callContractFunction("check()") == bytes(1, 0x01)); BOOST_CHECK(callContractFunction("check()") == encodeArgs(true));
} }
BOOST_AUTO_TEST_CASE(struct_reference) BOOST_AUTO_TEST_CASE(struct_reference)
@ -764,9 +763,9 @@ BOOST_AUTO_TEST_CASE(struct_reference)
" }\n" " }\n"
"}\n"; "}\n";
compileAndRun(sourceCode); compileAndRun(sourceCode);
BOOST_CHECK(callContractFunction("check()") == bytes(1, 0x00)); BOOST_CHECK(callContractFunction("check()") == encodeArgs(false));
BOOST_CHECK(callContractFunction("set()") == bytes()); BOOST_CHECK(callContractFunction("set()") == bytes());
BOOST_CHECK(callContractFunction("check()") == bytes(1, 0x01)); BOOST_CHECK(callContractFunction("check()") == encodeArgs(true));
} }
BOOST_AUTO_TEST_CASE(constructor) BOOST_AUTO_TEST_CASE(constructor)
@ -799,7 +798,7 @@ BOOST_AUTO_TEST_CASE(balance)
" }\n" " }\n"
"}\n"; "}\n";
compileAndRun(sourceCode, 23); compileAndRun(sourceCode, 23);
BOOST_CHECK(callContractFunction("getBalance()") == toBigEndian(u256(23))); BOOST_CHECK(callContractFunction("getBalance()") == encodeArgs(23));
} }
BOOST_AUTO_TEST_CASE(blockchain) BOOST_AUTO_TEST_CASE(blockchain)
@ -812,7 +811,7 @@ BOOST_AUTO_TEST_CASE(blockchain)
" }\n" " }\n"
"}\n"; "}\n";
compileAndRun(sourceCode, 27); compileAndRun(sourceCode, 27);
BOOST_CHECK(callContractFunction("someInfo()", bytes{0}, u256(28)) == toBigEndian(u256(28)) + bytes(20, 0) + toBigEndian(u256(1))); BOOST_CHECK(callContractFunctionWithValue("someInfo()", 28) == encodeArgs(28, 0, 1));
} }
BOOST_AUTO_TEST_CASE(function_types) BOOST_AUTO_TEST_CASE(function_types)
@ -831,8 +830,8 @@ BOOST_AUTO_TEST_CASE(function_types)
" }\n" " }\n"
"}\n"; "}\n";
compileAndRun(sourceCode); compileAndRun(sourceCode);
BOOST_CHECK(callContractFunction("a(bool)", bytes{0}) == toBigEndian(u256(11))); BOOST_CHECK(callContractFunction("a(bool)", false) == encodeArgs(11));
BOOST_CHECK(callContractFunction("a(bool)", bytes{1}) == toBigEndian(u256(12))); BOOST_CHECK(callContractFunction("a(bool)", true) == encodeArgs(12));
} }
BOOST_AUTO_TEST_CASE(send_ether) BOOST_AUTO_TEST_CASE(send_ether)
@ -846,7 +845,7 @@ BOOST_AUTO_TEST_CASE(send_ether)
u256 amount(130); u256 amount(130);
compileAndRun(sourceCode, amount + 1); compileAndRun(sourceCode, amount + 1);
u160 address(23); u160 address(23);
BOOST_CHECK(callContractFunction("a(address,uint256)", address, amount) == toBigEndian(u256(1))); BOOST_CHECK(callContractFunction("a(address,uint256)", address, amount) == encodeArgs(1));
BOOST_CHECK_EQUAL(m_state.balance(address), amount); BOOST_CHECK_EQUAL(m_state.balance(address), amount);
} }
@ -1031,7 +1030,7 @@ BOOST_AUTO_TEST_CASE(ecrecover)
u256 r("0x73b1693892219d736caba55bdb67216e485557ea6b6af75f37096c9aa6a5a75f"); u256 r("0x73b1693892219d736caba55bdb67216e485557ea6b6af75f37096c9aa6a5a75f");
u256 s("0xeeb940b1d03b21e36b0e47e79769f095fe2ab855bd91e3a38756b7d75a9c4549"); u256 s("0xeeb940b1d03b21e36b0e47e79769f095fe2ab855bd91e3a38756b7d75a9c4549");
u160 addr("0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b"); u160 addr("0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b");
BOOST_CHECK(callContractFunction("a(hash256,uint8,hash256,hash256)", h, v, r, s) == toBigEndian(addr)); BOOST_CHECK(callContractFunction("a(hash256,uint8,hash256,hash256)", h, v, r, s) == encodeArgs(addr));
} }
BOOST_AUTO_TEST_CASE(inter_contract_calls) BOOST_AUTO_TEST_CASE(inter_contract_calls)
@ -1058,10 +1057,10 @@ BOOST_AUTO_TEST_CASE(inter_contract_calls)
u160 const helperAddress = m_contractAddress; u160 const helperAddress = m_contractAddress;
compileAndRun(sourceCode, 0, "Main"); compileAndRun(sourceCode, 0, "Main");
BOOST_REQUIRE(callContractFunction("setHelper(address)", helperAddress) == bytes()); BOOST_REQUIRE(callContractFunction("setHelper(address)", helperAddress) == bytes());
BOOST_REQUIRE(callContractFunction("getHelper()", helperAddress) == toBigEndian(helperAddress)); BOOST_REQUIRE(callContractFunction("getHelper()", helperAddress) == encodeArgs(helperAddress));
u256 a(3456789); u256 a(3456789);
u256 b("0x282837623374623234aa74"); u256 b("0x282837623374623234aa74");
BOOST_REQUIRE(callContractFunction("callHelper(uint256,uint256)", a, b) == toBigEndian(a * b)); BOOST_REQUIRE(callContractFunction("callHelper(uint256,uint256)", a, b) == encodeArgs(a * b));
} }
BOOST_AUTO_TEST_CASE(inter_contract_calls_with_complex_parameters) BOOST_AUTO_TEST_CASE(inter_contract_calls_with_complex_parameters)
@ -1088,11 +1087,11 @@ BOOST_AUTO_TEST_CASE(inter_contract_calls_with_complex_parameters)
u160 const helperAddress = m_contractAddress; u160 const helperAddress = m_contractAddress;
compileAndRun(sourceCode, 0, "Main"); compileAndRun(sourceCode, 0, "Main");
BOOST_REQUIRE(callContractFunction("setHelper(address)", helperAddress) == bytes()); BOOST_REQUIRE(callContractFunction("setHelper(address)", helperAddress) == bytes());
BOOST_REQUIRE(callContractFunction("getHelper()", helperAddress) == toBigEndian(helperAddress)); BOOST_REQUIRE(callContractFunction("getHelper()", helperAddress) == encodeArgs(helperAddress));
u256 a(3456789); u256 a(3456789);
u256 b("0x282837623374623234aa74"); u256 b("0x282837623374623234aa74");
BOOST_REQUIRE(callContractFunction("callHelper(uint256,bool,uint256)", a, true, b) == toBigEndian(a * 3)); BOOST_REQUIRE(callContractFunction("callHelper(uint256,bool,uint256)", a, true, b) == encodeArgs(a * 3));
BOOST_REQUIRE(callContractFunction("callHelper(uint256,bool,uint256)", a, false, b) == toBigEndian(b * 3)); BOOST_REQUIRE(callContractFunction("callHelper(uint256,bool,uint256)", a, false, b) == encodeArgs(b * 3));
} }
BOOST_AUTO_TEST_CASE(inter_contract_calls_accessing_this) BOOST_AUTO_TEST_CASE(inter_contract_calls_accessing_this)
@ -1119,8 +1118,8 @@ BOOST_AUTO_TEST_CASE(inter_contract_calls_accessing_this)
u160 const helperAddress = m_contractAddress; u160 const helperAddress = m_contractAddress;
compileAndRun(sourceCode, 0, "Main"); compileAndRun(sourceCode, 0, "Main");
BOOST_REQUIRE(callContractFunction("setHelper(address)", helperAddress) == bytes()); BOOST_REQUIRE(callContractFunction("setHelper(address)", helperAddress) == bytes());
BOOST_REQUIRE(callContractFunction("getHelper()", helperAddress) == toBigEndian(helperAddress)); BOOST_REQUIRE(callContractFunction("getHelper()", helperAddress) == encodeArgs(helperAddress));
BOOST_REQUIRE(callContractFunction("callHelper()") == toBigEndian(helperAddress)); BOOST_REQUIRE(callContractFunction("callHelper()") == encodeArgs(helperAddress));
} }
BOOST_AUTO_TEST_CASE(calls_to_this) BOOST_AUTO_TEST_CASE(calls_to_this)
@ -1150,10 +1149,10 @@ BOOST_AUTO_TEST_CASE(calls_to_this)
u160 const helperAddress = m_contractAddress; u160 const helperAddress = m_contractAddress;
compileAndRun(sourceCode, 0, "Main"); compileAndRun(sourceCode, 0, "Main");
BOOST_REQUIRE(callContractFunction("setHelper(address)", helperAddress) == bytes()); BOOST_REQUIRE(callContractFunction("setHelper(address)", helperAddress) == bytes());
BOOST_REQUIRE(callContractFunction("getHelper()", helperAddress) == toBigEndian(helperAddress)); BOOST_REQUIRE(callContractFunction("getHelper()", helperAddress) == encodeArgs(helperAddress));
u256 a(3456789); u256 a(3456789);
u256 b("0x282837623374623234aa74"); u256 b("0x282837623374623234aa74");
BOOST_REQUIRE(callContractFunction("callHelper(uint256,uint256)", a, b) == toBigEndian(a * b + 10)); BOOST_REQUIRE(callContractFunction("callHelper(uint256,uint256)", a, b) == encodeArgs(a * b + 10));
} }
BOOST_AUTO_TEST_CASE(inter_contract_calls_with_local_vars) BOOST_AUTO_TEST_CASE(inter_contract_calls_with_local_vars)
@ -1185,10 +1184,10 @@ BOOST_AUTO_TEST_CASE(inter_contract_calls_with_local_vars)
u160 const helperAddress = m_contractAddress; u160 const helperAddress = m_contractAddress;
compileAndRun(sourceCode, 0, "Main"); compileAndRun(sourceCode, 0, "Main");
BOOST_REQUIRE(callContractFunction("setHelper(address)", helperAddress) == bytes()); BOOST_REQUIRE(callContractFunction("setHelper(address)", helperAddress) == bytes());
BOOST_REQUIRE(callContractFunction("getHelper()", helperAddress) == toBigEndian(helperAddress)); BOOST_REQUIRE(callContractFunction("getHelper()", helperAddress) == encodeArgs(helperAddress));
u256 a(3456789); u256 a(3456789);
u256 b("0x282837623374623234aa74"); u256 b("0x282837623374623234aa74");
BOOST_REQUIRE(callContractFunction("callHelper(uint256,uint256)", a, b) == toBigEndian(a * b + 9)); BOOST_REQUIRE(callContractFunction("callHelper(uint256,uint256)", a, b) == encodeArgs(a * b + 9));
} }
BOOST_AUTO_TEST_CASE(strings_in_calls) BOOST_AUTO_TEST_CASE(strings_in_calls)
@ -1215,8 +1214,8 @@ BOOST_AUTO_TEST_CASE(strings_in_calls)
u160 const helperAddress = m_contractAddress; u160 const helperAddress = m_contractAddress;
compileAndRun(sourceCode, 0, "Main"); compileAndRun(sourceCode, 0, "Main");
BOOST_REQUIRE(callContractFunction("setHelper(address)", helperAddress) == bytes()); BOOST_REQUIRE(callContractFunction("setHelper(address)", helperAddress) == bytes());
BOOST_REQUIRE(callContractFunction("getHelper()", helperAddress) == toBigEndian(helperAddress)); BOOST_REQUIRE(callContractFunction("getHelper()", helperAddress) == encodeArgs(helperAddress));
BOOST_CHECK(callContractFunction("callHelper(string2,bool)", bytes({0, 'a', 1})) == bytes({0, 'a', 0, 0, 0})); BOOST_CHECK(callContractFunction("callHelper(string2,bool)", string("\0a", 2), true) == encodeArgs(string("\0a\0\0\0", 5)));
} }
BOOST_AUTO_TEST_CASE(constructor_arguments) BOOST_AUTO_TEST_CASE(constructor_arguments)
@ -1241,8 +1240,8 @@ BOOST_AUTO_TEST_CASE(constructor_arguments)
function getName() returns (string3 ret) { return h.getName(); } function getName() returns (string3 ret) { return h.getName(); }
})"; })";
compileAndRun(sourceCode, 0, "Main"); compileAndRun(sourceCode, 0, "Main");
BOOST_REQUIRE(callContractFunction("getFlag()") == bytes({byte(0x01)})); BOOST_REQUIRE(callContractFunction("getFlag()") == encodeArgs(true));
BOOST_REQUIRE(callContractFunction("getName()") == bytes({'a', 'b', 'c'})); BOOST_REQUIRE(callContractFunction("getName()") == encodeArgs("abc"));
} }
BOOST_AUTO_TEST_CASE(functions_called_by_constructor) BOOST_AUTO_TEST_CASE(functions_called_by_constructor)
@ -1259,7 +1258,7 @@ BOOST_AUTO_TEST_CASE(functions_called_by_constructor)
function setName(string3 _name) { name = _name; } function setName(string3 _name) { name = _name; }
})"; })";
compileAndRun(sourceCode); compileAndRun(sourceCode);
BOOST_REQUIRE(callContractFunction("getName()") == bytes({'a', 'b', 'c'})); BOOST_REQUIRE(callContractFunction("getName()") == encodeArgs("abc"));
} }
BOOST_AUTO_TEST_SUITE_END() BOOST_AUTO_TEST_SUITE_END()

41
test/solidityExecutionFramework.h

@ -32,9 +32,6 @@
namespace dev namespace dev
{ {
/// Provides additional overloads for toBigEndian to encode arguments and return values.
inline bytes toBigEndian(byte _value) { return bytes({_value}); }
inline bytes toBigEndian(bool _value) { return bytes({byte(_value)}); }
namespace solidity namespace solidity
{ {
@ -56,18 +53,20 @@ public:
return m_output; return m_output;
} }
bytes const& callContractFunction(std::string _sig, bytes const& _data = bytes(), template <class... Args>
u256 const& _value = 0) bytes const& callContractFunctionWithValue(std::string _sig, u256 const& _value,
Args const&... _arguments)
{ {
FixedHash<4> hash(dev::sha3(_sig)); FixedHash<4> hash(dev::sha3(_sig));
sendMessage(hash.asBytes() + _data, false, _value); sendMessage(hash.asBytes() + encodeArgs(_arguments...), false, _value);
return m_output; return m_output;
} }
template <class... Args> template <class... Args>
bytes const& callContractFunction(std::string _sig, Args const&... _arguments) bytes const& callContractFunction(std::string _sig, Args const&... _arguments)
{ {
return callContractFunction(_sig, argsToBigEndian(_arguments...)); return callContractFunctionWithValue(_sig, 0, _arguments...);
} }
template <class CppFunction, class... Args> template <class CppFunction, class... Args>
@ -89,19 +88,33 @@ public:
bytes cppResult = callCppAndEncodeResult(_cppFunction, argument); bytes cppResult = callCppAndEncodeResult(_cppFunction, argument);
BOOST_CHECK_MESSAGE(solidityResult == cppResult, "Computed values do not match." BOOST_CHECK_MESSAGE(solidityResult == cppResult, "Computed values do not match."
"\nSolidity: " + toHex(solidityResult) + "\nC++: " + toHex(cppResult) + "\nSolidity: " + toHex(solidityResult) + "\nC++: " + toHex(cppResult) +
"\nArgument: " + toHex(toBigEndian(argument))); "\nArgument: " + toHex(encode(argument)));
} }
} }
private: static bytes encode(bool _value) { return encode(byte(_value)); }
template <class FirstArg, class... Args> static bytes encode(int _value) { return encode(u256(_value)); }
bytes argsToBigEndian(FirstArg const& _firstArg, Args const&... _followingArgs) const static bytes encode(char const* _value) { return encode(std::string(_value)); }
static bytes encode(byte _value) { return bytes(31, 0) + bytes{_value}; }
static bytes encode(u256 const& _value) { return toBigEndian(_value); }
static bytes encode(bytes const& _value, bool _padLeft = true)
{ {
return toBigEndian(_firstArg) + argsToBigEndian(_followingArgs...); bytes padding = bytes((32 - _value.size() % 32) % 32, 0);
return _padLeft ? padding + _value : _value + padding;
} }
static bytes encode(std::string const& _value) { return encode(asBytes(_value), false); }
bytes argsToBigEndian() const { return bytes(); } template <class FirstArg, class... Args>
static bytes encodeArgs(FirstArg const& _firstArg, Args const&... _followingArgs)
{
return encode(_firstArg) + encodeArgs(_followingArgs...);
}
static bytes encodeArgs()
{
return bytes();
}
private:
template <class CppFunction, class... Args> template <class CppFunction, class... Args>
auto callCppAndEncodeResult(CppFunction const& _cppFunction, Args const&... _arguments) auto callCppAndEncodeResult(CppFunction const& _cppFunction, Args const&... _arguments)
-> typename std::enable_if<std::is_void<decltype(_cppFunction(_arguments...))>::value, bytes>::type -> typename std::enable_if<std::is_void<decltype(_cppFunction(_arguments...))>::value, bytes>::type
@ -113,7 +126,7 @@ private:
auto callCppAndEncodeResult(CppFunction const& _cppFunction, Args const&... _arguments) auto callCppAndEncodeResult(CppFunction const& _cppFunction, Args const&... _arguments)
-> typename std::enable_if<!std::is_void<decltype(_cppFunction(_arguments...))>::value, bytes>::type -> typename std::enable_if<!std::is_void<decltype(_cppFunction(_arguments...))>::value, bytes>::type
{ {
return toBigEndian(_cppFunction(_arguments...)); return encode(_cppFunction(_arguments...));
} }
void sendMessage(bytes const& _data, bool _isCreation, u256 const& _value = 0) void sendMessage(bytes const& _data, bool _isCreation, u256 const& _value = 0)

Loading…
Cancel
Save