diff --git a/SolidityABIJSON.cpp b/SolidityABIJSON.cpp index 892b71f15..1f7d35ab1 100644 --- a/SolidityABIJSON.cpp +++ b/SolidityABIJSON.cpp @@ -35,7 +35,9 @@ namespace test class InterfaceChecker { public: - void checkInterface(std::string const& _code, std::string const& _expectedInterfaceString) + InterfaceChecker(): m_compilerStack(false) {} + + void checkInterface(std::string const& _code, std::string const& _expectedInterfaceString, std::string const& expectedSolidityInterface) { try { @@ -47,13 +49,17 @@ public: BOOST_FAIL(msg); } std::string generatedInterfaceString = m_compilerStack.getMetadata("", DocumentationType::ABI_INTERFACE); + std::string generatedSolidityInterfaceString = m_compilerStack.getMetadata("", DocumentationType::ABI_SOLIDITY_INTERFACE); Json::Value generatedInterface; m_reader.parse(generatedInterfaceString, generatedInterface); Json::Value expectedInterface; m_reader.parse(_expectedInterfaceString, expectedInterface); BOOST_CHECK_MESSAGE(expectedInterface == generatedInterface, - "Expected " << _expectedInterfaceString << - "\n but got:\n" << generatedInterfaceString); + "Expected:\n" << expectedInterface.toStyledString() << + "\n but got:\n" << generatedInterface.toStyledString()); + BOOST_CHECK_MESSAGE(expectedSolidityInterface == generatedSolidityInterfaceString, + "Expected:\n" << expectedSolidityInterface << + "\n but got:\n" << generatedSolidityInterfaceString); } private: @@ -69,10 +75,13 @@ BOOST_AUTO_TEST_CASE(basic_test) " function f(uint a) returns(uint d) { return a * 7; }\n" "}\n"; + char const* sourceInterface = "contract test{function f(uint256 a)returns(uint256 d){}}"; + char const* interface = R"([ { "name": "f", "constant": false, + "type": "function", "inputs": [ { "name": "a", @@ -88,17 +97,18 @@ BOOST_AUTO_TEST_CASE(basic_test) } ])"; - checkInterface(sourceCode, interface); + checkInterface(sourceCode, interface, sourceInterface); } BOOST_AUTO_TEST_CASE(empty_contract) { char const* sourceCode = "contract test {\n" "}\n"; + char const* sourceInterface = "contract test{}"; char const* interface = "[]"; - checkInterface(sourceCode, interface); + checkInterface(sourceCode, interface, sourceInterface); } BOOST_AUTO_TEST_CASE(multiple_methods) @@ -107,11 +117,13 @@ BOOST_AUTO_TEST_CASE(multiple_methods) " function f(uint a) returns(uint d) { return a * 7; }\n" " function g(uint b) returns(uint e) { return b * 8; }\n" "}\n"; + char const* sourceInterface = "contract test{function f(uint256 a)returns(uint256 d){}function g(uint256 b)returns(uint256 e){}}"; char const* interface = R"([ { "name": "f", "constant": false, + "type": "function", "inputs": [ { "name": "a", @@ -128,6 +140,7 @@ BOOST_AUTO_TEST_CASE(multiple_methods) { "name": "g", "constant": false, + "type": "function", "inputs": [ { "name": "b", @@ -143,7 +156,7 @@ BOOST_AUTO_TEST_CASE(multiple_methods) } ])"; - checkInterface(sourceCode, interface); + checkInterface(sourceCode, interface, sourceInterface); } BOOST_AUTO_TEST_CASE(multiple_params) @@ -151,11 +164,13 @@ BOOST_AUTO_TEST_CASE(multiple_params) char const* sourceCode = "contract test {\n" " function f(uint a, uint b) returns(uint d) { return a + b; }\n" "}\n"; + char const* sourceInterface = "contract test{function f(uint256 a,uint256 b)returns(uint256 d){}}"; char const* interface = R"([ { "name": "f", "constant": false, + "type": "function", "inputs": [ { "name": "a", @@ -175,7 +190,7 @@ BOOST_AUTO_TEST_CASE(multiple_params) } ])"; - checkInterface(sourceCode, interface); + checkInterface(sourceCode, interface, sourceInterface); } BOOST_AUTO_TEST_CASE(multiple_methods_order) @@ -185,11 +200,13 @@ BOOST_AUTO_TEST_CASE(multiple_methods_order) " function f(uint a) returns(uint d) { return a * 7; }\n" " function c(uint b) returns(uint e) { return b * 8; }\n" "}\n"; + char const* sourceInterface = "contract test{function c(uint256 b)returns(uint256 e){}function f(uint256 a)returns(uint256 d){}}"; char const* interface = R"([ { "name": "c", "constant": false, + "type": "function", "inputs": [ { "name": "b", @@ -206,6 +223,7 @@ BOOST_AUTO_TEST_CASE(multiple_methods_order) { "name": "f", "constant": false, + "type": "function", "inputs": [ { "name": "a", @@ -221,7 +239,7 @@ BOOST_AUTO_TEST_CASE(multiple_methods_order) } ])"; - checkInterface(sourceCode, interface); + checkInterface(sourceCode, interface, sourceInterface); } BOOST_AUTO_TEST_CASE(const_function) @@ -230,11 +248,13 @@ BOOST_AUTO_TEST_CASE(const_function) " function foo(uint a, uint b) returns(uint d) { return a + b; }\n" " function boo(uint32 a) constant returns(uint b) { return a * 4; }\n" "}\n"; + char const* sourceInterface = "contract test{function foo(uint256 a,uint256 b)returns(uint256 d){}function boo(uint32 a)constant returns(uint256 b){}}"; char const* interface = R"([ { "name": "foo", "constant": false, + "type": "function", "inputs": [ { "name": "a", @@ -255,6 +275,7 @@ BOOST_AUTO_TEST_CASE(const_function) { "name": "boo", "constant": true, + "type": "function", "inputs": [{ "name": "a", "type": "uint32" @@ -268,9 +289,144 @@ BOOST_AUTO_TEST_CASE(const_function) } ])"; - checkInterface(sourceCode, interface); + checkInterface(sourceCode, interface, sourceInterface); } +BOOST_AUTO_TEST_CASE(exclude_fallback_function) +{ + char const* sourceCode = "contract test { function() {} }"; + char const* sourceInterface = "contract test{}"; + + char const* interface = "[]"; + + checkInterface(sourceCode, interface, sourceInterface); +} + +BOOST_AUTO_TEST_CASE(events) +{ + char const* sourceCode = "contract test {\n" + " function f(uint a) returns(uint d) { return a * 7; }\n" + " event e1(uint b, address indexed c); \n" + " event e2(); \n" + "}\n"; + char const* sourceInterface = "contract test{function f(uint256 a)returns(uint256 d){}event e1(uint256 b,address indexed c);event e2;}"; + + char const* interface = R"([ + { + "name": "f", + "constant": false, + "type": "function", + "inputs": [ + { + "name": "a", + "type": "uint256" + } + ], + "outputs": [ + { + "name": "d", + "type": "uint256" + } + ] + }, + { + "name": "e1", + "type": "event", + "inputs": [ + { + "indexed": false, + "name": "b", + "type": "uint256" + }, + { + "indexed": true, + "name": "c", + "type": "address" + } + ] + }, + { + "name": "e2", + "type": "event", + "inputs": [] + } + + ])"; + + checkInterface(sourceCode, interface, sourceInterface); +} + + +BOOST_AUTO_TEST_CASE(inherited) +{ + char const* sourceCode = + " contract Base { \n" + " function baseFunction(uint p) returns (uint i) { return p; } \n" + " event baseEvent(string32 indexed evtArgBase); \n" + " } \n" + " contract Derived is Base { \n" + " function derivedFunction(string32 p) returns (string32 i) { return p; } \n" + " event derivedEvent(uint indexed evtArgDerived); \n" + " }"; + char const* sourceInterface = "contract Derived{function baseFunction(uint256 p)returns(uint256 i){}function derivedFunction(string32 p)returns(string32 i){}event derivedEvent(uint256 indexed evtArgDerived);event baseEvent(string32 indexed evtArgBase);}"; + + char const* interface = R"([ + { + "name": "baseFunction", + "constant": false, + "type": "function", + "inputs": + [{ + "name": "p", + "type": "uint256" + }], + "outputs": + [{ + "name": "i", + "type": "uint256" + }] + }, + { + "name": "derivedFunction", + "constant": false, + "type": "function", + "inputs": + [{ + "name": "p", + "type": "string32" + }], + "outputs": + [{ + "name": "i", + "type": "string32" + }] + }, + { + "name": "derivedEvent", + "type": "event", + "inputs": + [{ + "indexed": true, + "name": "evtArgDerived", + "type": "uint256" + }] + }, + { + "name": "baseEvent", + "type": "event", + "inputs": + [{ + "indexed": true, + "name": "evtArgBase", + "type": "string32" + }] + }])"; + + + checkInterface(sourceCode, interface, sourceInterface); +} + + BOOST_AUTO_TEST_SUITE_END() } diff --git a/SolidityCompiler.cpp b/SolidityCompiler.cpp index 53daa9dfe..17d9a7c07 100644 --- a/SolidityCompiler.cpp +++ b/SolidityCompiler.cpp @@ -96,7 +96,7 @@ BOOST_AUTO_TEST_CASE(smoke_test) "}\n"; bytes code = compileContract(sourceCode); - unsigned boilerplateSize = 73; + unsigned boilerplateSize = 69; bytes expectation({byte(Instruction::JUMPDEST), byte(Instruction::PUSH1), 0x0, // initialize local variable x byte(Instruction::PUSH1), 0x2, @@ -108,65 +108,14 @@ BOOST_AUTO_TEST_CASE(smoke_test) checkCodePresentAt(code, expectation, boilerplateSize); } -BOOST_AUTO_TEST_CASE(different_argument_numbers) -{ - char const* sourceCode = "contract test {\n" - " function f(uint a, uint b, uint c) returns(uint d) { return b; }\n" - " function g() returns (uint e, uint h) { h = f(1, 2, 3); }\n" - "}\n"; - bytes code = compileContract(sourceCode); - unsigned shift = 103; - unsigned boilerplateSize = 116; - bytes expectation({byte(Instruction::JUMPDEST), - byte(Instruction::PUSH1), 0x0, // initialize return variable d - byte(Instruction::DUP3), - byte(Instruction::SWAP1), // assign b to d - byte(Instruction::POP), - byte(Instruction::PUSH1), byte(0xa + shift), // jump to return - byte(Instruction::JUMP), - byte(Instruction::JUMPDEST), - byte(Instruction::SWAP4), // store d and fetch return address - byte(Instruction::SWAP3), // store return address - byte(Instruction::POP), - byte(Instruction::POP), - byte(Instruction::POP), - byte(Instruction::JUMP), // end of f - byte(Instruction::JUMPDEST), // beginning of g - byte(Instruction::PUSH1), 0x0, - byte(Instruction::PUSH1), 0x0, // initialized e and h - byte(Instruction::PUSH1), byte(0x21 + shift), // ret address - byte(Instruction::PUSH1), 0x1, - byte(Instruction::PUSH1), 0x2, - byte(Instruction::PUSH1), 0x3, - byte(Instruction::PUSH1), byte(0x1 + shift), - // stack here: ret e h 0x20 1 2 3 0x1 - byte(Instruction::JUMP), - byte(Instruction::JUMPDEST), - // stack here: ret e h f(1,2,3) - byte(Instruction::SWAP1), - // stack here: ret e f(1,2,3) h - byte(Instruction::POP), - byte(Instruction::DUP1), // retrieve it again as "value of expression" - byte(Instruction::POP), // end of assignment - // stack here: ret e f(1,2,3) - byte(Instruction::JUMPDEST), - byte(Instruction::SWAP1), - // ret e f(1,2,3) - byte(Instruction::SWAP2), - // f(1,2,3) e ret - byte(Instruction::JUMP) // end of g - }); - 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; + unsigned shift = 56; + unsigned boilerplateSize = 69; bytes expectation({byte(Instruction::JUMPDEST), byte(Instruction::PUSH1), 0x0, byte(Instruction::DUP1), @@ -206,8 +155,8 @@ BOOST_AUTO_TEST_CASE(loops) " function f() { while(true){1;break;2;continue;3;return;4;} }" "}\n"; bytes code = compileContract(sourceCode); - unsigned shift = 60; - unsigned boilerplateSize = 73; + unsigned shift = 56; + unsigned boilerplateSize = 69; bytes expectation({byte(Instruction::JUMPDEST), byte(Instruction::JUMPDEST), byte(Instruction::PUSH1), 0x1, diff --git a/SolidityEndToEndTest.cpp b/SolidityEndToEndTest.cpp index cf04edaad..7edc250c8 100644 --- a/SolidityEndToEndTest.cpp +++ b/SolidityEndToEndTest.cpp @@ -882,6 +882,43 @@ BOOST_AUTO_TEST_CASE(constructor) testSolidityAgainstCpp("get(uint256)", get, u256(7)); } +BOOST_AUTO_TEST_CASE(simple_accessor) +{ + char const* sourceCode = "contract test {\n" + " uint256 data;\n" + " function test() {\n" + " data = 8;\n" + " }\n" + "}\n"; + compileAndRun(sourceCode); + BOOST_CHECK(callContractFunction("data()") == encodeArgs(8)); +} + +BOOST_AUTO_TEST_CASE(multiple_elementary_accessors) +{ + char const* sourceCode = "contract test {\n" + " uint256 data;\n" + " string6 name;\n" + " hash a_hash;\n" + " address an_address;\n" + " function test() {\n" + " data = 8;\n" + " name = \"Celina\";\n" + " a_hash = sha3(123);\n" + " an_address = address(0x1337);\n" + " super_secret_data = 42;\n" + " }\n" + " private:" + " uint256 super_secret_data;" + "}\n"; + compileAndRun(sourceCode); + BOOST_CHECK(callContractFunction("data()") == encodeArgs(8)); + BOOST_CHECK(callContractFunction("name()") == encodeArgs("Celina")); + BOOST_CHECK(callContractFunction("a_hash()") == encodeArgs(dev::sha3(toBigEndian(u256(123))))); + BOOST_CHECK(callContractFunction("an_address()") == encodeArgs(toBigEndian(u160(0x1337)))); + BOOST_CHECK(callContractFunction("super_secret_data()") == bytes()); +} + BOOST_AUTO_TEST_CASE(balance) { char const* sourceCode = "contract test {\n" @@ -940,6 +977,97 @@ BOOST_AUTO_TEST_CASE(type_conversions_cleanup) 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0x00, 0x11, 0x22})); } +BOOST_AUTO_TEST_CASE(convert_string_to_string) +{ + char const* sourceCode = R"( + contract Test { + function pipeTrough(string3 input) returns (string3 ret) { + return string3(input); + } + })"; + compileAndRun(sourceCode); + BOOST_CHECK(callContractFunction("pipeTrough(string3)", "abc") == encodeArgs("abc")); +} + +BOOST_AUTO_TEST_CASE(convert_hash_to_string_same_size) +{ + char const* sourceCode = R"( + contract Test { + function hashToString(hash h) returns (string32 s) { + return string32(h); + } + })"; + compileAndRun(sourceCode); + u256 a("0x6162630000000000000000000000000000000000000000000000000000000000"); + BOOST_CHECK(callContractFunction("hashToString(hash256)", a) == encodeArgs(a)); +} + +BOOST_AUTO_TEST_CASE(convert_hash_to_string_different_size) +{ + char const* sourceCode = R"( + contract Test { + function hashToString(hash160 h) returns (string20 s) { + return string20(h); + } + })"; + compileAndRun(sourceCode); + BOOST_CHECK(callContractFunction("hashToString(hash160)", u160("0x6161626361626361626361616263616263616263")) == + encodeArgs(string("aabcabcabcaabcabcabc"))); +} + +BOOST_AUTO_TEST_CASE(convert_string_to_hash_same_size) +{ + char const* sourceCode = R"( + contract Test { + function stringToHash(string32 s) returns (hash h) { + return hash(s); + } + })"; + compileAndRun(sourceCode); + BOOST_CHECK(callContractFunction("stringToHash(string32)", string("abc2")) == + encodeArgs(u256("0x6162633200000000000000000000000000000000000000000000000000000000"))); +} + +BOOST_AUTO_TEST_CASE(convert_string_to_hash_different_size) +{ + char const* sourceCode = R"( + contract Test { + function stringToHash(string20 s) returns (hash160 h) { + return hash160(s); + } + })"; + compileAndRun(sourceCode); + BOOST_CHECK(callContractFunction("stringToHash(string20)", string("aabcabcabcaabcabcabc")) == + encodeArgs(u160("0x6161626361626361626361616263616263616263"))); +} + + +BOOST_AUTO_TEST_CASE(convert_string_to_hash_different_min_size) +{ + char const* sourceCode = R"( + contract Test { + function stringToHash(string1 s) returns (hash8 h) { + return hash8(s); + } + })"; + compileAndRun(sourceCode); + BOOST_CHECK(callContractFunction("stringToHash(string1)", string("a")) == + encodeArgs(u256("0x61"))); +} + + +BOOST_AUTO_TEST_CASE(convert_hash_to_string_different_min_size) +{ + char const* sourceCode = R"( + contract Test { + function HashToString(hash8 h) returns (string1 s) { + return string1(h); + } + })"; + compileAndRun(sourceCode); + BOOST_CHECK(callContractFunction("HashToString(hash8)", u256("0x61")) == + encodeArgs(string("a"))); +} BOOST_AUTO_TEST_CASE(send_ether) { @@ -1545,7 +1673,7 @@ BOOST_AUTO_TEST_CASE(single_copy_with_multiple_inheritance) } contract A is Base { function setViaA(uint i) { setData(i); } } contract B is Base { function getViaB() returns (uint i) { return getViaBase(); } } - contract Derived is A, B, Base { } + contract Derived is Base, B, A { } )"; compileAndRun(sourceCode, 0, "Derived"); BOOST_CHECK(callContractFunction("getViaB()") == encodeArgs(0)); @@ -1642,7 +1770,7 @@ BOOST_AUTO_TEST_CASE(constructor_argument_overriding) } } contract Base is BaseBase(2) { } - contract Derived is Base, BaseBase(3) { + contract Derived is BaseBase(3), Base { function getA() returns (uint r) { return m_a; } } )"; @@ -1650,6 +1778,284 @@ BOOST_AUTO_TEST_CASE(constructor_argument_overriding) BOOST_CHECK(callContractFunction("getA()") == encodeArgs(3)); } +BOOST_AUTO_TEST_CASE(function_modifier) +{ + char const* sourceCode = R"( + contract C { + function getOne() nonFree returns (uint r) { return 1; } + modifier nonFree { if (msg.value > 0) _ } + } + )"; + compileAndRun(sourceCode); + BOOST_CHECK(callContractFunction("getOne()") == encodeArgs(0)); + BOOST_CHECK(callContractFunctionWithValue("getOne()", 1) == encodeArgs(1)); +} + +BOOST_AUTO_TEST_CASE(function_modifier_local_variables) +{ + char const* sourceCode = R"( + contract C { + modifier mod1 { var a = 1; var b = 2; _ } + modifier mod2(bool a) { if (a) return; else _ } + function f(bool a) mod1 mod2(a) returns (uint r) { return 3; } + } + )"; + compileAndRun(sourceCode); + BOOST_CHECK(callContractFunction("f(bool)", true) == encodeArgs(0)); + BOOST_CHECK(callContractFunction("f(bool)", false) == encodeArgs(3)); +} + +BOOST_AUTO_TEST_CASE(function_modifier_loop) +{ + char const* sourceCode = R"( + contract C { + modifier repeat(uint count) { for (var i = 0; i < count; ++i) _ } + function f() repeat(10) returns (uint r) { r += 1; } + } + )"; + compileAndRun(sourceCode); + BOOST_CHECK(callContractFunction("f()") == encodeArgs(10)); +} + +BOOST_AUTO_TEST_CASE(function_modifier_multi_invocation) +{ + char const* sourceCode = R"( + contract C { + modifier repeat(bool twice) { if (twice) _ _ } + function f(bool twice) repeat(twice) returns (uint r) { r += 1; } + } + )"; + compileAndRun(sourceCode); + BOOST_CHECK(callContractFunction("f(bool)", false) == encodeArgs(1)); + BOOST_CHECK(callContractFunction("f(bool)", true) == encodeArgs(2)); +} + +BOOST_AUTO_TEST_CASE(function_modifier_multi_with_return) +{ + // Here, the explicit return prevents the second execution + char const* sourceCode = R"( + contract C { + modifier repeat(bool twice) { if (twice) _ _ } + function f(bool twice) repeat(twice) returns (uint r) { r += 1; return r; } + } + )"; + compileAndRun(sourceCode); + BOOST_CHECK(callContractFunction("f(bool)", false) == encodeArgs(1)); + BOOST_CHECK(callContractFunction("f(bool)", true) == encodeArgs(1)); +} + +BOOST_AUTO_TEST_CASE(function_modifier_overriding) +{ + char const* sourceCode = R"( + contract A { + function f() mod returns (bool r) { return true; } + modifier mod { _ } + } + contract C is A { + modifier mod { } + } + )"; + compileAndRun(sourceCode); + BOOST_CHECK(callContractFunction("f()") == encodeArgs(false)); +} + +BOOST_AUTO_TEST_CASE(function_modifier_calling_functions_in_creation_context) +{ + char const* sourceCode = R"( + contract A { + uint data; + function A() mod1 { f1(); } + function f1() mod2 { data |= 0x1; } + function f2() { data |= 0x20; } + function f3() { } + modifier mod1 { f2(); _ } + modifier mod2 { f3(); } + function getData() returns (uint r) { return data; } + } + contract C is A { + modifier mod1 { f4(); _ } + function f3() { data |= 0x300; } + function f4() { data |= 0x4000; } + } + )"; + compileAndRun(sourceCode); + BOOST_CHECK(callContractFunction("getData()") == encodeArgs(0x4300)); +} + +BOOST_AUTO_TEST_CASE(function_modifier_for_constructor) +{ + char const* sourceCode = R"( + contract A { + uint data; + function A() mod1 { data |= 2; } + modifier mod1 { data |= 1; _ } + function getData() returns (uint r) { return data; } + } + contract C is A { + modifier mod1 { data |= 4; _ } + } + )"; + compileAndRun(sourceCode); + BOOST_CHECK(callContractFunction("getData()") == encodeArgs(4 | 2)); +} + +BOOST_AUTO_TEST_CASE(use_std_lib) +{ + char const* sourceCode = R"( + import "mortal"; + contract Icarus is mortal { } + )"; + m_addStandardSources = true; + u256 amount(130); + u160 address(23); + compileAndRun(sourceCode, amount, "Icarus"); + u256 balanceBefore = m_state.balance(m_sender); + BOOST_CHECK(callContractFunction("kill()") == bytes()); + BOOST_CHECK(!m_state.addressHasCode(m_contractAddress)); + BOOST_CHECK(m_state.balance(m_sender) > balanceBefore); +} + +BOOST_AUTO_TEST_CASE(crazy_elementary_typenames_on_stack) +{ + char const* sourceCode = R"( + contract C { + function f() returns (uint r) { + uint; uint; uint; uint; + int x = -7; + var a = uint; + return a(x); + } + } + )"; + compileAndRun(sourceCode); + BOOST_CHECK(callContractFunction("f()") == encodeArgs(u256(-7))); +} + +BOOST_AUTO_TEST_CASE(super) +{ + char const* sourceCode = R"( + contract A { function f() returns (uint r) { return 1; } } + contract B is A { function f() returns (uint r) { return super.f() | 2; } } + contract C is A { function f() returns (uint r) { return super.f() | 4; } } + contract D is B, C { function f() returns (uint r) { return super.f() | 8; } } + )"; + compileAndRun(sourceCode, 0, "D"); + BOOST_CHECK(callContractFunction("f()") == encodeArgs(1 | 2 | 4 | 8)); +} + +BOOST_AUTO_TEST_CASE(super_in_constructor) +{ + char const* sourceCode = R"( + contract A { function f() returns (uint r) { return 1; } } + contract B is A { function f() returns (uint r) { return super.f() | 2; } } + contract C is A { function f() returns (uint r) { return super.f() | 4; } } + contract D is B, C { uint data; function D() { data = super.f() | 8; } function f() returns (uint r) { return data; } } + )"; + compileAndRun(sourceCode, 0, "D"); + BOOST_CHECK(callContractFunction("f()") == encodeArgs(1 | 2 | 4 | 8)); +} + +BOOST_AUTO_TEST_CASE(fallback_function) +{ + char const* sourceCode = R"( + contract A { + uint data; + function() returns (uint r) { data = 1; return 2; } + function getData() returns (uint r) { return data; } + } + )"; + compileAndRun(sourceCode); + BOOST_CHECK(callContractFunction("getData()") == encodeArgs(0)); + BOOST_CHECK(callContractFunction("") == encodeArgs(2)); + BOOST_CHECK(callContractFunction("getData()") == encodeArgs(1)); +} + +BOOST_AUTO_TEST_CASE(inherited_fallback_function) +{ + char const* sourceCode = R"( + contract A { + uint data; + function() returns (uint r) { data = 1; return 2; } + function getData() returns (uint r) { return data; } + } + contract B is A {} + )"; + compileAndRun(sourceCode, 0, "B"); + BOOST_CHECK(callContractFunction("getData()") == encodeArgs(0)); + BOOST_CHECK(callContractFunction("") == encodeArgs(2)); + BOOST_CHECK(callContractFunction("getData()") == encodeArgs(1)); +} + +BOOST_AUTO_TEST_CASE(event) +{ + char const* sourceCode = R"( + contract ClientReceipt { + event Deposit(address indexed _from, hash indexed _id, uint _value); + function deposit(hash _id, bool _manually) { + if (_manually) { + hash s = 0x50cb9fe53daa9737b786ab3646f04d0150dc50ef4e75f59509d83667ad5adb20; + log3(msg.value, s, hash32(msg.sender), _id); + } else + Deposit(hash32(msg.sender), _id, msg.value); + } + } + )"; + compileAndRun(sourceCode); + u256 value(18); + u256 id(0x1234); + for (bool manually: {true, false}) + { + callContractFunctionWithValue("deposit(hash256,bool)", value, id, manually); + BOOST_REQUIRE_EQUAL(m_logs.size(), 1); + BOOST_CHECK_EQUAL(m_logs[0].address, m_contractAddress); + BOOST_CHECK_EQUAL(h256(m_logs[0].data), h256(u256(value))); + BOOST_REQUIRE_EQUAL(m_logs[0].topics.size(), 3); + BOOST_CHECK_EQUAL(m_logs[0].topics[0], dev::sha3(string("Deposit(address,hash256,uint256)"))); + BOOST_CHECK_EQUAL(m_logs[0].topics[1], h256(m_sender)); + BOOST_CHECK_EQUAL(m_logs[0].topics[2], h256(id)); + } +} + +BOOST_AUTO_TEST_CASE(event_no_arguments) +{ + char const* sourceCode = R"( + contract ClientReceipt { + event Deposit; + function deposit() { + Deposit(); + } + } + )"; + compileAndRun(sourceCode); + callContractFunction("deposit()"); + BOOST_REQUIRE_EQUAL(m_logs.size(), 1); + BOOST_CHECK_EQUAL(m_logs[0].address, m_contractAddress); + BOOST_CHECK(m_logs[0].data.empty()); + BOOST_REQUIRE_EQUAL(m_logs[0].topics.size(), 1); + BOOST_CHECK_EQUAL(m_logs[0].topics[0], dev::sha3(string("Deposit()"))); +} + +BOOST_AUTO_TEST_CASE(event_lots_of_data) +{ + char const* sourceCode = R"( + contract ClientReceipt { + event Deposit(address _from, hash _id, uint _value, bool _flag); + function deposit(hash _id) { + Deposit(msg.sender, hash32(_id), msg.value, true); + } + } + )"; + compileAndRun(sourceCode); + u256 value(18); + u256 id(0x1234); + callContractFunctionWithValue("deposit(hash256)", value, id); + BOOST_REQUIRE_EQUAL(m_logs.size(), 1); + BOOST_CHECK_EQUAL(m_logs[0].address, m_contractAddress); + BOOST_CHECK(m_logs[0].data == encodeArgs(m_sender, id, value, true)); + BOOST_REQUIRE_EQUAL(m_logs[0].topics.size(), 1); + BOOST_CHECK_EQUAL(m_logs[0].topics[0], dev::sha3(string("Deposit(address,hash256,uint256,bool)"))); +} + BOOST_AUTO_TEST_SUITE_END() } diff --git a/SolidityExpressionCompiler.cpp b/SolidityExpressionCompiler.cpp index d50dc253e..a0cca3a3a 100644 --- a/SolidityExpressionCompiler.cpp +++ b/SolidityExpressionCompiler.cpp @@ -86,7 +86,8 @@ Declaration const& resolveDeclaration(vector const& _namespacedName, } bytes compileFirstExpression(const string& _sourceCode, vector> _functions = {}, - vector> _localVariables = {}, vector> _globalDeclarations = {}) + vector> _localVariables = {}, + vector> _globalDeclarations = {}) { Parser parser; ASTPointer sourceUnit; @@ -99,10 +100,12 @@ bytes compileFirstExpression(const string& _sourceCode, vector> _ NameAndTypeResolver resolver(declarations); resolver.registerDeclarations(*sourceUnit); + vector inheritanceHierarchy; for (ASTPointer const& node: sourceUnit->getNodes()) if (ContractDefinition* contract = dynamic_cast(node.get())) { BOOST_REQUIRE_NO_THROW(resolver.resolveNamesAndTypes(*contract)); + inheritanceHierarchy = vector(1, contract); } for (ASTPointer const& node: sourceUnit->getNodes()) if (ContractDefinition* contract = dynamic_cast(node.get())) @@ -116,10 +119,12 @@ bytes compileFirstExpression(const string& _sourceCode, vector> _ BOOST_REQUIRE(extractor.getExpression() != nullptr); CompilerContext context; - for (vector const& function: _functions) - context.addFunction(dynamic_cast(resolveDeclaration(function, resolver))); + context.setInheritanceHierarchy(inheritanceHierarchy); + unsigned parametersSize = _localVariables.size(); // assume they are all one slot on the stack + context.adjustStackOffset(parametersSize); for (vector const& variable: _localVariables) - context.addVariable(dynamic_cast(resolveDeclaration(variable, resolver))); + context.addVariable(dynamic_cast(resolveDeclaration(variable, resolver)), + parametersSize--); ExpressionCompiler::compileExpression(context, *extractor.getExpression()); diff --git a/SolidityNameAndTypeResolution.cpp b/SolidityNameAndTypeResolution.cpp index 6c8fd1b1c..b9a7140f7 100644 --- a/SolidityNameAndTypeResolution.cpp +++ b/SolidityNameAndTypeResolution.cpp @@ -23,12 +23,15 @@ #include #include +#include #include #include #include #include #include +using namespace std; + namespace dev { namespace solidity @@ -38,6 +41,7 @@ namespace test namespace { + ASTPointer parseTextAndResolveNames(std::string const& _source) { Parser parser; @@ -53,6 +57,48 @@ ASTPointer parseTextAndResolveNames(std::string const& _source) return sourceUnit; } + +ASTPointer parseTextAndResolveNamesWithChecks(std::string const& _source) +{ + Parser parser; + ASTPointer sourceUnit; + try + { + sourceUnit = parser.parse(std::make_shared(CharStream(_source))); + NameAndTypeResolver resolver({}); + resolver.registerDeclarations(*sourceUnit); + for (ASTPointer const& node: sourceUnit->getNodes()) + if (ContractDefinition* contract = dynamic_cast(node.get())) + resolver.resolveNamesAndTypes(*contract); + for (ASTPointer const& node: sourceUnit->getNodes()) + if (ContractDefinition* contract = dynamic_cast(node.get())) + resolver.checkTypeRequirements(*contract); + } + catch(boost::exception const& _e) + { + auto msg = std::string("Parsing text and resolving names failed with: \n") + boost::diagnostic_information(_e); + BOOST_FAIL(msg); + } + return sourceUnit; +} + +static ContractDefinition const* retrieveContract(ASTPointer _source, unsigned index) +{ + ContractDefinition* contract; + unsigned counter = 0; + for (ASTPointer const& node: _source->getNodes()) + if ((contract = dynamic_cast(node.get())) && counter == index) + return contract; + + return NULL; +} + +static FunctionTypePointer const& retrieveFunctionBySignature(ContractDefinition const* _contract, + std::string const& _signature) +{ + FixedHash<4> hash(dev::sha3(_signature)); + return _contract->getInterfaceFunctions()[hash]; +} } BOOST_AUTO_TEST_SUITE(SolidityNameAndTypeResolution) @@ -63,7 +109,7 @@ BOOST_AUTO_TEST_CASE(smoke_test) " uint256 stateVariable1;\n" " function fun(uint256 arg1) { var x; uint256 y; }" "}\n"; - BOOST_CHECK_NO_THROW(parseTextAndResolveNames(text)); + BOOST_CHECK_NO_THROW(parseTextAndResolveNamesWithChecks(text)); } BOOST_AUTO_TEST_CASE(double_stateVariable_declaration) @@ -386,7 +432,7 @@ BOOST_AUTO_TEST_CASE(inheritance_diamond_basic) contract root { function rootFunction() {} } contract inter1 is root { function f() {} } contract inter2 is root { function f() {} } - contract derived is inter1, inter2, root { + contract derived is root, inter2, inter1 { function g() { f(); rootFunction(); } } )"; @@ -479,6 +525,7 @@ BOOST_AUTO_TEST_CASE(implicit_derived_to_base_conversion) )"; BOOST_CHECK_NO_THROW(parseTextAndResolveNames(text)); } + BOOST_AUTO_TEST_CASE(implicit_base_to_derived_conversion) { char const* text = R"( @@ -490,6 +537,249 @@ BOOST_AUTO_TEST_CASE(implicit_base_to_derived_conversion) BOOST_CHECK_THROW(parseTextAndResolveNames(text), TypeError); } +BOOST_AUTO_TEST_CASE(function_modifier_invocation) +{ + char const* text = R"( + contract B { + function f() mod1(2, true) mod2("0123456") { } + modifier mod1(uint a, bool b) { if (b) _ } + modifier mod2(string7 a) { while (a == "1234567") _ } + } + )"; + BOOST_CHECK_NO_THROW(parseTextAndResolveNames(text)); +} + +BOOST_AUTO_TEST_CASE(invalid_function_modifier_type) +{ + char const* text = R"( + contract B { + function f() mod1(true) { } + modifier mod1(uint a) { if (a > 0) _ } + } + )"; + BOOST_CHECK_THROW(parseTextAndResolveNames(text), TypeError); +} + +BOOST_AUTO_TEST_CASE(function_modifier_invocation_parameters) +{ + char const* text = R"( + contract B { + function f(uint8 a) mod1(a, true) mod2(r) returns (string7 r) { } + modifier mod1(uint a, bool b) { if (b) _ } + modifier mod2(string7 a) { while (a == "1234567") _ } + } + )"; + BOOST_CHECK_NO_THROW(parseTextAndResolveNames(text)); +} + +BOOST_AUTO_TEST_CASE(function_modifier_invocation_local_variables) +{ + char const* text = R"( + contract B { + function f() mod(x) { uint x = 7; } + modifier mod(uint a) { if (a > 0) _ } + } + )"; + BOOST_CHECK_NO_THROW(parseTextAndResolveNames(text)); +} + +BOOST_AUTO_TEST_CASE(legal_modifier_override) +{ + char const* text = R"( + contract A { modifier mod(uint a) {} } + contract B is A { modifier mod(uint a) {} } + )"; + BOOST_CHECK_NO_THROW(parseTextAndResolveNames(text)); +} + +BOOST_AUTO_TEST_CASE(illegal_modifier_override) +{ + char const* text = R"( + contract A { modifier mod(uint a) {} } + contract B is A { modifier mod(uint8 a) {} } + )"; + BOOST_CHECK_THROW(parseTextAndResolveNames(text), TypeError); +} + +BOOST_AUTO_TEST_CASE(modifier_overrides_function) +{ + char const* text = R"( + contract A { modifier mod(uint a) {} } + contract B is A { function mod(uint a) {} } + )"; + BOOST_CHECK_THROW(parseTextAndResolveNames(text), TypeError); +} + +BOOST_AUTO_TEST_CASE(function_overrides_modifier) +{ + char const* text = R"( + contract A { function mod(uint a) {} } + contract B is A { modifier mod(uint a) {} } + )"; + BOOST_CHECK_THROW(parseTextAndResolveNames(text), TypeError); +} + +BOOST_AUTO_TEST_CASE(modifier_returns_value) +{ + char const* text = R"( + contract A { + function f(uint a) mod(2) returns (uint r) {} + modifier mod(uint a) { return 7; } + } + )"; + BOOST_CHECK_THROW(parseTextAndResolveNames(text), TypeError); +} + +BOOST_AUTO_TEST_CASE(state_variable_accessors) +{ + char const* text = "contract test {\n" + " function fun() {\n" + " uint64(2);\n" + " }\n" + "uint256 foo;\n" + "}\n"; + + ASTPointer source; + ContractDefinition const* contract; + BOOST_CHECK_NO_THROW(source = parseTextAndResolveNamesWithChecks(text)); + BOOST_REQUIRE((contract = retrieveContract(source, 0)) != nullptr); + FunctionTypePointer function = retrieveFunctionBySignature(contract, "foo()"); + BOOST_REQUIRE(function->hasDeclaration()); + auto returnParams = function->getReturnParameterTypeNames(); + BOOST_CHECK_EQUAL(returnParams.at(0), "uint256"); + BOOST_CHECK(function->isConstant()); +} + +BOOST_AUTO_TEST_CASE(function_clash_with_state_variable_accessor) +{ + char const* text = "contract test {\n" + " function fun() {\n" + " uint64(2);\n" + " }\n" + "uint256 foo;\n" + " function foo() {}\n" + "}\n"; + BOOST_CHECK_THROW(parseTextAndResolveNames(text), DeclarationError); +} + +BOOST_AUTO_TEST_CASE(private_state_variable) +{ + char const* text = "contract test {\n" + " function fun() {\n" + " uint64(2);\n" + " }\n" + "private:\n" + "uint256 foo;\n" + "}\n"; + + ASTPointer source; + ContractDefinition const* contract; + BOOST_CHECK_NO_THROW(source = parseTextAndResolveNamesWithChecks(text)); + BOOST_CHECK((contract = retrieveContract(source, 0)) != nullptr); + FunctionTypePointer function = retrieveFunctionBySignature(contract, "foo()"); + BOOST_CHECK_MESSAGE(function == nullptr, "Accessor function of a private variable should not exist"); +} + +BOOST_AUTO_TEST_CASE(fallback_function) +{ + char const* text = R"( + contract C { + uint x; + function() { x = 2; } + } + )"; + BOOST_CHECK_NO_THROW(parseTextAndResolveNames(text)); +} + +BOOST_AUTO_TEST_CASE(fallback_function_with_arguments) +{ + char const* text = R"( + contract C { + uint x; + function(uint a) { x = 2; } + } + )"; + BOOST_CHECK_THROW(parseTextAndResolveNames(text), TypeError); +} + +BOOST_AUTO_TEST_CASE(fallback_function_twice) +{ + char const* text = R"( + contract C { + uint x; + function() { x = 2; } + function() { x = 3; } + } + )"; + BOOST_CHECK_THROW(parseTextAndResolveNames(text), DeclarationError); +} + +BOOST_AUTO_TEST_CASE(fallback_function_inheritance) +{ + char const* text = R"( + contract A { + uint x; + function() { x = 1; } + } + contract C is A { + function() { x = 2; } + } + )"; + BOOST_CHECK_NO_THROW(parseTextAndResolveNames(text)); +} + +BOOST_AUTO_TEST_CASE(event) +{ + char const* text = R"( + contract c { + event e(uint indexed a, string3 indexed s, bool indexed b); + function f() { e(2, "abc", true); } + })"; + BOOST_CHECK_NO_THROW(parseTextAndResolveNames(text)); +} + +BOOST_AUTO_TEST_CASE(event_too_many_indexed) +{ + char const* text = R"( + contract c { + event e(uint indexed a, string3 indexed b, bool indexed c, uint indexed d); + function f() { e(2, "abc", true); } + })"; + BOOST_CHECK_THROW(parseTextAndResolveNames(text), TypeError); +} + +BOOST_AUTO_TEST_CASE(event_call) +{ + char const* text = R"( + contract c { + event e(uint a, string3 indexed s, bool indexed b); + function f() { e(2, "abc", true); } + })"; + BOOST_CHECK_NO_THROW(parseTextAndResolveNames(text)); +} + +BOOST_AUTO_TEST_CASE(event_inheritance) +{ + char const* text = R"( + contract base { + event e(uint a, string3 indexed s, bool indexed b); + } + contract c is base { + function f() { e(2, "abc", true); } + })"; + BOOST_CHECK_NO_THROW(parseTextAndResolveNames(text)); +} + +BOOST_AUTO_TEST_CASE(multiple_events_argument_clash) +{ + char const* text = R"( + contract c { + event e1(uint a, uint e1, uint e2); + event e2(uint a, uint e1, uint e2); + })"; + BOOST_CHECK_NO_THROW(parseTextAndResolveNames(text)); +} + BOOST_AUTO_TEST_SUITE_END() } diff --git a/SolidityNatspecJSON.cpp b/SolidityNatspecJSON.cpp index 743651d54..911820ddd 100644 --- a/SolidityNatspecJSON.cpp +++ b/SolidityNatspecJSON.cpp @@ -36,6 +36,8 @@ namespace test class DocumentationChecker { public: + DocumentationChecker(): m_compilerStack(false) {} + void checkNatspec(std::string const& _code, std::string const& _expectedDocumentationString, bool _userDocumentation) diff --git a/SolidityParser.cpp b/SolidityParser.cpp index 91e571306..4adee9c66 100644 --- a/SolidityParser.cpp +++ b/SolidityParser.cpp @@ -66,6 +66,14 @@ ASTPointer parseTextExplainError(std::string const& _source) } } +static void checkFunctionNatspec(ASTPointer _function, + std::string const& _expectedDoc) +{ + auto doc = _function->getDocumentation(); + BOOST_CHECK_MESSAGE(doc != nullptr, "Function does not have Natspec Doc as expected"); + BOOST_CHECK_EQUAL(*doc, _expectedDoc); +} + } @@ -121,14 +129,16 @@ BOOST_AUTO_TEST_CASE(function_natspec_documentation) ASTPointer contract; ASTPointer function; char const* text = "contract test {\n" - " uint256 stateVar;\n" + " private:\n" + " uint256 stateVar;\n" + " public:\n" " /// This is a test function\n" " function functionName(hash hashin) returns (hash hashout) {}\n" "}\n"; BOOST_REQUIRE_NO_THROW(contract = parseText(text)); auto functions = contract->getDefinedFunctions(); BOOST_REQUIRE_NO_THROW(function = functions.at(0)); - BOOST_CHECK_EQUAL(*function->getDocumentation(), "This is a test function"); + checkFunctionNatspec(function, "This is a test function"); } BOOST_AUTO_TEST_CASE(function_normal_comments) @@ -144,7 +154,7 @@ BOOST_AUTO_TEST_CASE(function_normal_comments) auto functions = contract->getDefinedFunctions(); BOOST_REQUIRE_NO_THROW(function = functions.at(0)); BOOST_CHECK_MESSAGE(function->getDocumentation() == nullptr, - "Should not have gotten a Natspect comment for this function"); + "Should not have gotten a Natspecc comment for this function"); } BOOST_AUTO_TEST_CASE(multiple_functions_natspec_documentation) @@ -152,7 +162,9 @@ BOOST_AUTO_TEST_CASE(multiple_functions_natspec_documentation) ASTPointer contract; ASTPointer function; char const* text = "contract test {\n" + " private:\n" " uint256 stateVar;\n" + " public:\n" " /// This is test function 1\n" " function functionName1(hash hashin) returns (hash hashout) {}\n" " /// This is test function 2\n" @@ -166,17 +178,17 @@ BOOST_AUTO_TEST_CASE(multiple_functions_natspec_documentation) auto functions = contract->getDefinedFunctions(); BOOST_REQUIRE_NO_THROW(function = functions.at(0)); - BOOST_CHECK_EQUAL(*function->getDocumentation(), "This is test function 1"); + checkFunctionNatspec(function, "This is test function 1"); BOOST_REQUIRE_NO_THROW(function = functions.at(1)); - BOOST_CHECK_EQUAL(*function->getDocumentation(), "This is test function 2"); + checkFunctionNatspec(function, "This is test function 2"); BOOST_REQUIRE_NO_THROW(function = functions.at(2)); BOOST_CHECK_MESSAGE(function->getDocumentation() == nullptr, "Should not have gotten natspec comment for functionName3()"); BOOST_REQUIRE_NO_THROW(function = functions.at(3)); - BOOST_CHECK_EQUAL(*function->getDocumentation(), "This is test function 4"); + checkFunctionNatspec(function, "This is test function 4"); } BOOST_AUTO_TEST_CASE(multiline_function_documentation) @@ -193,9 +205,8 @@ BOOST_AUTO_TEST_CASE(multiline_function_documentation) auto functions = contract->getDefinedFunctions(); BOOST_REQUIRE_NO_THROW(function = functions.at(0)); - BOOST_CHECK_EQUAL(*function->getDocumentation(), - "This is a test function\n" - " and it has 2 lines"); + checkFunctionNatspec(function, "This is a test function\n" + " and it has 2 lines"); } BOOST_AUTO_TEST_CASE(natspec_comment_in_function_body) @@ -211,7 +222,6 @@ BOOST_AUTO_TEST_CASE(natspec_comment_in_function_body) " mapping(address=>hash) d;\n" " string name = \"Solidity\";" " }\n" - " uint256 stateVar;\n" " /// This is a test function\n" " /// and it has 2 lines\n" " function fun(hash hashin) returns (hash hashout) {}\n" @@ -220,12 +230,11 @@ BOOST_AUTO_TEST_CASE(natspec_comment_in_function_body) auto functions = contract->getDefinedFunctions(); BOOST_REQUIRE_NO_THROW(function = functions.at(0)); - BOOST_CHECK_EQUAL(*function->getDocumentation(), "fun1 description"); + checkFunctionNatspec(function, "fun1 description"); BOOST_REQUIRE_NO_THROW(function = functions.at(1)); - BOOST_CHECK_EQUAL(*function->getDocumentation(), - "This is a test function\n" - " and it has 2 lines"); + checkFunctionNatspec(function, "This is a test function\n" + " and it has 2 lines"); } BOOST_AUTO_TEST_CASE(natspec_docstring_between_keyword_and_signature) @@ -540,6 +549,78 @@ BOOST_AUTO_TEST_CASE(contract_multiple_inheritance_with_arguments) BOOST_CHECK_NO_THROW(parseText(text)); } +BOOST_AUTO_TEST_CASE(placeholder_in_function_context) +{ + char const* text = "contract c {\n" + " function fun() returns (uint r) {\n" + " var _ = 8;\n" + " return _ + 1;" + " }\n" + "}\n"; + BOOST_CHECK_NO_THROW(parseText(text)); +} + +BOOST_AUTO_TEST_CASE(modifier) +{ + char const* text = "contract c {\n" + " modifier mod { if (msg.sender == 0) _ }\n" + "}\n"; + BOOST_CHECK_NO_THROW(parseText(text)); +} + +BOOST_AUTO_TEST_CASE(modifier_arguments) +{ + char const* text = "contract c {\n" + " modifier mod(uint a) { if (msg.sender == a) _ }\n" + "}\n"; + BOOST_CHECK_NO_THROW(parseText(text)); +} + +BOOST_AUTO_TEST_CASE(modifier_invocation) +{ + char const* text = "contract c {\n" + " modifier mod1(uint a) { if (msg.sender == a) _ }\n" + " modifier mod2 { if (msg.sender == 2) _ }\n" + " function f() mod1(7) mod2 { }\n" + "}\n"; + BOOST_CHECK_NO_THROW(parseText(text)); +} + +BOOST_AUTO_TEST_CASE(fallback_function) +{ + char const* text = "contract c {\n" + " function() { }\n" + "}\n"; + BOOST_CHECK_NO_THROW(parseText(text)); +} + +BOOST_AUTO_TEST_CASE(event) +{ + char const* text = R"( + contract c { + event e(); + })"; + BOOST_CHECK_NO_THROW(parseText(text)); +} + +BOOST_AUTO_TEST_CASE(event_arguments) +{ + char const* text = R"( + contract c { + event e(uint a, string32 s); + })"; + BOOST_CHECK_NO_THROW(parseText(text)); +} + +BOOST_AUTO_TEST_CASE(event_arguments_indexed) +{ + char const* text = R"( + contract c { + event e(uint a, string32 indexed s, bool indexed b); + })"; + BOOST_CHECK_NO_THROW(parseText(text)); +} + BOOST_AUTO_TEST_SUITE_END() } diff --git a/commonjs.cpp b/commonjs.cpp new file mode 100644 index 000000000..860b713dd --- /dev/null +++ b/commonjs.cpp @@ -0,0 +1,57 @@ +/* + 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 . +*/ +/** @file commonjs.cpp + * @author Marek Kotewicz + * @date 2014 + */ + +#include +#include + +BOOST_AUTO_TEST_SUITE(commonjs) +using namespace std; +using namespace dev; +using namespace dev::eth; + +BOOST_AUTO_TEST_CASE(jsToPublic) +{ + cnote << "Testing jsToPublic..."; + KeyPair kp = KeyPair::create(); + string string = toJS(kp.pub()); + Public pub = dev::jsToPublic(string); + BOOST_CHECK_EQUAL(kp.pub(), pub); +} + +BOOST_AUTO_TEST_CASE(jsToAddress) +{ + cnote << "Testing jsToPublic..."; + KeyPair kp = KeyPair::create(); + string string = toJS(kp.address()); + Address address = dev::jsToAddress(string); + BOOST_CHECK_EQUAL(kp.address(), address); +} + +BOOST_AUTO_TEST_CASE(jsToSecret) +{ + cnote << "Testing jsToPublic..."; + KeyPair kp = KeyPair::create(); + string string = toJS(kp.secret()); + Secret secret = dev::jsToSecret(string); + BOOST_CHECK_EQUAL(kp.secret(), secret); +} + +BOOST_AUTO_TEST_SUITE_END() diff --git a/jsonrpc.cpp b/jsonrpc.cpp index 42b1a5ebb..1f0a466b2 100644 --- a/jsonrpc.cpp +++ b/jsonrpc.cpp @@ -31,8 +31,6 @@ #include #include #include -#include -//#include #include #include #include diff --git a/solidityExecutionFramework.h b/solidityExecutionFramework.h index 271a594c4..5a6935365 100644 --- a/solidityExecutionFramework.h +++ b/solidityExecutionFramework.h @@ -45,10 +45,11 @@ public: bytes const& compileAndRun(std::string const& _sourceCode, u256 const& _value = 0, std::string const& _contractName = "") { - dev::solidity::CompilerStack compiler; + dev::solidity::CompilerStack compiler(m_addStandardSources); try { - compiler.compile(_sourceCode, m_optimize); + compiler.addSource("", _sourceCode); + compiler.compile(m_optimize); } catch(boost::exception const& _e) { @@ -66,7 +67,6 @@ public: 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); return m_output; @@ -173,6 +173,7 @@ private: protected: bool m_optimize = false; + bool m_addStandardSources = false; Address m_sender; Address m_contractAddress; eth::State m_state; diff --git a/stSpecialTestFiller.json b/stSpecialTestFiller.json index fcb1d74a6..3691df80f 100644 --- a/stSpecialTestFiller.json +++ b/stSpecialTestFiller.json @@ -37,5 +37,36 @@ "secretKey" : "45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8", "data" : "" } + }, + + "OverflowGasMakeMoney" : { + "env" : { + "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "currentDifficulty" : "45678256", + "currentGasLimit" : "(2**256)-1", + "currentGasLimit" : "115792089237316195423570985008687907853269984665640564039457584007913129639935", + "currentNumber" : "0", + "currentTimestamp" : 1, + "previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6" + }, + "pre" : { + "a94f5374fce5edbc8e2a8697c15331677e6ebf0b" : { + "balance" : "1000", + "code" : "", + "nonce" : "0", + "storage" : { + } + } + }, + "transaction" : + { + "data" : "", + "gasLimit" : "115792089237316195423570985008687907853269984665640564039457584007913129639435", + "gasPrice" : "1", + "nonce" : "0", + "secretKey" : "45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8", + "to" : "b94f5374fce5edbc8e2a8697c15331677e6ebf0b", + "value" : "501" + } } } diff --git a/whisperTopic.cpp b/whisperTopic.cpp index 79adf3d6a..0162124b8 100644 --- a/whisperTopic.cpp +++ b/whisperTopic.cpp @@ -46,16 +46,16 @@ BOOST_AUTO_TEST_CASE(topic) auto wh = ph.registerCapability(new WhisperHost()); ph.start(); - started = true; - /// Only interested in odd packets auto w = wh->installWatch(BuildTopicMask("odd")); - for (int i = 0, last = 0; i < 200 && last < 81; ++i) + started = true; + + for (int iterout = 0, last = 0; iterout < 200 && last < 81; ++iterout) { for (auto i: wh->checkWatch(w)) { - Message msg = wh->envelope(i).open(); + Message msg = wh->envelope(i).open(wh->fullTopic(w)); last = RLP(msg.payload()).toInt(); cnote << "New message from:" << msg.from().abridged() << RLP(msg.payload()).toInt(); result += last; @@ -68,7 +68,7 @@ BOOST_AUTO_TEST_CASE(topic) this_thread::sleep_for(chrono::milliseconds(50)); Host ph("Test", NetworkPreferences(50300, "", false, true)); - auto wh = ph.registerCapability(new WhisperHost()); + shared_ptr wh = ph.registerCapability(new WhisperHost()); this_thread::sleep_for(chrono::milliseconds(500)); ph.start(); this_thread::sleep_for(chrono::milliseconds(500)); @@ -87,4 +87,188 @@ BOOST_AUTO_TEST_CASE(topic) BOOST_REQUIRE_EQUAL(result, 1 + 9 + 25 + 49 + 81); } +BOOST_AUTO_TEST_CASE(forwarding) +{ + cnote << "Testing Whisper forwarding..."; + auto oldLogVerbosity = g_logVerbosity; + g_logVerbosity = 0; + + unsigned result = 0; + bool done = false; + + bool startedListener = false; + std::thread listener([&]() + { + setThreadName("listener"); + + // Host must be configured not to share peers. + Host ph("Listner", NetworkPreferences(50303, "", false, true)); + ph.setIdealPeerCount(0); + auto wh = ph.registerCapability(new WhisperHost()); + ph.start(); + + startedListener = true; + + /// Only interested in odd packets + auto w = wh->installWatch(BuildTopicMask("test")); + + for (int i = 0; i < 200 && !result; ++i) + { + for (auto i: wh->checkWatch(w)) + { + Message msg = wh->envelope(i).open(wh->fullTopic(w)); + unsigned last = RLP(msg.payload()).toInt(); + cnote << "New message from:" << msg.from().abridged() << RLP(msg.payload()).toInt(); + result = last; + } + this_thread::sleep_for(chrono::milliseconds(50)); + } + }); + + bool startedForwarder = false; + std::thread forwarder([&]() + { + setThreadName("forwarder"); + + while (!startedListener) + this_thread::sleep_for(chrono::milliseconds(50)); + + // Host must be configured not to share peers. + Host ph("Forwarder", NetworkPreferences(50305, "", false, true)); + ph.setIdealPeerCount(0); + auto wh = ph.registerCapability(new WhisperHost()); + this_thread::sleep_for(chrono::milliseconds(500)); + ph.start(); + + this_thread::sleep_for(chrono::milliseconds(500)); + ph.connect("127.0.0.1", 50303); + + startedForwarder = true; + + /// Only interested in odd packets + auto w = wh->installWatch(BuildTopicMask("test")); + + while (!done) + { + for (auto i: wh->checkWatch(w)) + { + Message msg = wh->envelope(i).open(wh->fullTopic(w)); + cnote << "New message from:" << msg.from().abridged() << RLP(msg.payload()).toInt(); + } + this_thread::sleep_for(chrono::milliseconds(50)); + } + }); + + while (!startedForwarder) + this_thread::sleep_for(chrono::milliseconds(50)); + + Host ph("Sender", NetworkPreferences(50300, "", false, true)); + ph.setIdealPeerCount(0); + shared_ptr wh = ph.registerCapability(new WhisperHost()); + this_thread::sleep_for(chrono::milliseconds(500)); + ph.start(); + this_thread::sleep_for(chrono::milliseconds(500)); + ph.connect("127.0.0.1", 50305); + + KeyPair us = KeyPair::create(); + wh->post(us.sec(), RLPStream().append(1).out(), BuildTopic("test")); + this_thread::sleep_for(chrono::milliseconds(250)); + + listener.join(); + done = true; + forwarder.join(); + g_logVerbosity = oldLogVerbosity; + + BOOST_REQUIRE_EQUAL(result, 1); +} + +BOOST_AUTO_TEST_CASE(asyncforwarding) +{ + cnote << "Testing Whisper async forwarding..."; + auto oldLogVerbosity = g_logVerbosity; + g_logVerbosity = 2; + + unsigned result = 0; + bool done = false; + + bool startedForwarder = false; + std::thread forwarder([&]() + { + setThreadName("forwarder"); + + // Host must be configured not to share peers. + Host ph("Forwarder", NetworkPreferences(50305, "", false, true)); + ph.setIdealPeerCount(0); + auto wh = ph.registerCapability(new WhisperHost()); + this_thread::sleep_for(chrono::milliseconds(500)); + ph.start(); + + this_thread::sleep_for(chrono::milliseconds(500)); + ph.connect("127.0.0.1", 50303); + + startedForwarder = true; + + /// Only interested in odd packets + auto w = wh->installWatch(BuildTopicMask("test")); + + while (!done) + { + for (auto i: wh->checkWatch(w)) + { + Message msg = wh->envelope(i).open(wh->fullTopic(w)); + cnote << "New message from:" << msg.from().abridged() << RLP(msg.payload()).toInt(); + } + this_thread::sleep_for(chrono::milliseconds(50)); + } + }); + + while (!startedForwarder) + this_thread::sleep_for(chrono::milliseconds(50)); + + { + Host ph("Sender", NetworkPreferences(50300, "", false, true)); + ph.setIdealPeerCount(0); + shared_ptr wh = ph.registerCapability(new WhisperHost()); + this_thread::sleep_for(chrono::milliseconds(500)); + ph.start(); + this_thread::sleep_for(chrono::milliseconds(500)); + ph.connect("127.0.0.1", 50305); + + KeyPair us = KeyPair::create(); + wh->post(us.sec(), RLPStream().append(1).out(), BuildTopic("test")); + this_thread::sleep_for(chrono::milliseconds(250)); + } + + { + Host ph("Listener", NetworkPreferences(50300, "", false, true)); + ph.setIdealPeerCount(0); + shared_ptr wh = ph.registerCapability(new WhisperHost()); + this_thread::sleep_for(chrono::milliseconds(500)); + ph.start(); + this_thread::sleep_for(chrono::milliseconds(500)); + ph.connect("127.0.0.1", 50305); + + /// Only interested in odd packets + auto w = wh->installWatch(BuildTopicMask("test")); + + for (int i = 0; i < 200 && !result; ++i) + { + for (auto i: wh->checkWatch(w)) + { + Message msg = wh->envelope(i).open(wh->fullTopic(w)); + unsigned last = RLP(msg.payload()).toInt(); + cnote << "New message from:" << msg.from().abridged() << RLP(msg.payload()).toInt(); + result = last; + } + this_thread::sleep_for(chrono::milliseconds(50)); + } + } + + done = true; + forwarder.join(); + g_logVerbosity = oldLogVerbosity; + + BOOST_REQUIRE_EQUAL(result, 1); +} + BOOST_AUTO_TEST_SUITE_END()