diff options
author | chriseth <chris@ethereum.org> | 2017-07-31 22:14:46 +0800 |
---|---|---|
committer | GitHub <noreply@github.com> | 2017-07-31 22:14:46 +0800 |
commit | c2215d4605d1fbcef1366d6b822ec610fc031b3c (patch) | |
tree | 940ba55f0f27e8884332eaf90c11da48d5e98980 | |
parent | 0fb4cb1ab9bb4b6cc72e28cc5a1753ad14781f14 (diff) | |
parent | 2abfdb65c8dcda6866143280b7ff1bde094a1419 (diff) | |
download | dexon-solidity-c2215d4605d1fbcef1366d6b822ec610fc031b3c.tar.gz dexon-solidity-c2215d4605d1fbcef1366d6b822ec610fc031b3c.tar.zst dexon-solidity-c2215d4605d1fbcef1366d6b822ec610fc031b3c.zip |
Merge pull request #2667 from ethereum/develop
Merge develop into release in proparation for 0.4.14
194 files changed, 17492 insertions, 1581 deletions
diff --git a/CMakeLists.txt b/CMakeLists.txt index f7220b17..b29bc414 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -8,7 +8,7 @@ include(EthPolicy) eth_policy() # project name and version should be set after cmake_policy CMP0048 -set(PROJECT_VERSION "0.4.13") +set(PROJECT_VERSION "0.4.14") project(solidity VERSION ${PROJECT_VERSION}) # Let's find our dependencies diff --git a/Changelog.md b/Changelog.md index 4d84d7a1..af301fdd 100644 --- a/Changelog.md +++ b/Changelog.md @@ -1,3 +1,25 @@ +### 0.4.14 (2017-07-31) + +Features: + * C API (``jsonCompiler``): Export the ``license`` method. + * Code Generator: Optimise the fallback function, by removing a useless jump. + * Inline Assembly: Show useful error message if trying to access calldata variables. + * Inline Assembly: Support variable declaration without initial value (defaults to 0). + * Metadata: Only include files which were used to compile the given contract. + * Type Checker: Disallow value transfers to contracts without a payable fallback function. + * Type Checker: Include types in explicit conversion error message. + * Type Checker: Raise proper error for arrays too large for ABI encoding. + * Type checker: Warn if using ``this`` in a constructor. + * Type checker: Warn when existing symbols, including builtins, are overwritten. + +Bugfixes: + * Code Generator: Properly clear return memory area for ecrecover. + * Type Checker: Fix crash for some assignment to non-lvalue. + * Type Checker: Fix invalid "specify storage keyword" warning for reference members of structs. + * Type Checker: Mark modifiers as internal. + * Type Checker: Re-allow multiple mentions of the same modifier per function. + + ### 0.4.13 (2017-07-06) Features: diff --git a/ReleaseChecklist.md b/ReleaseChecklist.md new file mode 100644 index 00000000..b5df9fda --- /dev/null +++ b/ReleaseChecklist.md @@ -0,0 +1,19 @@ +Checklist for making a release: + + - [ ] Check that all "nextrelease" issues and pull requests are merged to ``develop``. + - [ ] Create a commit in ``develop`` that updates the ``Changelog`` to include a release date (run the tests locally to update the bug list). + - [ ] Create a pull request and wait for the tests, merge it. + - [ ] Create a pull request from ``develop`` to ``release``, wait for the tests, then merge it. + - [ ] Make a final check that there are no platform-dependency issues in the ``solc-test-bytecode`` repository. + - [ ] Wait for the tests for the commit on ``release``, create a release in Github, creating the tag. + - [ ] Thank voluntary contributors in the Github release page (use ``git shortlog -s -n -e origin/release..origin/develop``). + - [ ] Wait for the CI runs on the tag itself (they should push artefacts onto the Github release page). + - [ ] Run ``scripts/release_ppa.sh release`` to create the PPA release (you need the relevant openssl key). + - [ ] Check that the Docker release was pushed to Docker Hub (this still seems to have problems). + - [ ] Update the homebrew realease in https://github.com/ethereum/homebrew-ethereum/blob/master/solidity.rb (version and hash) + - [ ] Make a release of ``solc-js``: Increment the version number, create a pull request for that, merge it after tests succeeded. + - [ ] Run ``npm publish`` in the updated ``solc-js`` repository. + - [ ] Create a commit to increase the version number on ``develop`` in ``CMakeLists.txt`` and add a new skeleton changelog entry. + - [ ] Merge ``release`` back into ``develop``. + - [ ] Announce on Twitter and Reddit. + - [ ] Lean back, wait for bug reports and repeat from step 1 :) diff --git a/cmake/EthCompilerSettings.cmake b/cmake/EthCompilerSettings.cmake index ea3b185a..4ce9d22d 100644 --- a/cmake/EthCompilerSettings.cmake +++ b/cmake/EthCompilerSettings.cmake @@ -160,10 +160,24 @@ if (("${CMAKE_CXX_COMPILER_ID}" MATCHES "GNU") OR ("${CMAKE_CXX_COMPILER_ID}" MA endif() if (EMSCRIPTEN) - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} --memory-init-file 0 -O3 -s LINKABLE=1 -s DISABLE_EXCEPTION_CATCHING=0 -s NO_EXIT_RUNTIME=1 -s ALLOW_MEMORY_GROWTH=1 -s NO_DYNAMIC_EXECUTION=1") - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fdata-sections -ffunction-sections -Wl,--gc-sections") - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fvisibility=hidden") - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -s NO_FILESYSTEM=1 -s AGGRESSIVE_VARIABLE_ELIMINATION=1") + # Do emit a separate memory initialiser file + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} --memory-init-file 0") + # Leave only exported symbols as public and agressively remove others + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fdata-sections -ffunction-sections -Wl,--gc-sections -fvisibility=hidden") + # Optimisation level + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -O3") + # Re-enable exception catching (optimisations above -O1 disable it) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -s DISABLE_EXCEPTION_CATCHING=0") + # Remove any code related to exit (such as atexit) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -s NO_EXIT_RUNTIME=1") + # Remove any code related to filesystem access + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -s NO_FILESYSTEM=1") + # Remove variables even if it needs to be duplicated (can improve speed at the cost of size) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -s AGGRESSIVE_VARIABLE_ELIMINATION=1") + # Allow memory growth, but disable some optimisations + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -s ALLOW_MEMORY_GROWTH=1") + # Disable eval() + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -s NO_DYNAMIC_EXECUTION=1") add_definitions(-DETH_EMSCRIPTEN=1) endif() endif() diff --git a/docs/abi-spec.rst b/docs/abi-spec.rst index e39c8861..2cf57427 100644 --- a/docs/abi-spec.rst +++ b/docs/abi-spec.rst @@ -6,14 +6,14 @@ Application Binary Interface Specification ****************************************** -Basic design +Basic Design ============ The Application Binary Interface is the standard way to interact with contracts in the Ethereum ecosystem, both -from outside the blockchain and for contract-to-contract interaction. Data is encoded following its type, -according to this specification. +from outside the blockchain and for contract-to-contract interaction. Data is encoded according to its type, +as described in this specification. The encoding is not self describing and thus requires a schema in order to decode. -We assume the Application Binary Interface (ABI) is strongly typed, known at compilation time and static. No introspection mechanism will be provided. We assert that all contracts will have the interface definitions of any contracts they call available at compile-time. +We assume the interface functions of a contract are strongly typed, known at compilation time and static. No introspection mechanism will be provided. We assume that all contracts will have the interface definitions of any contracts they call available at compile-time. This specification does not address contracts whose interface is dynamic or otherwise known only at run-time. Should these cases become important they can be adequately handled as facilities built within the Ethereum ecosystem. @@ -58,7 +58,7 @@ The following (fixed-size) array type exists: - `<type>[M]`: a fixed-length array of the given fixed-length type. -The following non-fixed-size types exist: +The following non-fixed-size types exist: - `bytes`: dynamic sized byte sequence. @@ -93,6 +93,7 @@ We distinguish static and dynamic types. Static types are encoded in-place and d * `string` * `T[]` for any `T` * `T[k]` for any dynamic `T` and any `k > 0` +* `(T1,...,Tk)` if any `Ti` is dynamic for `1 <= i <= k` All other types are called "static". @@ -181,6 +182,8 @@ Given the contract: :: + pragma solidity ^0.4.0; + contract Foo { function bar(bytes3[2] xy) {} function baz(uint32 x, bool y) returns (bool r) { r = x > 32 || y; } @@ -313,6 +316,8 @@ For example, :: + pragma solidity ^0.4.0; + contract Test { function Test(){ b = 0x12345678901234567890123456789012; } event Event(uint indexed a, bytes32 b) @@ -334,10 +339,6 @@ would result in the JSON: "inputs": [{"name":"a","type":"uint256","indexed":true},{"name":"b","type":"bytes32","indexed":false}], "name":"Event2" }, { - "type":"event", - "inputs": [{"name":"a","type":"uint256","indexed":true},{"name":"b","type":"bytes32","indexed":false}], - "name":"Event2" - }, { "type":"function", "inputs": [{"name":"a","type":"uint256"}], "name":"foo", diff --git a/docs/assembly.rst b/docs/assembly.rst index 83643634..4e665b7e 100644 --- a/docs/assembly.rst +++ b/docs/assembly.rst @@ -92,7 +92,7 @@ you really know what you are doing. function sumAsm(uint[] _data) returns (uint o_sum) { for (uint i = 0; i < _data.length; ++i) { assembly { - o_sum := mload(add(add(_data, 0x20), mul(i, 0x20))) + o_sum := add(o_sum, mload(add(add(_data, 0x20), mul(i, 0x20)))) } } } @@ -110,7 +110,7 @@ these curly braces, the following can be used (see the later sections for more d - opcodes (in "instruction style"), e.g. ``mload sload dup1 sstore``, for a list see below - opcodes in functional style, e.g. ``add(1, mlod(0))`` - labels, e.g. ``name:`` - - variable declarations, e.g. ``let x := 7`` or ``let x := add(y, 3)`` + - variable declarations, e.g. ``let x := 7``, ``let x := add(y, 3)`` or ``let x`` (initial value of empty (0) is assigned) - identifiers (labels or assembly-local variables and externals if used as inline assembly), e.g. ``jump(name)``, ``3 x add`` - assignments (in "instruction style"), e.g. ``3 =: x`` - assignments in functional style, e.g. ``x := add(y, 3)`` @@ -490,7 +490,7 @@ is performed by replacing the variable's value on the stack by the new value. .. code:: - assembly { + { let v := 0 // functional-style assignment as part of variable declaration let g := add(v, 2) sload(10) @@ -509,7 +509,7 @@ case called ``default``. .. code:: - assembly { + { let x := 0 switch calldataload(4) case 0 { @@ -538,7 +538,7 @@ The following example computes the sum of an area in memory. .. code:: - assembly { + { let x := 0 for { let i := 0 } lt(i, 0x100) { i := add(i, 0x20) } { x := add(x, mload(i)) @@ -565,7 +565,7 @@ The following example implements the power function by square-and-multiply. .. code:: - assembly { + { function power(base, exponent) -> result { switch exponent case 0 { result := 1 } @@ -679,6 +679,8 @@ Example: We will follow an example compilation from Solidity to desugared assembly. We consider the runtime bytecode of the following Solidity program:: + pragma solidity ^0.4.0; + contract C { function f(uint x) returns (uint y) { y = 1; @@ -965,7 +967,7 @@ adjustment. Every time a new local variable is introduced, it is registered together with the current stack height. If a variable is accessed (either for copying its value or for assignment), the appropriate DUP or SWAP instruction is selected depending -on the difference bitween the current stack height and the +on the difference between the current stack height and the stack height at the point the variable was introduced. Pseudocode:: diff --git a/docs/bugs.json b/docs/bugs.json index a0c0e7c4..4fd73492 100644 --- a/docs/bugs.json +++ b/docs/bugs.json @@ -1,5 +1,12 @@ [ { + "name": "ECRecoverMalformedInput", + "summary": "The ecrecover() builtin can return garbage for malformed input.", + "description": "The ecrecover precompile does not properly signal failure for malformed input (especially in the 'v' argument) and thus the Solidity function can return data that was previously present in the return area in memory.", + "fixed": "0.4.14", + "severity": "medium" + }, + { "name": "SkipEmptyStringLiteral", "summary": "If \"\" is used in a function call, the following function arguments will not be correctly passed to the function.", "description": "If the empty string literal \"\" is used as an argument in a function call, it is skipped by the encoder. This has the effect that the encoding of all arguments following this is shifted left by 32 bytes and thus the function call data is corrupted.", @@ -107,4 +114,4 @@ "severity": "high", "fixed": "0.3.0" } -]
\ No newline at end of file +] diff --git a/docs/bugs_by_version.json b/docs/bugs_by_version.json index d6802eec..1a5b4f5f 100644 --- a/docs/bugs_by_version.json +++ b/docs/bugs_by_version.json @@ -1,6 +1,7 @@ { "0.1.0": { "bugs": [ + "ECRecoverMalformedInput", "SkipEmptyStringLiteral", "ConstantOptimizerSubtraction", "IdentityPrecompileReturnIgnored", @@ -16,6 +17,7 @@ }, "0.1.1": { "bugs": [ + "ECRecoverMalformedInput", "SkipEmptyStringLiteral", "ConstantOptimizerSubtraction", "IdentityPrecompileReturnIgnored", @@ -31,6 +33,7 @@ }, "0.1.2": { "bugs": [ + "ECRecoverMalformedInput", "SkipEmptyStringLiteral", "ConstantOptimizerSubtraction", "IdentityPrecompileReturnIgnored", @@ -46,6 +49,7 @@ }, "0.1.3": { "bugs": [ + "ECRecoverMalformedInput", "SkipEmptyStringLiteral", "ConstantOptimizerSubtraction", "IdentityPrecompileReturnIgnored", @@ -61,6 +65,7 @@ }, "0.1.4": { "bugs": [ + "ECRecoverMalformedInput", "SkipEmptyStringLiteral", "ConstantOptimizerSubtraction", "IdentityPrecompileReturnIgnored", @@ -76,6 +81,7 @@ }, "0.1.5": { "bugs": [ + "ECRecoverMalformedInput", "SkipEmptyStringLiteral", "ConstantOptimizerSubtraction", "IdentityPrecompileReturnIgnored", @@ -91,6 +97,7 @@ }, "0.1.6": { "bugs": [ + "ECRecoverMalformedInput", "SkipEmptyStringLiteral", "ConstantOptimizerSubtraction", "IdentityPrecompileReturnIgnored", @@ -107,6 +114,7 @@ }, "0.1.7": { "bugs": [ + "ECRecoverMalformedInput", "SkipEmptyStringLiteral", "ConstantOptimizerSubtraction", "IdentityPrecompileReturnIgnored", @@ -123,6 +131,7 @@ }, "0.2.0": { "bugs": [ + "ECRecoverMalformedInput", "SkipEmptyStringLiteral", "ConstantOptimizerSubtraction", "IdentityPrecompileReturnIgnored", @@ -139,6 +148,7 @@ }, "0.2.1": { "bugs": [ + "ECRecoverMalformedInput", "SkipEmptyStringLiteral", "ConstantOptimizerSubtraction", "IdentityPrecompileReturnIgnored", @@ -155,6 +165,7 @@ }, "0.2.2": { "bugs": [ + "ECRecoverMalformedInput", "SkipEmptyStringLiteral", "ConstantOptimizerSubtraction", "IdentityPrecompileReturnIgnored", @@ -171,6 +182,7 @@ }, "0.3.0": { "bugs": [ + "ECRecoverMalformedInput", "SkipEmptyStringLiteral", "ConstantOptimizerSubtraction", "IdentityPrecompileReturnIgnored", @@ -186,6 +198,7 @@ }, "0.3.1": { "bugs": [ + "ECRecoverMalformedInput", "SkipEmptyStringLiteral", "ConstantOptimizerSubtraction", "IdentityPrecompileReturnIgnored", @@ -200,6 +213,7 @@ }, "0.3.2": { "bugs": [ + "ECRecoverMalformedInput", "SkipEmptyStringLiteral", "ConstantOptimizerSubtraction", "IdentityPrecompileReturnIgnored", @@ -214,6 +228,7 @@ }, "0.3.3": { "bugs": [ + "ECRecoverMalformedInput", "SkipEmptyStringLiteral", "ConstantOptimizerSubtraction", "IdentityPrecompileReturnIgnored", @@ -227,6 +242,7 @@ }, "0.3.4": { "bugs": [ + "ECRecoverMalformedInput", "SkipEmptyStringLiteral", "ConstantOptimizerSubtraction", "IdentityPrecompileReturnIgnored", @@ -240,6 +256,7 @@ }, "0.3.5": { "bugs": [ + "ECRecoverMalformedInput", "SkipEmptyStringLiteral", "ConstantOptimizerSubtraction", "IdentityPrecompileReturnIgnored", @@ -253,6 +270,7 @@ }, "0.3.6": { "bugs": [ + "ECRecoverMalformedInput", "SkipEmptyStringLiteral", "ConstantOptimizerSubtraction", "IdentityPrecompileReturnIgnored", @@ -264,6 +282,7 @@ }, "0.4.0": { "bugs": [ + "ECRecoverMalformedInput", "SkipEmptyStringLiteral", "ConstantOptimizerSubtraction", "IdentityPrecompileReturnIgnored", @@ -275,6 +294,7 @@ }, "0.4.1": { "bugs": [ + "ECRecoverMalformedInput", "SkipEmptyStringLiteral", "ConstantOptimizerSubtraction", "IdentityPrecompileReturnIgnored", @@ -286,6 +306,7 @@ }, "0.4.10": { "bugs": [ + "ECRecoverMalformedInput", "SkipEmptyStringLiteral", "ConstantOptimizerSubtraction" ], @@ -293,20 +314,30 @@ }, "0.4.11": { "bugs": [ + "ECRecoverMalformedInput", "SkipEmptyStringLiteral" ], "released": "2017-05-03" }, "0.4.12": { - "bugs": [], + "bugs": [ + "ECRecoverMalformedInput" + ], "released": "2017-07-03" }, "0.4.13": { - "bugs": [], + "bugs": [ + "ECRecoverMalformedInput" + ], "released": "2017-07-06" }, + "0.4.14": { + "bugs": [], + "released": "2017-07-31" + }, "0.4.2": { "bugs": [ + "ECRecoverMalformedInput", "SkipEmptyStringLiteral", "ConstantOptimizerSubtraction", "IdentityPrecompileReturnIgnored", @@ -317,6 +348,7 @@ }, "0.4.3": { "bugs": [ + "ECRecoverMalformedInput", "SkipEmptyStringLiteral", "ConstantOptimizerSubtraction", "IdentityPrecompileReturnIgnored", @@ -326,6 +358,7 @@ }, "0.4.4": { "bugs": [ + "ECRecoverMalformedInput", "SkipEmptyStringLiteral", "ConstantOptimizerSubtraction", "IdentityPrecompileReturnIgnored" @@ -334,6 +367,7 @@ }, "0.4.5": { "bugs": [ + "ECRecoverMalformedInput", "SkipEmptyStringLiteral", "ConstantOptimizerSubtraction", "IdentityPrecompileReturnIgnored", @@ -343,6 +377,7 @@ }, "0.4.6": { "bugs": [ + "ECRecoverMalformedInput", "SkipEmptyStringLiteral", "ConstantOptimizerSubtraction", "IdentityPrecompileReturnIgnored" @@ -351,6 +386,7 @@ }, "0.4.7": { "bugs": [ + "ECRecoverMalformedInput", "SkipEmptyStringLiteral", "ConstantOptimizerSubtraction" ], @@ -358,6 +394,7 @@ }, "0.4.8": { "bugs": [ + "ECRecoverMalformedInput", "SkipEmptyStringLiteral", "ConstantOptimizerSubtraction" ], @@ -365,6 +402,7 @@ }, "0.4.9": { "bugs": [ + "ECRecoverMalformedInput", "SkipEmptyStringLiteral", "ConstantOptimizerSubtraction" ], diff --git a/docs/contracts.rst b/docs/contracts.rst index e9ea1b3b..da797702 100644 --- a/docs/contracts.rst +++ b/docs/contracts.rst @@ -84,7 +84,7 @@ This means that cyclic creation dependencies are impossible. // State variables are accessed via their name // and not via e.g. this.owner. This also applies // to functions and especially in the constructors, - // you can only call them like that ("internall"), + // you can only call them like that ("internally"), // because the contract itself does not exist yet. owner = msg.sender; // We do an explicit type conversion from `address` @@ -213,6 +213,8 @@ In the following example, ``D``, can call ``c.getData()`` to retrieve the value :: + // This will not compile + pragma solidity ^0.4.0; contract C { @@ -244,7 +246,7 @@ In the following example, ``D``, can call ``c.getData()`` to retrieve the value } .. index:: ! getter;function, ! function;getter -.. _getter_functions: +.. _getter-functions: Getter Functions ================ @@ -545,9 +547,11 @@ Please ensure you test your fallback function thoroughly to ensure the execution test.call(0xabcdef01); // hash does not exist // results in test.x becoming == 1. - // The following call will fail, reject the - // Ether and return false: - test.send(2 ether); + // The following will not compile, but even + // if someone sends ether to that contract, + // the transaction will fail and reject the + // Ether. + //test.send(2 ether); } } @@ -773,13 +777,17 @@ seen in the following example:: pragma solidity ^0.4.0; + contract owned { + function owned() { owner = msg.sender; } + address owner; + } + contract mortal is owned { function kill() { if (msg.sender == owner) selfdestruct(owner); } } - contract Base1 is mortal { function kill() { /* do cleanup 1 */ mortal.kill(); } } @@ -800,6 +808,11 @@ derived override, but this function will bypass pragma solidity ^0.4.0; + contract owned { + function owned() { owner = msg.sender; } + address owner; + } + contract mortal is owned { function kill() { if (msg.sender == owner) selfdestruct(owner); @@ -879,6 +892,8 @@ error "Linearization of inheritance graph impossible". :: + // This will not compile + pragma solidity ^0.4.0; contract X {} @@ -914,10 +929,16 @@ Contract functions can lack an implementation as in the following example (note function utterance() returns (bytes32); } -Such contracts cannot be compiled (even if they contain implemented functions alongside non-implemented functions), but they can be used as base contracts:: +Such contracts cannot be compiled (even if they contain +implemented functions alongside non-implemented functions), +but they can be used as base contracts:: pragma solidity ^0.4.0; + contract Feline { + function utterance() returns (bytes32); + } + contract Cat is Feline { function utterance() returns (bytes32) { return "miaow"; } } @@ -947,6 +968,8 @@ Interfaces are denoted by their own keyword: :: + pragma solidity ^0.4.11; + interface Token { function transfer(address recipient, uint amount); } diff --git a/docs/control-structures.rst b/docs/control-structures.rst index 03787c20..a7af69f5 100644 --- a/docs/control-structures.rst +++ b/docs/control-structures.rst @@ -20,6 +20,8 @@ For example, suppose we want our contract to accept one kind of external calls with two integers, we would write something like:: + pragma solidity ^0.4.0; + contract Simple { function taker(uint _a, uint _b) { // do something with _a and _b. @@ -34,6 +36,8 @@ The output parameters can be declared with the same syntax after the the sum and the product of the two given integers, then we would write:: + pragma solidity ^0.4.0; + contract Simple { function arithmetics(uint _a, uint _b) returns (uint o_sum, uint o_product) { o_sum = _a + _b; @@ -91,6 +95,8 @@ Internal Function Calls Functions of the current contract can be called directly ("internally"), also recursively, as seen in this nonsensical example:: + pragma solidity ^0.4.0; + contract C { function g(uint a) returns (uint ret) { return f(); } function f() returns (uint ret) { return g(7) + f(); } @@ -116,11 +122,12 @@ all function arguments have to be copied to memory. When calling functions of other contracts, the amount of Wei sent with the call and the gas can be specified with special options ``.value()`` and ``.gas()``, respectively:: + pragma solidity ^0.4.0; + contract InfoFeed { function info() payable returns (uint ret) { return 42; } } - contract Consumer { InfoFeed feed; function setFeed(address addr) { feed = InfoFeed(addr); } @@ -173,7 +180,9 @@ parameters from the function declaration, but can be in arbitrary order. pragma solidity ^0.4.0; contract C { - function f(uint key, uint value) { ... } + function f(uint key, uint value) { + // ... + } function g() { // named arguments @@ -221,7 +230,6 @@ creation-dependencies are not possible. } } - contract C { D d = new D(4); // will be executed as part of C's constructor @@ -261,6 +269,8 @@ Destructuring Assignments and Returning Multiple Values Solidity internally allows tuple types, i.e. a list of objects of potentially different types whose size is a constant at compile-time. Those tuples can be used to return multiple values at the same time and also assign them to multiple variables (or LValues in general) at the same time:: + pragma solidity ^0.4.0; + contract C { uint[] data; @@ -313,6 +323,8 @@ This happens because Solidity inherits its scoping rules from JavaScript. This is in contrast to many languages where variables are only scoped where they are declared until the end of the semantic block. As a result, the following code is illegal and cause the compiler to throw an error, ``Identifier already declared``:: + // This will not compile + pragma solidity ^0.4.0; contract ScopingErrors { @@ -369,13 +381,11 @@ Error handling: Assert, Require, Revert and Exceptions Solidity uses state-reverting exceptions to handle errors. Such an exception will undo all changes made to the state in the current call (and all its sub-calls) and also flag an error to the caller. The convenience functions ``assert`` and ``require`` can be used to check for conditions and throw an exception -if the condition is not met. The difference between the two is that ``assert`` should only be used for internal errors -and ``require`` should be used to check external conditions (invalid inputs or errors in external components). -The idea behind that is that analysis tools can check your contract and try to come up with situations and -series of function calls that will reach a failing assertion. If this is possible, this means there is a bug -in your contract you should fix. +if the condition is not met. The ``assert`` function should only be used to test for internal errors, and to check invariants. +The ``require`` function should be used to ensure valid conditions, such as inputs, or contract state variables are met, or to validate return values from calls to external contracts. +If used properly, analysis tools can evaluate your contract to identify the conditions and function calls which will reach a failing ``assert``. Properly functioning code should never reach a failing assert statement; if this happens there is a bug in your contract which you should fix. -There are two other ways to trigger execptions: The ``revert`` function can be used to flag an error and +There are two other ways to trigger exceptions: The ``revert`` function can be used to flag an error and revert the current call. In the future it might be possible to also include details about the error in a call to ``revert``. The ``throw`` keyword can also be used as an alternative to ``revert()``. @@ -429,4 +439,4 @@ Internally, Solidity performs a revert operation (instruction ``0xfd``) for a `` the EVM to revert all changes made to the state. The reason for reverting is that there is no safe way to continue execution, because an expected effect did not occur. Because we want to retain the atomicity of transactions, the safest thing to do is to revert all changes and make the whole transaction (or at least call) without effect. Note that ``assert``-style exceptions consume all gas available to the call, while -``revert``-style exceptions will not consume any gas starting from the Metropolis release.
\ No newline at end of file +``require``-style exceptions will not consume any gas starting from the Metropolis release. diff --git a/docs/frequently-asked-questions.rst b/docs/frequently-asked-questions.rst index 03ee8388..73210991 100644 --- a/docs/frequently-asked-questions.rst +++ b/docs/frequently-asked-questions.rst @@ -116,6 +116,8 @@ array in the return statement. Pretty cool, huh? Example:: + pragma solidity ^0.4.0; + contract C { function f() returns (uint8[5]) { string[4] memory adaArr = ["This", "is", "an", "array"]; @@ -192,6 +194,8 @@ should be noted that you must declare them as static memory arrays. Examples:: + pragma solidity ^0.4.0; + contract C { struct S { uint a; @@ -200,10 +204,9 @@ Examples:: S public x = S(1, 2); string name = "Ada"; - string[4] memory adaArr = ["This", "is", "an", "array"]; + string[4] adaArr = ["This", "is", "an", "array"]; } - contract D { C c = new C(); } @@ -243,6 +246,8 @@ which will be extended in the future. In addition, Arachnid has written `solidit For now, if you want to modify a string (even when you only want to know its length), you should always convert it to a ``bytes`` first:: + pragma solidity ^0.4.0; + contract C { string s; @@ -288,6 +293,8 @@ situation. If you do not want to throw, you can return a pair:: + pragma solidity ^0.4.0; + contract C { uint[] counters; @@ -302,9 +309,9 @@ If you do not want to throw, you can return a pair:: function checkCounter(uint index) { var (counter, error) = getCounter(index); if (error) { - ... + // ... } else { - ... + // ... } } } @@ -363,6 +370,8 @@ of variable it concerns: Example:: + pragma solidity ^0.4.0; + contract C { uint[] data1; uint[] data2; @@ -375,7 +384,7 @@ Example:: append(data2); } - function append(uint[] storage d) { + function append(uint[] storage d) internal { d.push(1); } } @@ -393,6 +402,9 @@ A common mistake is to declare a local variable and assume that it will be created in memory, although it will be created in storage:: /// THIS CONTRACT CONTAINS AN ERROR + + pragma solidity ^0.4.0; + contract C { uint someVariable; uint[] data; @@ -417,6 +429,8 @@ slot ``0``) is modified by ``x.push(2)``. The correct way to do this is the following:: + pragma solidity ^0.4.0; + contract C { uint someVariable; uint[] data; @@ -533,11 +547,12 @@ In the case of a ``contract A`` calling a new instance of ``contract B``, parent You will need to make sure that you have both contracts aware of each other's presence and that ``contract B`` has a ``payable`` constructor. In this example:: + pragma solidity ^0.4.0; + contract B { function B() payable {} } - contract A { address child; @@ -580,6 +595,8 @@ Can a contract pass an array (static size) or string or ``bytes`` (dynamic size) Sure. Take care that if you cross the memory / storage boundary, independent copies will be created:: + pragma solidity ^0.4.0; + contract C { uint[20] x; @@ -588,11 +605,11 @@ independent copies will be created:: h(x); } - function g(uint[20] y) { + function g(uint[20] y) internal { y[2] = 3; } - function h(uint[20] storage y) { + function h(uint[20] storage y) internal { y[3] = 4; } } diff --git a/docs/index.rst b/docs/index.rst index 3cdda62d..dea11a86 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -41,9 +41,6 @@ Available Solidity Integrations * `Remix <https://remix.ethereum.org/>`_ Browser-based IDE with integrated compiler and Solidity runtime environment without server-side components. -* `Ethereum Studio <https://live.ether.camp/>`_ - Specialized web IDE that also provides shell access to a complete Ethereum environment. - * `IntelliJ IDEA plugin <https://plugins.jetbrains.com/plugin/9475-intellij-solidity>`_ Solidity plugin for IntelliJ IDEA (and all other JetBrains IDEs) @@ -82,6 +79,8 @@ Discontinued: * `Mix IDE <https://github.com/ethereum/mix/>`_ Qt based IDE for designing, debugging and testing solidity smart contracts. +* `Ethereum Studio <https://live.ether.camp/>`_ + Specialized web IDE that also provides shell access to a complete Ethereum environment. Solidity Tools -------------- diff --git a/docs/installing-solidity.rst b/docs/installing-solidity.rst index 9b5ba9f2..e07561c5 100644 --- a/docs/installing-solidity.rst +++ b/docs/installing-solidity.rst @@ -82,6 +82,10 @@ If you want to use the cutting edge developer version: sudo add-apt-repository ppa:ethereum/ethereum-dev sudo apt-get update sudo apt-get install solc + +We are also releasing a `snap package <https://snapcraft.io/>`_, which is installable in all the `supported Linux distros <https://snapcraft.io/docs/core/install>`_. To help testing the unstable solc with the most recent changes from the development branch: + + sudo snap install solc --edge Arch Linux also has packages, albeit limited to the latest development version: diff --git a/docs/layout-of-source-files.rst b/docs/layout-of-source-files.rst index e4b403f6..f9d197b7 100644 --- a/docs/layout-of-source-files.rst +++ b/docs/layout-of-source-files.rst @@ -197,17 +197,16 @@ for the two input parameters and two returned values. pragma solidity ^0.4.0; - /** @title Shape calculator.*/ - contract shapeCalculator{ - /**@dev Calculates a rectangle's surface and perimeter. - * @param w Width of the rectangle. - * @param h Height of the rectangle. - * @return s The calculated surface. - * @return p The calculated perimeter. - */ - function rectangle(uint w, uint h) returns (uint s, uint p) { - s = w * h; - p = 2 * (w + h); - } - } - + /** @title Shape calculator. */ + contract shapeCalculator { + /** @dev Calculates a rectangle's surface and perimeter. + * @param w Width of the rectangle. + * @param h Height of the rectangle. + * @return s The calculated surface. + * @return p The calculated perimeter. + */ + function rectangle(uint w, uint h) returns (uint s, uint p) { + s = w * h; + p = 2 * (w + h); + } + } diff --git a/docs/miscellaneous.rst b/docs/miscellaneous.rst index 182de33a..e364bee7 100644 --- a/docs/miscellaneous.rst +++ b/docs/miscellaneous.rst @@ -48,6 +48,8 @@ non-elementary type, the positions are found by adding an offset of ``keccak256( So for the following contract snippet:: + pragma solidity ^0.4.0; + contract C { struct s { uint a; uint b; } uint x; @@ -467,7 +469,7 @@ Global Variables - ``require(bool condition)``: abort execution and revert state changes if condition is ``false`` (use for malformed input or error in external component) - ``revert()``: abort execution and revert state changes - ``keccak256(...) returns (bytes32)``: compute the Ethereum-SHA-3 (Keccak-256) hash of the (tightly packed) arguments -- ``sha3(...) returns (bytes32)``: an alias to `keccak256()` +- ``sha3(...) returns (bytes32)``: an alias to `keccak256` - ``sha256(...) returns (bytes32)``: compute the SHA-256 hash of the (tightly packed) arguments - ``ripemd160(...) returns (bytes20)``: compute the RIPEMD-160 hash of the (tightly packed) arguments - ``ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) returns (address)``: recover address associated with the public key from elliptic curve signature, return zero on error @@ -476,6 +478,7 @@ Global Variables - ``this`` (current contract's type): the current contract, explicitly convertible to ``address`` - ``super``: the contract one level higher in the inheritance hierarchy - ``selfdestruct(address recipient)``: destroy the current contract, sending its funds to the given address +- ``suicide(address recipieint)``: an alias to `selfdestruct`` - ``<address>.balance`` (``uint256``): balance of the :ref:`address` in Wei - ``<address>.send(uint256 amount) returns (bool)``: send given amount of Wei to :ref:`address`, returns ``false`` on failure - ``<address>.transfer(uint256 amount)``: send given amount of Wei to :ref:`address`, throws on failure @@ -513,7 +516,7 @@ Reserved Keywords These keywords are reserved in Solidity. They might become part of the syntax in the future: -``abstract``, ``after``, ``case``, ``catch``, ``default``, ``final``, ``in``, ``inline``, ``interface``, ``let``, ``match``, ``null``, +``abstract``, ``after``, ``case``, ``catch``, ``default``, ``final``, ``in``, ``inline``, ``let``, ``match``, ``null``, ``of``, ``pure``, ``relocatable``, ``static``, ``switch``, ``try``, ``type``, ``typeof``, ``view``. Language Grammar diff --git a/docs/security-considerations.rst b/docs/security-considerations.rst index 33c613d8..6586cb5f 100644 --- a/docs/security-considerations.rst +++ b/docs/security-considerations.rst @@ -14,7 +14,7 @@ the source code is often available. Of course you always have to consider how much is at stake: You can compare a smart contract with a web service that is open to the -public (and thus, also to malicous actors) and perhaps even open source. +public (and thus, also to malicious actors) and perhaps even open source. If you only store your grocery list on that web service, you might not have to take too much care, but if you manage your bank account using that web service, you should be more careful. @@ -179,11 +179,13 @@ Never use tx.origin for authorization. Let's say you have a wallet contract like } } -Now someone tricks you into sending ether to the address of this attack wallet: +Now someone tricks you into sending ether to the address of this attack wallet:: -:: + pragma solidity ^0.4.11; - pragma solidity ^0.4.0; + interface TxUserWallet { + function transferTo(address dest, uint amount); + } contract TxAttackWallet { address owner; @@ -278,8 +280,7 @@ Formal Verification Using formal verification, it is possible to perform an automated mathematical proof that your source code fulfills a certain formal specification. The specification is still formal (just as the source code), but usually much -simpler. There is a prototype in Solidity that performs formal verification and -it will be better documented soon. +simpler. Note that formal verification itself can only help you understand the difference between what you did (the specification) and how you did it diff --git a/docs/solidity-by-example.rst b/docs/solidity-by-example.rst index 450b0286..71d27192 100644 --- a/docs/solidity-by-example.rst +++ b/docs/solidity-by-example.rst @@ -101,7 +101,7 @@ of votes. /// Delegate your vote to the voter `to`. function delegate(address to) { // assigns reference - Voter sender = voters[msg.sender]; + Voter storage sender = voters[msg.sender]; require(!sender.voted); // Self-delegation is not allowed. @@ -141,7 +141,7 @@ of votes. /// Give your vote (including votes delegated to you) /// to proposal `proposals[proposal].name`. function vote(uint proposal) { - Voter sender = voters[msg.sender]; + Voter storage sender = voters[msg.sender]; require(!sender.voted); sender.voted = true; sender.vote = proposal; @@ -289,7 +289,7 @@ activate themselves. /// Withdraw a bid that was overbid. function withdraw() returns (bool) { - var amount = pendingReturns[msg.sender]; + uint amount = pendingReturns[msg.sender]; if (amount > 0) { // It is important to set this to zero because the recipient // can call this function again as part of the receiving call @@ -362,8 +362,8 @@ together with the bid. Since value transfers cannot be blinded in Ethereum, anyone can see the value. The following contract solves this problem by -accepting any value that is at least as large as -the bid. Since this can of course only be checked during +accepting any value that is larger than the highest +bid. Since this can of course only be checked during the reveal phase, some bids might be **invalid**, and this is on purpose (it even provides an explicit flag to place invalid bids with high value transfers): @@ -491,8 +491,8 @@ high or low invalid bids. } /// Withdraw a bid that was overbid. - function withdraw() returns (bool) { - var amount = pendingReturns[msg.sender]; + function withdraw() { + uint amount = pendingReturns[msg.sender]; if (amount > 0) { // It is important to set this to zero because the recipient // can call this function again as part of the receiving call @@ -500,13 +500,8 @@ high or low invalid bids. // conditions -> effects -> interaction). pendingReturns[msg.sender] = 0; - if (!msg.sender.send(amount)){ - // No need to call throw here, just reset the amount owing - pendingReturns[msg.sender] = amount; - return false; - } + msg.sender.transfer(amount); } - return true; } /// End the auction and send the highest bid diff --git a/docs/types.rst b/docs/types.rst index 319701c7..dd9c6269 100644 --- a/docs/types.rst +++ b/docs/types.rst @@ -135,6 +135,9 @@ The ``.gas()`` option is available on all three methods, while the ``.value()`` All contracts inherit the members of address, so it is possible to query the balance of the current contract using ``this.balance``. +.. note:: + The use of ``callcode`` is discouraged and will be removed in the future. + .. warning:: All these functions are low-level functions and should be used with care. Specifically, any unknown contract might be malicious and if you call it, you @@ -222,14 +225,6 @@ For example, ``(2**800 + 1) - 2**800`` results in the constant ``1`` (of type `` although intermediate results would not even fit the machine word size. Furthermore, ``.5 * 8`` results in the integer ``4`` (although non-integers were used in between). -If the result is not an integer, -an appropriate ``ufixed`` or ``fixed`` type is used whose number of fractional bits is as large as -required (approximating the rational number in the worst case). - -In ``var x = 1/4;``, ``x`` will receive the type ``ufixed0x8`` while in ``var x = 1/3`` it will receive -the type ``ufixed0x256`` because ``1/3`` is not finitely representable in binary and will thus be -approximated. - Any operator that can be applied to integers can also be applied to number literal expressions as long as the operands are integers. If any of the two is fractional, bit operations are disallowed and exponentiation is disallowed if the exponent is fractional (because that might result in @@ -243,20 +238,14 @@ a non-rational number). types. So the number literal expressions ``1 + 2`` and ``2 + 1`` both belong to the same number literal type for the rational number three. -.. note:: - Most finite decimal fractions like ``5.3743`` are not finitely representable in binary. The correct type - for ``5.3743`` is ``ufixed8x248`` because that allows to best approximate the number. If you want to - use the number together with types like ``ufixed`` (i.e. ``ufixed128x128``), you have to explicitly - specify the desired precision: ``x + ufixed(5.3743)``. - .. warning:: Division on integer literals used to truncate in earlier versions, but it will now convert into a rational number, i.e. ``5 / 2`` is not equal to ``2``, but to ``2.5``. .. note:: Number literal expressions are converted into a non-literal type as soon as they are used with non-literal expressions. Even though we know that the value of the - expression assigned to ``b`` in the following example evaluates to an integer, it still - uses fixed point types (and not rational number literals) in between and so the code + expression assigned to ``b`` in the following example evaluates to + an integer, but the partial expression ``2.5 + a`` does not type check so the code does not compile :: @@ -390,7 +379,7 @@ Example that shows how to use internal function types:: function (uint, uint) returns (uint) f ) internal - returns (uint) + returns (uint r) { r = self[0]; for (uint i = 1; i < self.length; i++) { @@ -450,7 +439,8 @@ Another example that uses external function types:: } } -Note that lambda or inline functions are planned but not yet supported. +.. note:: + Lambda or inline functions are planned but not yet supported. .. index:: ! type;reference, ! reference type, storage, memory, location, array, struct @@ -557,7 +547,7 @@ So ``bytes`` should always be preferred over ``byte[]`` because it is cheaper. that you are accessing the low-level bytes of the UTF-8 representation, and not the individual characters! -It is possible to mark arrays ``public`` and have Solidity create a getter. +It is possible to mark arrays ``public`` and have Solidity create a :ref:`getter <visibility-and-getters>`. The numeric index will become a required parameter for the getter. .. index:: ! array;allocating, new @@ -613,6 +603,8 @@ possible: :: + // This will not compile. + pragma solidity ^0.4.0; contract C { @@ -620,6 +612,7 @@ possible: // The next line creates a type error because uint[3] memory // cannot be converted to uint[] memory. uint[] x = [uint(1), 3, 4]; + } } It is planned to remove this restriction in the future but currently creates @@ -750,7 +743,7 @@ shown in the following example: } function contribute(uint campaignID) payable { - Campaign c = campaigns[campaignID]; + Campaign storage c = campaigns[campaignID]; // Creates a new temporary memory struct, initialised with the given values // and copies it over to storage. // Note that you can also use Funder(msg.sender, msg.value) to initialise. @@ -759,7 +752,7 @@ shown in the following example: } function checkGoalReached(uint campaignID) returns (bool reached) { - Campaign c = campaigns[campaignID]; + Campaign storage c = campaigns[campaignID]; if (c.amount < c.fundingGoal) return false; uint amount = c.amount; @@ -806,7 +799,7 @@ Because of this, mappings do not have a length or a concept of a key or value be Mappings are only allowed for state variables (or as storage reference types in internal functions). -It is possible to mark mappings ``public`` and have Solidity create a getter. +It is possible to mark mappings ``public`` and have Solidity create a :ref:`getter <visibility-and-getters>`. The ``_KeyType`` will become a required parameter for the getter and it will return ``_ValueType``. @@ -827,7 +820,9 @@ for each ``_KeyType``, recursively. contract MappingUser { function f() returns (uint) { - return MappingExample(<address>).balances(this); + MappingExample m = new MappingExample(); + m.update(100); + return m.balances(this); } } diff --git a/docs/units-and-global-variables.rst b/docs/units-and-global-variables.rst index 7d21f065..64795306 100644 --- a/docs/units-and-global-variables.rst +++ b/docs/units-and-global-variables.rst @@ -35,7 +35,9 @@ These suffixes cannot be applied to variables. If you want to interpret some input variable in e.g. days, you can do it in the following way:: function f(uint start, uint daysAfter) { - if (now >= start + daysAfter * 1 days) { ... } + if (now >= start + daysAfter * 1 days) { + // ... + } } Special Variables and Functions @@ -70,6 +72,7 @@ Block and Transaction Properties ``msg.value`` can change for every **external** function call. This includes calls to library functions. +.. note:: If you want to implement access restrictions in library functions using ``msg.sender``, you have to manually supply the value of ``msg.sender`` as an argument. @@ -102,10 +105,10 @@ Mathematical and Cryptographic Functions compute ``(x * y) % k`` where the multiplication is performed with arbitrary precision and does not wrap around at ``2**256``. ``keccak256(...) returns (bytes32)``: compute the Ethereum-SHA-3 (Keccak-256) hash of the (tightly packed) arguments -``sha3(...) returns (bytes32)``: - alias to ``keccak256()`` ``sha256(...) returns (bytes32)``: compute the SHA-256 hash of the (tightly packed) arguments +``sha3(...) returns (bytes32)``: + alias to ``keccak256`` ``ripemd160(...) returns (bytes20)``: compute RIPEMD-160 hash of the (tightly packed) arguments ``ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) returns (address)``: @@ -157,6 +160,9 @@ For more information, see the section on :ref:`address`. to make safe Ether transfers, always check the return value of ``send``, use ``transfer`` or even better: Use a pattern where the recipient withdraws the money. +.. note:: + The use of ``callcode`` is discouraged and will be removed in the future. + .. index:: this, selfdestruct Contract Related @@ -168,5 +174,8 @@ Contract Related ``selfdestruct(address recipient)``: destroy the current contract, sending its funds to the given :ref:`address` +``suicide(address recipient)``: + alias to ``selfdestruct`` + Furthermore, all functions of the current contract are callable directly including the current function. diff --git a/libdevcore/CommonData.h b/libdevcore/CommonData.h index 98ad548d..ab4bfe68 100644 --- a/libdevcore/CommonData.h +++ b/libdevcore/CommonData.h @@ -23,13 +23,14 @@ #pragma once +#include <libdevcore/Common.h> + #include <vector> #include <algorithm> #include <unordered_set> #include <type_traits> #include <cstring> #include <string> -#include "Common.h" namespace dev { @@ -165,6 +166,12 @@ template <class T, class U> std::vector<T>& operator+=(std::vector<T>& _a, U con _a.push_back(i); return _a; } +/// Concatenate the contents of a container onto a set +template <class T, class U> std::set<T>& operator+=(std::set<T>& _a, U const& _b) +{ + _a.insert(_b.begin(), _b.end()); + return _a; +} /// Concatenate two vectors of elements. template <class T> inline std::vector<T> operator+(std::vector<T> const& _a, std::vector<T> const& _b) diff --git a/libdevcore/Exceptions.cpp b/libdevcore/Exceptions.cpp new file mode 100644 index 00000000..f422d926 --- /dev/null +++ b/libdevcore/Exceptions.cpp @@ -0,0 +1,49 @@ +/* + This file is part of solidity. + + solidity 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. + + solidity 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 solidity. If not, see <http://www.gnu.org/licenses/>. +*/ + +#include <libdevcore/Exceptions.h> + +#include <boost/lexical_cast.hpp> + +using namespace std; +using namespace dev; + +char const* Exception::what() const noexcept +{ + if (string const* cmt = comment()) + return cmt->c_str(); + else + return nullptr; +} + +string Exception::lineInfo() const +{ + char const* const* file = boost::get_error_info<boost::throw_file>(*this); + int const* line = boost::get_error_info<boost::throw_line>(*this); + string ret; + if (file) + ret += *file; + ret += ':'; + if (line) + ret += boost::lexical_cast<string>(*line); + return ret; +} + +string const* Exception::comment() const noexcept +{ + return boost::get_error_info<errinfo_comment>(*this); +} diff --git a/libdevcore/Exceptions.h b/libdevcore/Exceptions.h index 4817e9e3..a3e638bf 100644 --- a/libdevcore/Exceptions.h +++ b/libdevcore/Exceptions.h @@ -14,23 +14,16 @@ You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ -/** @file Exceptions.h - * @author Gav Wood <i@gavwood.com> - * @date 2014 - */ #pragma once -#include <exception> -#include <string> #include <boost/exception/exception.hpp> #include <boost/exception/info.hpp> #include <boost/exception/info_tuple.hpp> #include <boost/exception/diagnostic_information.hpp> -#include <boost/throw_exception.hpp> -#include <boost/tuple/tuple.hpp> -#include "CommonData.h" -#include "FixedHash.h" + +#include <exception> +#include <string> namespace dev { @@ -38,14 +31,15 @@ namespace dev /// Base class for all exceptions. struct Exception: virtual std::exception, virtual boost::exception { - Exception(std::string _message = std::string()): m_message(std::move(_message)) {} - const char* what() const noexcept override { return m_message.empty() ? std::exception::what() : m_message.c_str(); } + const char* what() const noexcept override; /// @returns "FileName:LineNumber" referring to the point where the exception was thrown. std::string lineInfo() const; + /// @returns the errinfo_comment of this exception. + std::string const* comment() const noexcept; + private: - std::string m_message; }; #define DEV_SIMPLE_EXCEPTION(X) struct X: virtual Exception { const char* what() const noexcept override { return #X; } } diff --git a/libevmasm/Assembly.cpp b/libevmasm/Assembly.cpp index 597fdae1..42b923df 100644 --- a/libevmasm/Assembly.cpp +++ b/libevmasm/Assembly.cpp @@ -350,38 +350,65 @@ void Assembly::injectStart(AssemblyItem const& _i) Assembly& Assembly::optimise(bool _enable, bool _isCreation, size_t _runs) { - optimiseInternal(_enable, _isCreation, _runs); + OptimiserSettings settings; + settings.isCreation = _isCreation; + settings.runPeephole = true; + if (_enable) + { + settings.runDeduplicate = true; + settings.runCSE = true; + settings.runConstantOptimiser = true; + } + settings.expectedExecutionsPerDeployment = _runs; + optimiseInternal(settings); return *this; } -map<u256, u256> Assembly::optimiseInternal(bool _enable, bool _isCreation, size_t _runs) + +Assembly& Assembly::optimise(OptimiserSettings _settings) { + optimiseInternal(_settings); + return *this; +} + +map<u256, u256> Assembly::optimiseInternal(OptimiserSettings _settings) +{ + // Run optimisation for sub-assemblies. for (size_t subId = 0; subId < m_subs.size(); ++subId) { - map<u256, u256> subTagReplacements = m_subs[subId]->optimiseInternal(_enable, false, _runs); + OptimiserSettings settings = _settings; + // Disable creation mode for sub-assemblies. + settings.isCreation = false; + map<u256, u256> subTagReplacements = m_subs[subId]->optimiseInternal(settings); + // Apply the replacements (can be empty). BlockDeduplicator::applyTagReplacement(m_items, subTagReplacements, subId); } map<u256, u256> tagReplacements; + // Iterate until no new optimisation possibilities are found. for (unsigned count = 1; count > 0;) { count = 0; - PeepholeOptimiser peepOpt(m_items); - while (peepOpt.optimise()) - count++; - - if (!_enable) - continue; + if (_settings.runPeephole) + { + PeepholeOptimiser peepOpt(m_items); + while (peepOpt.optimise()) + count++; + } // This only modifies PushTags, we have to run again to actually remove code. - BlockDeduplicator dedup(m_items); - if (dedup.deduplicate()) + if (_settings.runDeduplicate) { - tagReplacements.insert(dedup.replacedTags().begin(), dedup.replacedTags().end()); - count++; + BlockDeduplicator dedup(m_items); + if (dedup.deduplicate()) + { + tagReplacements.insert(dedup.replacedTags().begin(), dedup.replacedTags().end()); + count++; + } } + if (_settings.runCSE) { // Control flow graph optimization has been here before but is disabled because it // assumes we only jump to tags that are pushed. This is not the case anymore with @@ -429,10 +456,10 @@ map<u256, u256> Assembly::optimiseInternal(bool _enable, bool _isCreation, size_ } } - if (_enable) + if (_settings.runConstantOptimiser) ConstantOptimisationMethod::optimiseConstants( - _isCreation, - _isCreation ? 1 : _runs, + _settings.isCreation, + _settings.isCreation ? 1 : _settings.expectedExecutionsPerDeployment, *this, m_items ); diff --git a/libevmasm/Assembly.h b/libevmasm/Assembly.h index 0d40abcf..451b4ea0 100644 --- a/libevmasm/Assembly.h +++ b/libevmasm/Assembly.h @@ -97,12 +97,28 @@ public: LinkerObject const& assemble() const; bytes const& data(h256 const& _i) const { return m_data.at(_i); } + struct OptimiserSettings + { + bool isCreation = false; + bool runPeephole = false; + bool runDeduplicate = false; + bool runCSE = false; + bool runConstantOptimiser = false; + /// This specifies an estimate on how often each opcode in this assembly will be executed, + /// i.e. use a small value to optimise for size and a large value to optimise for runtime gas usage. + size_t expectedExecutionsPerDeployment = 200; + }; + + /// Execute optimisation passes as defined by @a _settings and return the optimised assembly. + Assembly& optimise(OptimiserSettings _settings); + /// Modify (if @a _enable is set) and return the current assembly such that creation and /// execution gas usage is optimised. @a _isCreation should be true for the top-level assembly. /// @a _runs specifes an estimate on how often each opcode in this assembly will be executed, /// i.e. use a small value to optimise for size and a large value to optimise for runtime. /// If @a _enable is not set, will perform some simple peephole optimizations. Assembly& optimise(bool _enable, bool _isCreation = true, size_t _runs = 200); + Json::Value stream( std::ostream& _out, std::string const& _prefix = "", @@ -113,7 +129,7 @@ public: protected: /// Does the same operations as @a optimise, but should only be applied to a sub and /// returns the replaced tags. - std::map<u256, u256> optimiseInternal(bool _enable, bool _isCreation, size_t _runs); + std::map<u256, u256> optimiseInternal(OptimiserSettings _settings); unsigned bytesRequired(unsigned subTagSize) const; diff --git a/libevmasm/AssemblyItem.cpp b/libevmasm/AssemblyItem.cpp index e69b5932..76104866 100644 --- a/libevmasm/AssemblyItem.cpp +++ b/libevmasm/AssemblyItem.cpp @@ -14,13 +14,14 @@ You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ -/** @file Assembly.cpp - * @author Gav Wood <i@gavwood.com> - * @date 2014 - */ -#include "AssemblyItem.h" +#include <libevmasm/AssemblyItem.h> + #include <libevmasm/SemanticInformation.h> + +#include <libdevcore/CommonData.h> +#include <libdevcore/FixedHash.h> + #include <fstream> using namespace std; diff --git a/libevmasm/GasMeter.cpp b/libevmasm/GasMeter.cpp index c96c6ca5..6a7c80e0 100644 --- a/libevmasm/GasMeter.cpp +++ b/libevmasm/GasMeter.cpp @@ -14,13 +14,13 @@ You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ -/** @file GasMeter.cpp - * @author Christian <c@ethdev.com> - * @date 2015 - */ -#include "GasMeter.h" +#include <libevmasm/GasMeter.h> + #include <libevmasm/KnownState.h> + +#include <libdevcore/FixedHash.h> + using namespace std; using namespace dev; using namespace dev::eth; diff --git a/libjulia/backends/evm/EVMCodeTransform.cpp b/libjulia/backends/evm/EVMCodeTransform.cpp index efbe5647..704aa3c1 100644 --- a/libjulia/backends/evm/EVMCodeTransform.cpp +++ b/libjulia/backends/evm/EVMCodeTransform.cpp @@ -37,10 +37,19 @@ void CodeTransform::operator()(VariableDeclaration const& _varDecl) { solAssert(m_scope, ""); - int expectedItems = _varDecl.variables.size(); + int const numVariables = _varDecl.variables.size(); int height = m_assembly.stackHeight(); - boost::apply_visitor(*this, *_varDecl.value); - expectDeposit(expectedItems, height); + if (_varDecl.value) + { + boost::apply_visitor(*this, *_varDecl.value); + expectDeposit(numVariables, height); + } + else + { + int variablesLeft = numVariables; + while (variablesLeft--) + m_assembly.appendConstant(u256(0)); + } for (auto const& variable: _varDecl.variables) { auto& var = boost::get<Scope::Variable>(m_scope->identifiers.at(variable.name)); diff --git a/liblll/CodeFragment.cpp b/liblll/CodeFragment.cpp index 56c1e26a..254f436f 100644 --- a/liblll/CodeFragment.cpp +++ b/liblll/CodeFragment.cpp @@ -203,7 +203,7 @@ void CodeFragment::constructOperation(sp::utree const& _t, CompilerState& _s) else if (us == "INCLUDE") { if (_t.size() != 2) - error<IncorrectParameterCount>(); + error<IncorrectParameterCount>(us); string fileName = firstAsString(); if (fileName.empty()) error<InvalidName>("Empty file name provided"); @@ -215,7 +215,7 @@ void CodeFragment::constructOperation(sp::utree const& _t, CompilerState& _s) else if (us == "SET") { if (_t.size() != 3) - error<IncorrectParameterCount>(); + error<IncorrectParameterCount>(us); int c = 0; for (auto const& i: _t) if (c++ == 2) @@ -226,7 +226,7 @@ void CodeFragment::constructOperation(sp::utree const& _t, CompilerState& _s) else if (us == "GET") { if (_t.size() != 2) - error<IncorrectParameterCount>(); + error<IncorrectParameterCount>(us); m_asm.append((u256)varAddress(firstAsString())); m_asm.append(Instruction::MLOAD); } @@ -237,7 +237,7 @@ void CodeFragment::constructOperation(sp::utree const& _t, CompilerState& _s) string n; unsigned ii = 0; if (_t.size() != 3 && _t.size() != 4) - error<IncorrectParameterCount>(); + error<IncorrectParameterCount>(us); vector<string> args; for (auto const& i: _t) { @@ -288,7 +288,7 @@ void CodeFragment::constructOperation(sp::utree const& _t, CompilerState& _s) else if (us == "LIT") { if (_t.size() < 3) - error<IncorrectParameterCount>(); + error<IncorrectParameterCount>(us); unsigned ii = 0; CodeFragment pos; bytes data; @@ -303,7 +303,7 @@ void CodeFragment::constructOperation(sp::utree const& _t, CompilerState& _s) { pos = CodeFragment(i, _s); if (pos.m_asm.deposit() != 1) - error<InvalidDeposit>(); + error<InvalidDeposit>(us); } else if (i.tag() != 0) { @@ -384,10 +384,10 @@ void CodeFragment::constructOperation(sp::utree const& _t, CompilerState& _s) else code.push_back(CodeFragment(i, _s)); } - auto requireSize = [&](unsigned s) { if (code.size() != s) error<IncorrectParameterCount>(); }; - auto requireMinSize = [&](unsigned s) { if (code.size() < s) error<IncorrectParameterCount>(); }; - auto requireMaxSize = [&](unsigned s) { if (code.size() > s) error<IncorrectParameterCount>(); }; - auto requireDeposit = [&](unsigned i, int s) { if (code[i].m_asm.deposit() != s) error<InvalidDeposit>(); }; + auto requireSize = [&](unsigned s) { if (code.size() != s) error<IncorrectParameterCount>(us); }; + auto requireMinSize = [&](unsigned s) { if (code.size() < s) error<IncorrectParameterCount>(us); }; + auto requireMaxSize = [&](unsigned s) { if (code.size() > s) error<IncorrectParameterCount>(us); }; + auto requireDeposit = [&](unsigned i, int s) { if (code[i].m_asm.deposit() != s) error<InvalidDeposit>(us); }; if (_s.macros.count(make_pair(s, code.size()))) { @@ -412,11 +412,7 @@ void CodeFragment::constructOperation(sp::utree const& _t, CompilerState& _s) else if (c_instructions.count(us)) { auto it = c_instructions.find(us); - int ea = instructionInfo(it->second).args; - if (ea >= 0) - requireSize(ea); - else - requireMinSize(-ea); + requireSize(instructionInfo(it->second).args); for (unsigned i = code.size(); i; --i) m_asm.append(code[i - 1].m_asm, 1); @@ -475,7 +471,7 @@ void CodeFragment::constructOperation(sp::utree const& _t, CompilerState& _s) m_asm.append(code[1].m_asm, minDep); m_asm << end.tag(); if (m_asm.deposit() != deposit) - error<InvalidDeposit>(); + error<InvalidDeposit>(us); } else if (us == "WHEN" || us == "UNLESS") { @@ -523,14 +519,30 @@ void CodeFragment::constructOperation(sp::utree const& _t, CompilerState& _s) requireSize(1); requireDeposit(0, 1); - m_asm.append(Instruction::MSIZE); - m_asm.append(u256(0)); + // (alloc N): + // - Evaluates to (msize) before the allocation - the start of the allocated memory + // - Does not allocate memory when N is zero + // - Size of memory allocated is N bytes rounded up to a multiple of 32 + // - Uses MLOAD to expand MSIZE to avoid modifying memory. + + auto end = m_asm.newTag(); + m_asm.append(Instruction::MSIZE); // Result will be original top of memory + m_asm.append(code[0].m_asm, 1); // The alloc argument N + m_asm.append(Instruction::DUP1); + m_asm.append(Instruction::ISZERO);// (alloc 0) does not change MSIZE + m_asm.appendJumpI(end); m_asm.append(u256(1)); - m_asm.append(code[0].m_asm, 1); - m_asm.append(Instruction::MSIZE); + m_asm.append(Instruction::DUP2); // Copy N + m_asm.append(Instruction::SUB); // N-1 + m_asm.append(u256(0x1f)); // Bit mask + m_asm.append(Instruction::NOT); // Invert + m_asm.append(Instruction::AND); // Align N-1 on 32 byte boundary + m_asm.append(Instruction::MSIZE); // MSIZE is cheap m_asm.append(Instruction::ADD); - m_asm.append(Instruction::SUB); - m_asm.append(Instruction::MSTORE8); + m_asm.append(Instruction::MLOAD); // Updates MSIZE + m_asm.append(Instruction::POP); // Discard the result of the MLOAD + m_asm.append(end); + m_asm.append(Instruction::POP); // Discard duplicate N _s.usedAlloc = true; } diff --git a/liblll/Compiler.cpp b/liblll/Compiler.cpp index 05376cd5..4ec11ca9 100644 --- a/liblll/Compiler.cpp +++ b/liblll/Compiler.cpp @@ -34,7 +34,10 @@ bytes dev::eth::compileLLL(string const& _src, bool _opt, vector<string>* _error { CompilerState cs; cs.populateStandard(); - bytes ret = CodeFragment::compile(_src, cs).assembly(cs).optimise(_opt).assemble().bytecode; + auto assembly = CodeFragment::compile(_src, cs).assembly(cs); + if (_opt) + assembly = assembly.optimise(true); + bytes ret = assembly.assemble().bytecode; for (auto i: cs.treesToKill) killBigints(i); return ret; @@ -70,7 +73,10 @@ std::string dev::eth::compileLLLToAsm(std::string const& _src, bool _opt, std::v CompilerState cs; cs.populateStandard(); stringstream ret; - CodeFragment::compile(_src, cs).assembly(cs).optimise(_opt).stream(ret); + auto assembly = CodeFragment::compile(_src, cs).assembly(cs); + if (_opt) + assembly = assembly.optimise(true); + assembly.stream(ret); for (auto i: cs.treesToKill) killBigints(i); return ret.str(); diff --git a/liblll/CompilerState.cpp b/liblll/CompilerState.cpp index 5d38bb8c..9701e16b 100644 --- a/liblll/CompilerState.cpp +++ b/liblll/CompilerState.cpp @@ -46,6 +46,8 @@ void CompilerState::populateStandard() { static const string s = "{" "(def 'panic () (asm INVALID))" + // Alternative macro version of alloc, which is currently implemented in the parser + // "(def 'alloc (n) (raw (msize) (when n (pop (mload (+ (msize) (& (- n 1) (~ 0x1f))))))))" "(def 'allgas (- (gas) 21))" "(def 'send (to value) (call allgas to value 0 0 0 0))" "(def 'send (gaslimit to value) (call gaslimit to value 0 0 0 0))" diff --git a/libsolidity/analysis/NameAndTypeResolver.cpp b/libsolidity/analysis/NameAndTypeResolver.cpp index aac90311..df83f382 100644 --- a/libsolidity/analysis/NameAndTypeResolver.cpp +++ b/libsolidity/analysis/NameAndTypeResolver.cpp @@ -104,29 +104,18 @@ bool NameAndTypeResolver::performImports(SourceUnit& _sourceUnit, map<string, So } else for (Declaration const* declaration: declarations) - { - ASTString const* name = alias.second ? alias.second.get() : &declaration->name(); - if (!target.registerDeclaration(*declaration, name)) - { - m_errorReporter.declarationError( - imp->location(), - "Identifier \"" + *name + "\" already declared." - ); + if (!DeclarationRegistrationHelper::registerDeclaration( + target, *declaration, alias.second.get(), &imp->location(), true, m_errorReporter + )) error = true; - } - } } else if (imp->name().empty()) for (auto const& nameAndDeclaration: scope->second->declarations()) for (auto const& declaration: nameAndDeclaration.second) - if (!target.registerDeclaration(*declaration, &nameAndDeclaration.first)) - { - m_errorReporter.declarationError( - imp->location(), - "Identifier \"" + nameAndDeclaration.first + "\" already declared." - ); - error = true; - } + if (!DeclarationRegistrationHelper::registerDeclaration( + target, *declaration, &nameAndDeclaration.first, &imp->location(), true, m_errorReporter + )) + error = true; } return !error; } @@ -450,6 +439,75 @@ DeclarationRegistrationHelper::DeclarationRegistrationHelper( solAssert(m_currentScope == _currentScope, "Scopes not correctly closed."); } +bool DeclarationRegistrationHelper::registerDeclaration( + DeclarationContainer& _container, + Declaration const& _declaration, + string const* _name, + SourceLocation const* _errorLocation, + bool _warnOnShadow, + ErrorReporter& _errorReporter +) +{ + if (!_errorLocation) + _errorLocation = &_declaration.location(); + + Declaration const* shadowedDeclaration = nullptr; + if (_warnOnShadow && !_declaration.name().empty()) + for (auto const* decl: _container.resolveName(_declaration.name(), true)) + if (decl != &_declaration) + { + shadowedDeclaration = decl; + break; + } + + if (!_container.registerDeclaration(_declaration, _name, !_declaration.isVisibleInContract())) + { + SourceLocation firstDeclarationLocation; + SourceLocation secondDeclarationLocation; + Declaration const* conflictingDeclaration = _container.conflictingDeclaration(_declaration, _name); + solAssert(conflictingDeclaration, ""); + bool const comparable = + _errorLocation->sourceName && + conflictingDeclaration->location().sourceName && + *_errorLocation->sourceName == *conflictingDeclaration->location().sourceName; + if (comparable && _errorLocation->start < conflictingDeclaration->location().start) + { + firstDeclarationLocation = *_errorLocation; + secondDeclarationLocation = conflictingDeclaration->location(); + } + else + { + firstDeclarationLocation = conflictingDeclaration->location(); + secondDeclarationLocation = *_errorLocation; + } + + _errorReporter.declarationError( + secondDeclarationLocation, + SecondarySourceLocation().append("The previous declaration is here:", firstDeclarationLocation), + "Identifier already declared." + ); + return false; + } + else if (shadowedDeclaration) + { + if (dynamic_cast<MagicVariableDeclaration const*>(shadowedDeclaration)) + _errorReporter.warning( + _declaration.location(), + "This declaration shadows a builtin symbol." + ); + else + { + auto shadowedLocation = shadowedDeclaration->location(); + _errorReporter.warning( + _declaration.location(), + "This declaration shadows an existing declaration.", + SecondarySourceLocation().append("The shadowed declaration is here:", shadowedLocation) + ); + } + } + return true; +} + bool DeclarationRegistrationHelper::visit(SourceUnit& _sourceUnit) { if (!m_scopes[&_sourceUnit]) @@ -590,30 +648,21 @@ void DeclarationRegistrationHelper::closeCurrentScope() void DeclarationRegistrationHelper::registerDeclaration(Declaration& _declaration, bool _opensScope) { solAssert(m_currentScope && m_scopes.count(m_currentScope), "No current scope."); - if (!m_scopes[m_currentScope]->registerDeclaration(_declaration, nullptr, !_declaration.isVisibleInContract())) - { - SourceLocation firstDeclarationLocation; - SourceLocation secondDeclarationLocation; - Declaration const* conflictingDeclaration = m_scopes[m_currentScope]->conflictingDeclaration(_declaration); - solAssert(conflictingDeclaration, ""); - if (_declaration.location().start < conflictingDeclaration->location().start) - { - firstDeclarationLocation = _declaration.location(); - secondDeclarationLocation = conflictingDeclaration->location(); - } - else - { - firstDeclarationLocation = conflictingDeclaration->location(); - secondDeclarationLocation = _declaration.location(); - } + bool warnAboutShadowing = true; + // Do not warn about shadowing for structs and enums because their members are + // not accessible without prefixes. + if ( + dynamic_cast<StructDefinition const*>(m_currentScope) || + dynamic_cast<EnumDefinition const*>(m_currentScope) + ) + warnAboutShadowing = false; + // Do not warn about the constructor shadowing the contract. + if (auto fun = dynamic_cast<FunctionDefinition const*>(&_declaration)) + if (fun->isConstructor()) + warnAboutShadowing = false; - m_errorReporter.declarationError( - secondDeclarationLocation, - SecondarySourceLocation().append("The previous declaration is here:", firstDeclarationLocation), - "Identifier already declared." - ); - } + registerDeclaration(*m_scopes[m_currentScope], _declaration, nullptr, nullptr, warnAboutShadowing, m_errorReporter); _declaration.setScope(m_currentScope); if (_opensScope) diff --git a/libsolidity/analysis/NameAndTypeResolver.h b/libsolidity/analysis/NameAndTypeResolver.h index 84628778..a498c7ba 100644 --- a/libsolidity/analysis/NameAndTypeResolver.h +++ b/libsolidity/analysis/NameAndTypeResolver.h @@ -136,6 +136,15 @@ public: ASTNode const* _currentScope = nullptr ); + static bool registerDeclaration( + DeclarationContainer& _container, + Declaration const& _declaration, + std::string const* _name, + SourceLocation const* _errorLocation, + bool _warnOnShadow, + ErrorReporter& _errorReporter + ); + private: bool visit(SourceUnit& _sourceUnit) override; void endVisit(SourceUnit& _sourceUnit) override; diff --git a/libsolidity/analysis/ReferencesResolver.cpp b/libsolidity/analysis/ReferencesResolver.cpp index cc95c294..8f07d43a 100644 --- a/libsolidity/analysis/ReferencesResolver.cpp +++ b/libsolidity/analysis/ReferencesResolver.cpp @@ -295,7 +295,7 @@ void ReferencesResolver::endVisit(VariableDeclaration const& _variable) else { typeLoc = DataLocation::Storage; - if (!_variable.isStateVariable()) + if (_variable.isLocalVariable()) m_errorReporter.warning( _variable.location(), "Variable is declared as a storage pointer. " diff --git a/libsolidity/analysis/StaticAnalyzer.cpp b/libsolidity/analysis/StaticAnalyzer.cpp index b1b31163..46477e1e 100644 --- a/libsolidity/analysis/StaticAnalyzer.cpp +++ b/libsolidity/analysis/StaticAnalyzer.cpp @@ -38,12 +38,14 @@ bool StaticAnalyzer::analyze(SourceUnit const& _sourceUnit) bool StaticAnalyzer::visit(ContractDefinition const& _contract) { m_library = _contract.isLibrary(); + m_currentContract = &_contract; return true; } void StaticAnalyzer::endVisit(ContractDefinition const&) { m_library = false; + m_currentContract = nullptr; } bool StaticAnalyzer::visit(FunctionDefinition const& _function) @@ -54,6 +56,7 @@ bool StaticAnalyzer::visit(FunctionDefinition const& _function) solAssert(!m_currentFunction, ""); solAssert(m_localVarUseCount.empty(), ""); m_nonPayablePublic = _function.isPublic() && !_function.isPayable(); + m_constructor = _function.isConstructor(); return true; } @@ -61,6 +64,7 @@ void StaticAnalyzer::endVisit(FunctionDefinition const&) { m_currentFunction = nullptr; m_nonPayablePublic = false; + m_constructor = false; for (auto const& var: m_localVarUseCount) if (var.second == 0) m_errorReporter.warning(var.first->location(), "Unused local variable"); @@ -131,6 +135,11 @@ bool StaticAnalyzer::visit(MemberAccess const& _memberAccess) "\"callcode\" has been deprecated in favour of \"delegatecall\"." ); + if (m_constructor && m_currentContract) + if (ContractType const* type = dynamic_cast<ContractType const*>(_memberAccess.expression().annotation().type.get())) + if (type->contractDefinition() == *m_currentContract) + m_errorReporter.warning(_memberAccess.location(), "\"this\" used in constructor."); + return true; } diff --git a/libsolidity/analysis/StaticAnalyzer.h b/libsolidity/analysis/StaticAnalyzer.h index cd6913b5..21a487df 100644 --- a/libsolidity/analysis/StaticAnalyzer.h +++ b/libsolidity/analysis/StaticAnalyzer.h @@ -77,6 +77,12 @@ private: std::map<VariableDeclaration const*, int> m_localVarUseCount; FunctionDefinition const* m_currentFunction = nullptr; + + /// Flag that indicates a constructor. + bool m_constructor = false; + + /// Current contract. + ContractDefinition const* m_currentContract = nullptr; }; } diff --git a/libsolidity/analysis/TypeChecker.cpp b/libsolidity/analysis/TypeChecker.cpp index 7306a36d..5419db2d 100644 --- a/libsolidity/analysis/TypeChecker.cpp +++ b/libsolidity/analysis/TypeChecker.cpp @@ -93,7 +93,7 @@ bool TypeChecker::visit(ContractDefinition const& _contract) FunctionDefinition const* fallbackFunction = nullptr; for (FunctionDefinition const* function: _contract.definedFunctions()) { - if (function->name().empty()) + if (function->isFallback()) { if (fallbackFunction) { @@ -482,7 +482,7 @@ bool TypeChecker::visit(FunctionDefinition const& _function) { if (isLibraryFunction) m_errorReporter.typeError(_function.location(), "Library functions cannot be payable."); - if (!_function.isConstructor() && !_function.name().empty() && !_function.isPartOfExternalInterface()) + if (!_function.isConstructor() && !_function.isFallback() && !_function.isPartOfExternalInterface()) m_errorReporter.typeError(_function.location(), "Internal functions cannot be payable."); if (_function.isDeclaredConst()) m_errorReporter.typeError(_function.location(), "Functions cannot be constant and payable at the same time."); @@ -510,8 +510,6 @@ bool TypeChecker::visit(FunctionDefinition const& _function) { if (dynamic_cast<ContractDefinition const*>(decl)) m_errorReporter.declarationError(modifier->location(), "Base constructor already provided."); - else - m_errorReporter.declarationError(modifier->location(), "Modifier already used for this function."); } else modifiers.insert(decl); @@ -583,6 +581,16 @@ bool TypeChecker::visit(VariableDeclaration const& _variable) !FunctionType(_variable).interfaceFunctionType() ) m_errorReporter.typeError(_variable.location(), "Internal type is not allowed for public state variables."); + + if (varType->category() == Type::Category::Array) + if (auto arrayType = dynamic_cast<ArrayType const*>(varType.get())) + if ( + ((arrayType->location() == DataLocation::Memory) || + (arrayType->location() == DataLocation::CallData)) && + !arrayType->validForCalldata() + ) + m_errorReporter.typeError(_variable.location(), "Array is too large to be encoded as calldata."); + return false; } @@ -723,7 +731,10 @@ bool TypeChecker::visit(InlineAssembly const& _inlineAssembly) } else if (var->type()->sizeOnStack() != 1) { - m_errorReporter.typeError(_identifier.location, "Only types that use one stack slot are supported."); + if (var->type()->dataStoredIn(DataLocation::CallData)) + m_errorReporter.typeError(_identifier.location, "Call data elements cannot be accessed directly. Copy to a local variable first or use \"calldataload\" or \"calldatacopy\" with manually determined offsets and sizes."); + else + m_errorReporter.typeError(_identifier.location, "Only types that use one stack slot are supported."); return size_t(-1); } } @@ -1111,7 +1122,9 @@ bool TypeChecker::visit(Assignment const& _assignment) _assignment.annotation().type = make_shared<TupleType>(); expectType(_assignment.rightHandSide(), *tupleType); - checkDoubleStorageAssignment(_assignment); + // expectType does not cause fatal errors, so we have to check again here. + if (dynamic_cast<TupleType const*>(type(_assignment.rightHandSide()).get())) + checkDoubleStorageAssignment(_assignment); } else if (t->category() == Type::Category::Mapping) { @@ -1351,7 +1364,14 @@ bool TypeChecker::visit(FunctionCall const& _functionCall) // (data location cannot yet be specified for type conversions) resultType = ReferenceType::copyForLocationIfReference(argRefType->location(), resultType); if (!argType->isExplicitlyConvertibleTo(*resultType)) - m_errorReporter.typeError(_functionCall.location(), "Explicit type conversion not allowed."); + m_errorReporter.typeError( + _functionCall.location(), + "Explicit type conversion not allowed from \"" + + argType->toString() + + "\" to \"" + + resultType->toString() + + "\"." + ); } _functionCall.annotation().type = resultType; _functionCall.annotation().isPure = isPure; @@ -1628,6 +1648,25 @@ bool TypeChecker::visit(MemberAccess const& _memberAccess) annotation.isLValue = annotation.referencedDeclaration->isLValue(); } + if (exprType->category() == Type::Category::Contract) + { + if (auto callType = dynamic_cast<FunctionType const*>(type(_memberAccess).get())) + { + auto kind = callType->kind(); + auto contractType = dynamic_cast<ContractType const*>(exprType.get()); + solAssert(!!contractType, "Should be contract type."); + + if ( + (kind == FunctionType::Kind::Send || kind == FunctionType::Kind::Transfer) && + !contractType->isPayable() + ) + m_errorReporter.typeError( + _memberAccess.location(), + "Value transfer to a contract without a payable fallback function." + ); + } + } + // TODO some members might be pure, but for example `address(0x123).balance` is not pure // although every subexpression is, so leaving this limited for now. if (auto tt = dynamic_cast<TypeType const*>(exprType.get())) diff --git a/libsolidity/ast/AST.cpp b/libsolidity/ast/AST.cpp index 403f4b79..1d68231e 100644 --- a/libsolidity/ast/AST.cpp +++ b/libsolidity/ast/AST.cpp @@ -84,13 +84,35 @@ SourceUnitAnnotation& SourceUnit::annotation() const return dynamic_cast<SourceUnitAnnotation&>(*m_annotation); } -string Declaration::sourceUnitName() const +set<SourceUnit const*> SourceUnit::referencedSourceUnits(bool _recurse, set<SourceUnit const*> _skipList) const +{ + set<SourceUnit const*> sourceUnits; + for (ImportDirective const* importDirective: filteredNodes<ImportDirective>(nodes())) + { + auto const& sourceUnit = importDirective->annotation().sourceUnit; + if (!_skipList.count(sourceUnit)) + { + _skipList.insert(sourceUnit); + sourceUnits.insert(sourceUnit); + if (_recurse) + sourceUnits += sourceUnit->referencedSourceUnits(true, _skipList); + } + } + return sourceUnits; +} + +SourceUnit const& Declaration::sourceUnit() const { solAssert(!!m_scope, ""); ASTNode const* scope = m_scope; while (dynamic_cast<Declaration const*>(scope) && dynamic_cast<Declaration const*>(scope)->m_scope) scope = dynamic_cast<Declaration const*>(scope)->m_scope; - return dynamic_cast<SourceUnit const&>(*scope).annotation().path; + return dynamic_cast<SourceUnit const&>(*scope); +} + +string Declaration::sourceUnitName() const +{ + return sourceUnit().annotation().path; } ImportAnnotation& ImportDirective::annotation() const @@ -140,7 +162,7 @@ FunctionDefinition const* ContractDefinition::fallbackFunction() const { for (ContractDefinition const* contract: annotation().linearizedBaseContracts) for (FunctionDefinition const* f: contract->definedFunctions()) - if (f->name().empty()) + if (f->isFallback()) return f; return nullptr; } @@ -416,6 +438,23 @@ bool VariableDeclaration::isCallableParameter() const return false; } +bool VariableDeclaration::isLocalOrReturn() const +{ + return isReturnParameter() || (isLocalVariable() && !isCallableParameter()); +} + +bool VariableDeclaration::isReturnParameter() const +{ + auto const* callable = dynamic_cast<CallableDeclaration const*>(scope()); + if (!callable) + return false; + if (callable->returnParameterList()) + for (auto const& variable: callable->returnParameterList()->parameters()) + if (variable.get() == this) + return true; + return false; +} + bool VariableDeclaration::isExternalCallableParameter() const { auto const* callable = dynamic_cast<CallableDeclaration const*>(scope()); diff --git a/libsolidity/ast/AST.h b/libsolidity/ast/AST.h index e8831dc0..3e97286b 100644 --- a/libsolidity/ast/AST.h +++ b/libsolidity/ast/AST.h @@ -23,19 +23,24 @@ #pragma once -#include <string> -#include <vector> -#include <memory> -#include <boost/noncopyable.hpp> -#include <libevmasm/SourceLocation.h> -#include <libevmasm/Instruction.h> #include <libsolidity/ast/ASTForward.h> #include <libsolidity/parsing/Token.h> #include <libsolidity/ast/Types.h> #include <libsolidity/interface/Exceptions.h> #include <libsolidity/ast/ASTAnnotations.h> + +#include <libevmasm/SourceLocation.h> +#include <libevmasm/Instruction.h> + +#include <libdevcore/FixedHash.h> #include <json/json.h> +#include <boost/noncopyable.hpp> + +#include <string> +#include <vector> +#include <memory> + namespace dev { namespace solidity @@ -131,6 +136,9 @@ public: std::vector<ASTPointer<ASTNode>> nodes() const { return m_nodes; } + /// @returns a set of referenced SourceUnits. Recursively if @a _recurse is true. + std::set<SourceUnit const*> referencedSourceUnits(bool _recurse = false, std::set<SourceUnit const*> _skipList = std::set<SourceUnit const*>()) const; + private: std::vector<ASTPointer<ASTNode>> m_nodes; }; @@ -163,6 +171,9 @@ public: ASTNode const* scope() const { return m_scope; } void setScope(ASTNode const* _scope) { m_scope = _scope; } + /// @returns the source unit this declaration is present in. + SourceUnit const& sourceUnit() const; + /// @returns the source name this declaration is present in. /// Can be combined with annotation().canonicalName to form a globally unique name. std::string sourceUnitName() const; @@ -578,6 +589,7 @@ public: virtual void accept(ASTConstVisitor& _visitor) const override; bool isConstructor() const { return m_isConstructor; } + bool isFallback() const { return name().empty(); } bool isDeclaredConst() const { return m_isDeclaredConst; } bool isPayable() const { return m_isPayable; } std::vector<ASTPointer<ModifierInvocation>> const& modifiers() const { return m_functionModifiers; } @@ -585,9 +597,9 @@ public: Block const& body() const { solAssert(m_body, ""); return *m_body; } virtual bool isVisibleInContract() const override { - return Declaration::isVisibleInContract() && !isConstructor() && !name().empty(); + return Declaration::isVisibleInContract() && !isConstructor() && !isFallback(); } - virtual bool isPartOfExternalInterface() const override { return isPublic() && !m_isConstructor && !name().empty(); } + virtual bool isPartOfExternalInterface() const override { return isPublic() && !isConstructor() && !isFallback(); } /// @returns the external signature of the function /// That consists of the name of the function followed by the types of the @@ -650,6 +662,10 @@ public: bool isLocalVariable() const { return !!dynamic_cast<CallableDeclaration const*>(scope()); } /// @returns true if this variable is a parameter or return parameter of a function. bool isCallableParameter() const; + /// @returns true if this variable is a return parameter of a function. + bool isReturnParameter() const; + /// @returns true if this variable is a local variable or return parameter. + bool isLocalOrReturn() const; /// @returns true if this variable is a parameter (not return parameter) of an external function. bool isExternalCallableParameter() const; /// @returns true if the type of the variable does not need to be specified, i.e. it is declared @@ -695,7 +711,7 @@ public: ASTPointer<ParameterList> const& _parameters, ASTPointer<Block> const& _body ): - CallableDeclaration(_location, _name, Visibility::Default, _parameters), + CallableDeclaration(_location, _name, Visibility::Internal, _parameters), Documented(_documentation), m_body(_body) { @@ -782,11 +798,11 @@ public: Declaration(SourceLocation(), std::make_shared<ASTString>(_name)), m_type(_type) {} virtual void accept(ASTVisitor&) override { - BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("MagicVariableDeclaration used inside real AST.")); + solAssert(false, "MagicVariableDeclaration used inside real AST."); } virtual void accept(ASTConstVisitor&) const override { - BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("MagicVariableDeclaration used inside real AST.")); + solAssert(false, "MagicVariableDeclaration used inside real AST."); } virtual TypePointer type() const override { return m_type; } diff --git a/libsolidity/ast/ASTJsonConverter.cpp b/libsolidity/ast/ASTJsonConverter.cpp index a90debb2..eda70b63 100644 --- a/libsolidity/ast/ASTJsonConverter.cpp +++ b/libsolidity/ast/ASTJsonConverter.cpp @@ -743,7 +743,7 @@ string ASTJsonConverter::visibility(Declaration::Visibility const& _visibility) case Declaration::Visibility::External: return "external"; default: - BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Unknown declaration visibility.")); + solAssert(false, "Unknown declaration visibility."); } } @@ -758,7 +758,7 @@ string ASTJsonConverter::location(VariableDeclaration::Location _location) case VariableDeclaration::Location::Memory: return "memory"; default: - BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Unknown declaration location.")); + solAssert(false, "Unknown declaration location."); } } @@ -773,7 +773,7 @@ string ASTJsonConverter::contractKind(ContractDefinition::ContractKind _kind) case ContractDefinition::ContractKind::Library: return "library"; default: - BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Unknown kind of contract.")); + solAssert(false, "Unknown kind of contract."); } } @@ -788,7 +788,7 @@ string ASTJsonConverter::functionCallKind(FunctionCallKind _kind) case FunctionCallKind::StructConstructorCall: return "structConstructorCall"; default: - BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Unknown kind of function call .")); + solAssert(false, "Unknown kind of function call."); } } @@ -804,7 +804,7 @@ string ASTJsonConverter::literalTokenKind(Token::Value _token) case dev::solidity::Token::FalseLiteral: return "bool"; default: - BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Unknown kind of literal token.")); + solAssert(false, "Unknown kind of literal token."); } } diff --git a/libsolidity/ast/Types.cpp b/libsolidity/ast/Types.cpp index 7dc6c4a6..3f8da501 100644 --- a/libsolidity/ast/Types.cpp +++ b/libsolidity/ast/Types.cpp @@ -196,9 +196,9 @@ TypePointer Type::fromElementaryTypeName(ElementaryTypeNameToken const& _type) case Token::UInt: return make_shared<IntegerType>(256, IntegerType::Modifier::Unsigned); case Token::Fixed: - return make_shared<FixedPointType>(128, 128, FixedPointType::Modifier::Signed); + return make_shared<FixedPointType>(128, 19, FixedPointType::Modifier::Signed); case Token::UFixed: - return make_shared<FixedPointType>(128, 128, FixedPointType::Modifier::Unsigned); + return make_shared<FixedPointType>(128, 19, FixedPointType::Modifier::Unsigned); case Token::Byte: return make_shared<FixedBytesType>(1); case Token::Address: @@ -211,9 +211,10 @@ TypePointer Type::fromElementaryTypeName(ElementaryTypeNameToken const& _type) return make_shared<ArrayType>(DataLocation::Storage, true); //no types found default: - BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment( + solAssert( + false, "Unable to convert elementary typename " + _type.toString() + " to type." - )); + ); } } @@ -352,12 +353,11 @@ bool IntegerType::isImplicitlyConvertibleTo(Type const& _convertTo) const else if (_convertTo.category() == Category::FixedPoint) { FixedPointType const& convertTo = dynamic_cast<FixedPointType const&>(_convertTo); - if (convertTo.integerBits() < m_bits || isAddress()) + + if (isAddress()) return false; - else if (isSigned()) - return convertTo.isSigned(); else - return !convertTo.isSigned() || convertTo.integerBits() > m_bits; + return maxValue() <= convertTo.maxIntegerValue() && minValue() >= convertTo.minIntegerValue(); } else return false; @@ -413,6 +413,22 @@ u256 IntegerType::literalValue(Literal const* _literal) const return u256(_literal->value()); } +bigint IntegerType::minValue() const +{ + if (isSigned()) + return -(bigint(1) << (m_bits - 1)); + else + return bigint(0); +} + +bigint IntegerType::maxValue() const +{ + if (isSigned()) + return (bigint(1) << (m_bits - 1)) - 1; + else + return (bigint(1) << m_bits) - 1; +} + TypePointer IntegerType::binaryOperatorResult(Token::Value _operator, TypePointer const& _other) const { if ( @@ -471,22 +487,20 @@ MemberList::MemberMap IntegerType::nativeMembers(ContractDefinition const*) cons return MemberList::MemberMap(); } -FixedPointType::FixedPointType(int _integerBits, int _fractionalBits, FixedPointType::Modifier _modifier): - m_integerBits(_integerBits), m_fractionalBits(_fractionalBits), m_modifier(_modifier) +FixedPointType::FixedPointType(int _totalBits, int _fractionalDigits, FixedPointType::Modifier _modifier): + m_totalBits(_totalBits), m_fractionalDigits(_fractionalDigits), m_modifier(_modifier) { solAssert( - m_integerBits + m_fractionalBits > 0 && - m_integerBits + m_fractionalBits <= 256 && - m_integerBits % 8 == 0 && - m_fractionalBits % 8 == 0, + 8 <= m_totalBits && m_totalBits <= 256 && m_totalBits % 8 == 0 && + 0 <= m_fractionalDigits && m_fractionalDigits <= 80, "Invalid bit number(s) for fixed type: " + - dev::toString(_integerBits) + "x" + dev::toString(_fractionalBits) - ); + dev::toString(_totalBits) + "x" + dev::toString(_fractionalDigits) + ); } string FixedPointType::identifier() const { - return "t_" + string(isSigned() ? "" : "u") + "fixed" + std::to_string(integerBits()) + "x" + std::to_string(fractionalBits()); + return "t_" + string(isSigned() ? "" : "u") + "fixed" + std::to_string(m_totalBits) + "x" + std::to_string(m_fractionalDigits); } bool FixedPointType::isImplicitlyConvertibleTo(Type const& _convertTo) const @@ -494,12 +508,10 @@ bool FixedPointType::isImplicitlyConvertibleTo(Type const& _convertTo) const if (_convertTo.category() == category()) { FixedPointType const& convertTo = dynamic_cast<FixedPointType const&>(_convertTo); - if (convertTo.m_integerBits < m_integerBits || convertTo.m_fractionalBits < m_fractionalBits) + if (convertTo.numBits() < m_totalBits || convertTo.fractionalDigits() < m_fractionalDigits) return false; - else if (isSigned()) - return convertTo.isSigned(); else - return !convertTo.isSigned() || (convertTo.m_integerBits > m_integerBits); + return convertTo.maxIntegerValue() >= maxIntegerValue() && convertTo.minIntegerValue() <= minIntegerValue(); } return false; } @@ -533,13 +545,30 @@ bool FixedPointType::operator==(Type const& _other) const if (_other.category() != category()) return false; FixedPointType const& other = dynamic_cast<FixedPointType const&>(_other); - return other.m_integerBits == m_integerBits && other.m_fractionalBits == m_fractionalBits && other.m_modifier == m_modifier; + return other.m_totalBits == m_totalBits && other.m_fractionalDigits == m_fractionalDigits && other.m_modifier == m_modifier; } string FixedPointType::toString(bool) const { string prefix = isSigned() ? "fixed" : "ufixed"; - return prefix + dev::toString(m_integerBits) + "x" + dev::toString(m_fractionalBits); + return prefix + dev::toString(m_totalBits) + "x" + dev::toString(m_fractionalDigits); +} + +bigint FixedPointType::maxIntegerValue() const +{ + bigint maxValue = (bigint(1) << (m_totalBits - (isSigned() ? 1 : 0))) - 1; + return maxValue / pow(bigint(10), m_fractionalDigits); +} + +bigint FixedPointType::minIntegerValue() const +{ + if (isSigned()) + { + bigint minValue = -(bigint(1) << (m_totalBits - (isSigned() ? 1 : 0))); + return minValue / pow(bigint(10), m_fractionalDigits); + } + else + return bigint(0); } TypePointer FixedPointType::binaryOperatorResult(Token::Value _operator, TypePointer const& _other) const @@ -727,13 +756,9 @@ bool RationalNumberType::isImplicitlyConvertibleTo(Type const& _convertTo) const else if (_convertTo.category() == Category::FixedPoint) { if (auto fixed = fixedPointType()) - { - // We disallow implicit conversion if we would have to truncate (fixedPointType() - // can return a type that requires truncation). - rational value = m_value * (bigint(1) << fixed->fractionalBits()); - return value.denominator() == 1 && fixed->isImplicitlyConvertibleTo(_convertTo); - } - return false; + return fixed->isImplicitlyConvertibleTo(_convertTo); + else + return false; } else if (_convertTo.category() == Category::FixedBytes) { @@ -937,10 +962,9 @@ u256 RationalNumberType::literalValue(Literal const*) const else { auto fixed = fixedPointType(); - solAssert(!!fixed, ""); - rational shifted = m_value * (bigint(1) << fixed->fractionalBits()); - // truncate - shiftedValue = shifted.numerator() / shifted.denominator(); + solAssert(fixed, ""); + int fractionalDigits = fixed->fractionalDigits(); + shiftedValue = (m_value.numerator() / m_value.denominator()) * pow(bigint(10), fractionalDigits); } // we ignore the literal and hope that the type was correctly determined @@ -981,22 +1005,21 @@ shared_ptr<IntegerType const> RationalNumberType::integerType() const shared_ptr<FixedPointType const> RationalNumberType::fixedPointType() const { bool negative = (m_value < 0); - unsigned fractionalBits = 0; + unsigned fractionalDigits = 0; rational value = abs(m_value); // We care about the sign later. rational maxValue = negative ? rational(bigint(1) << 255, 1): rational((bigint(1) << 256) - 1, 1); - while (value * 0x100 <= maxValue && value.denominator() != 1 && fractionalBits < 256) + while (value * 10 <= maxValue && value.denominator() != 1 && fractionalDigits < 80) { - value *= 0x100; - fractionalBits += 8; + value *= 10; + fractionalDigits++; } if (value > maxValue) return shared_ptr<FixedPointType const>(); - // u256(v) is the actual value that will be put on the stack - // From here on, very similar to integerType() + // This means we round towards zero for positive and negative values. bigint v = value.numerator() / value.denominator(); if (negative) // modify value to satisfy bit requirements for negative numbers: @@ -1006,26 +1029,11 @@ shared_ptr<FixedPointType const> RationalNumberType::fixedPointType() const if (v > u256(-1)) return shared_ptr<FixedPointType const>(); - unsigned totalBits = bytesRequired(v) * 8; + unsigned totalBits = max(bytesRequired(v), 1u) * 8; solAssert(totalBits <= 256, ""); - unsigned integerBits = totalBits >= fractionalBits ? totalBits - fractionalBits : 0; - // Special case: Numbers between -1 and 0 have their sign bit in the fractional part. - if (negative && abs(m_value) < 1 && totalBits > fractionalBits) - { - fractionalBits += 8; - integerBits = 0; - } - - if (integerBits > 256 || fractionalBits > 256 || fractionalBits + integerBits > 256) - return shared_ptr<FixedPointType const>(); - if (integerBits == 0 && fractionalBits == 0) - { - integerBits = 0; - fractionalBits = 8; - } return make_shared<FixedPointType>( - integerBits, fractionalBits, + totalBits, fractionalDigits, negative ? FixedPointType::Modifier::Signed : FixedPointType::Modifier::Unsigned ); } @@ -1169,7 +1177,7 @@ u256 BoolType::literalValue(Literal const* _literal) const else if (_literal->token() == Token::FalseLiteral) return u256(0); else - BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Bool type constructed from non-boolean literal.")); + solAssert(false, "Bool type constructed from non-boolean literal."); } TypePointer BoolType::unaryOperatorResult(Token::Value _operator) const @@ -1214,6 +1222,12 @@ bool ContractType::isExplicitlyConvertibleTo(Type const& _convertTo) const _convertTo.category() == Category::Contract; } +bool ContractType::isPayable() const +{ + auto fallbackFunction = m_contract.fallbackFunction(); + return fallbackFunction && fallbackFunction->isPayable(); +} + TypePointer ContractType::unaryOperatorResult(Token::Value _operator) const { return _operator == Token::Delete ? make_shared<TupleType>() : TypePointer(); @@ -1373,12 +1387,23 @@ bool ArrayType::operator==(Type const& _other) const return isDynamicallySized() || length() == other.length(); } -unsigned ArrayType::calldataEncodedSize(bool _padded) const +bool ArrayType::validForCalldata() const +{ + return unlimitedCalldataEncodedSize(true) <= numeric_limits<unsigned>::max(); +} + +bigint ArrayType::unlimitedCalldataEncodedSize(bool _padded) const { if (isDynamicallySized()) return 32; bigint size = bigint(length()) * (isByteArray() ? 1 : baseType()->calldataEncodedSize(_padded)); size = ((size + 31) / 32) * 32; + return size; +} + +unsigned ArrayType::calldataEncodedSize(bool _padded) const +{ + bigint size = unlimitedCalldataEncodedSize(_padded); solAssert(size <= numeric_limits<unsigned>::max(), "Array size does not fit unsigned."); return unsigned(size); } @@ -1914,10 +1939,7 @@ string TupleType::toString(bool _short) const u256 TupleType::storageSize() const { - BOOST_THROW_EXCEPTION( - InternalCompilerError() << - errinfo_comment("Storage size of non-storable tuple type requested.") - ); + solAssert(false, "Storage size of non-storable tuple type requested."); } unsigned TupleType::sizeOnStack() const @@ -2299,9 +2321,7 @@ u256 FunctionType::storageSize() const if (m_kind == Kind::External || m_kind == Kind::Internal) return 1; else - BOOST_THROW_EXCEPTION( - InternalCompilerError() - << errinfo_comment("Storage size of non-storable function type requested.")); + solAssert(false, "Storage size of non-storable function type requested."); } unsigned FunctionType::storageBytes() const @@ -2311,9 +2331,7 @@ unsigned FunctionType::storageBytes() const else if (m_kind == Kind::Internal) return 8; // it should really not be possible to create larger programs else - BOOST_THROW_EXCEPTION( - InternalCompilerError() - << errinfo_comment("Storage size of non-storable function type requested.")); + solAssert(false, "Storage size of non-storable function type requested."); } unsigned FunctionType::sizeOnStack() const @@ -2506,6 +2524,7 @@ bool FunctionType::isBareCall() const string FunctionType::externalSignature() const { solAssert(m_declaration != nullptr, "External signature of function needs declaration"); + solAssert(!m_declaration->name().empty(), "Fallback function has no signature."); bool _inLibrary = dynamic_cast<ContractDefinition const&>(*m_declaration->scope()).isLibrary(); @@ -2671,9 +2690,7 @@ bool TypeType::operator==(Type const& _other) const u256 TypeType::storageSize() const { - BOOST_THROW_EXCEPTION( - InternalCompilerError() - << errinfo_comment("Storage size of non-storable type type requested.")); + solAssert(false, "Storage size of non-storable type type requested."); } unsigned TypeType::sizeOnStack() const @@ -2740,9 +2757,7 @@ ModifierType::ModifierType(const ModifierDefinition& _modifier) u256 ModifierType::storageSize() const { - BOOST_THROW_EXCEPTION( - InternalCompilerError() - << errinfo_comment("Storage size of non-storable type type requested.")); + solAssert(false, "Storage size of non-storable type type requested."); } string ModifierType::identifier() const @@ -2851,7 +2866,7 @@ MemberList::MemberMap MagicType::nativeMembers(ContractDefinition const*) const {"gasprice", make_shared<IntegerType>(256)} }); default: - BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Unknown kind of magic.")); + solAssert(false, "Unknown kind of magic."); } } @@ -2866,6 +2881,6 @@ string MagicType::toString(bool) const case Kind::Transaction: return "tx"; default: - BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Unknown kind of magic.")); + solAssert(false, "Unknown kind of magic."); } } diff --git a/libsolidity/ast/Types.h b/libsolidity/ast/Types.h index f7a73ab5..1db46355 100644 --- a/libsolidity/ast/Types.h +++ b/libsolidity/ast/Types.h @@ -28,7 +28,6 @@ #include <libdevcore/Common.h> #include <libdevcore/CommonIO.h> -#include <libdevcore/UndefMacros.h> #include <boost/noncopyable.hpp> #include <boost/rational.hpp> @@ -246,10 +245,7 @@ public: virtual std::string canonicalName(bool /*_addDataLocation*/) const { return toString(true); } virtual u256 literalValue(Literal const*) const { - BOOST_THROW_EXCEPTION( - InternalCompilerError() << - errinfo_comment("Literal value requested for type without literals.") - ); + solAssert(false, "Literal value requested for type without literals."); } /// @returns a (simpler) type that is encoded in the same way for external function calls. @@ -323,6 +319,9 @@ public: bool isAddress() const { return m_modifier == Modifier::Address; } bool isSigned() const { return m_modifier == Modifier::Signed; } + bigint minValue() const; + bigint maxValue() const; + private: int m_bits; Modifier m_modifier; @@ -340,7 +339,7 @@ public: }; virtual Category category() const override { return Category::FixedPoint; } - explicit FixedPointType(int _integerBits, int _fractionalBits, Modifier _modifier = Modifier::Unsigned); + explicit FixedPointType(int _totalBits, int _fractionalDigits, Modifier _modifier = Modifier::Unsigned); virtual std::string identifier() const override; virtual bool isImplicitlyConvertibleTo(Type const& _convertTo) const override; @@ -350,8 +349,8 @@ public: virtual bool operator==(Type const& _other) const override; - virtual unsigned calldataEncodedSize(bool _padded = true) const override { return _padded ? 32 : (m_integerBits + m_fractionalBits) / 8; } - virtual unsigned storageBytes() const override { return (m_integerBits + m_fractionalBits) / 8; } + virtual unsigned calldataEncodedSize(bool _padded = true) const override { return _padded ? 32 : m_totalBits / 8; } + virtual unsigned storageBytes() const override { return m_totalBits / 8; } virtual bool isValueType() const override { return true; } virtual std::string toString(bool _short) const override; @@ -359,14 +358,21 @@ public: virtual TypePointer encodingType() const override { return shared_from_this(); } virtual TypePointer interfaceType(bool) const override { return shared_from_this(); } - int numBits() const { return m_integerBits + m_fractionalBits; } - int integerBits() const { return m_integerBits; } - int fractionalBits() const { return m_fractionalBits; } + /// Number of bits used for this type in total. + int numBits() const { return m_totalBits; } + /// Number of decimal digits after the radix point. + int fractionalDigits() const { return m_fractionalDigits; } bool isSigned() const { return m_modifier == Modifier::Signed; } + /// @returns the largest integer value this type con hold. Note that this is not the + /// largest value in general. + bigint maxIntegerValue() const; + /// @returns the smallest integer value this type can hold. Note hat this is not the + /// smallest value in general. + bigint minIntegerValue() const; private: - int m_integerBits; - int m_fractionalBits; + int m_totalBits; + int m_fractionalDigits; Modifier m_modifier; }; @@ -614,6 +620,9 @@ public: virtual TypePointer interfaceType(bool _inLibrary) const override; virtual bool canBeUsedExternally(bool _inLibrary) const override; + /// @returns true if this is valid to be stored in calldata + bool validForCalldata() const; + /// @returns true if this is a byte array or a string bool isByteArray() const { return m_arrayKind != ArrayKind::Ordinary; } /// @returns true if this is a string @@ -628,6 +637,8 @@ private: /// String is interpreted as a subtype of Bytes. enum class ArrayKind { Ordinary, Bytes, String }; + bigint unlimitedCalldataEncodedSize(bool _padded) const; + ///< Byte arrays ("bytes") and strings have different semantics from ordinary arrays. ArrayKind m_arrayKind = ArrayKind::Ordinary; TypePointer m_baseType; @@ -673,6 +684,10 @@ public: } bool isSuper() const { return m_super; } + + // @returns true if and only if the contract has a payable fallback function + bool isPayable() const; + ContractDefinition const& contractDefinition() const { return m_contract; } /// Returns the function type of the constructor modified to return an object of the contract's type. diff --git a/libsolidity/codegen/CompilerContext.cpp b/libsolidity/codegen/CompilerContext.cpp index 6875bda1..bc4de3ee 100644 --- a/libsolidity/codegen/CompilerContext.cpp +++ b/libsolidity/codegen/CompilerContext.cpp @@ -124,14 +124,15 @@ void CompilerContext::addVariable(VariableDeclaration const& _declaration, unsigned _offsetToCurrent) { solAssert(m_asm->deposit() >= 0 && unsigned(m_asm->deposit()) >= _offsetToCurrent, ""); - solAssert(m_localVariables.count(&_declaration) == 0, "Variable already present"); - m_localVariables[&_declaration] = unsigned(m_asm->deposit()) - _offsetToCurrent; + m_localVariables[&_declaration].push_back(unsigned(m_asm->deposit()) - _offsetToCurrent); } void CompilerContext::removeVariable(VariableDeclaration const& _declaration) { - solAssert(!!m_localVariables.count(&_declaration), ""); - m_localVariables.erase(&_declaration); + solAssert(m_localVariables.count(&_declaration) && !m_localVariables[&_declaration].empty(), ""); + m_localVariables[&_declaration].pop_back(); + if (m_localVariables[&_declaration].empty()) + m_localVariables.erase(&_declaration); } eth::Assembly const& CompilerContext::compiledContract(const ContractDefinition& _contract) const @@ -196,15 +197,15 @@ ModifierDefinition const& CompilerContext::functionModifier(string const& _name) for (ModifierDefinition const* modifier: contract->functionModifiers()) if (modifier->name() == _name) return *modifier; - BOOST_THROW_EXCEPTION(InternalCompilerError() - << errinfo_comment("Function modifier " + _name + " not found.")); + solAssert(false, "Function modifier " + _name + " not found."); } unsigned CompilerContext::baseStackOffsetOfVariable(Declaration const& _declaration) const { auto res = m_localVariables.find(&_declaration); solAssert(res != m_localVariables.end(), "Variable not found on stack."); - return res->second; + solAssert(!res->second.empty(), ""); + return res->second.back(); } unsigned CompilerContext::baseToCurrentStackOffset(unsigned _baseOffset) const @@ -310,6 +311,7 @@ void CompilerContext::appendInlineAssembly( if (stackDiff < 1 || stackDiff > 16) BOOST_THROW_EXCEPTION( CompilerError() << + errinfo_sourceLocation(_identifier.location) << errinfo_comment("Stack too deep (" + to_string(stackDiff) + "), try removing local variables.") ); if (_context == julia::IdentifierContext::RValue) diff --git a/libsolidity/codegen/CompilerContext.h b/libsolidity/codegen/CompilerContext.h index 1968c1e1..13821f67 100644 --- a/libsolidity/codegen/CompilerContext.h +++ b/libsolidity/codegen/CompilerContext.h @@ -272,7 +272,10 @@ private: /// Storage offsets of state variables std::map<Declaration const*, std::pair<u256, unsigned>> m_stateVariables; /// Offsets of local variables on the stack (relative to stack base). - std::map<Declaration const*, unsigned> m_localVariables; + /// This needs to be a stack because if a modifier contains a local variable and this + /// modifier is applied twice, the position of the variable needs to be restored + /// after the nested modifier is left. + std::map<Declaration const*, std::vector<unsigned>> m_localVariables; /// List of current inheritance hierarchy from derived to base. std::vector<ContractDefinition const*> m_inheritanceHierarchy; /// Stack of current visited AST nodes, used for location attachment diff --git a/libsolidity/codegen/CompilerUtils.cpp b/libsolidity/codegen/CompilerUtils.cpp index 7067ddd5..782aad9d 100644 --- a/libsolidity/codegen/CompilerUtils.cpp +++ b/libsolidity/codegen/CompilerUtils.cpp @@ -504,7 +504,7 @@ void CompilerUtils::convertType( //shift all integer bits onto the left side of the fixed type FixedPointType const& targetFixedPointType = dynamic_cast<FixedPointType const&>(_targetType); if (auto typeOnStack = dynamic_cast<IntegerType const*>(&_typeOnStack)) - if (targetFixedPointType.integerBits() > typeOnStack->numBits()) + if (targetFixedPointType.numBits() > typeOnStack->numBits()) cleanHigherOrderBits(*typeOnStack); solUnimplemented("Not yet implemented - FixedPointType."); } diff --git a/libsolidity/codegen/ContractCompiler.cpp b/libsolidity/codegen/ContractCompiler.cpp index cad388df..fd0998d4 100644 --- a/libsolidity/codegen/ContractCompiler.cpp +++ b/libsolidity/codegen/ContractCompiler.cpp @@ -267,18 +267,13 @@ void ContractCompiler::appendFunctionSelector(ContractDefinition const& _contrac m_context << notFound; if (fallback) { - m_context.setStackOffset(0); if (!fallback->isPayable()) appendCallValueCheck(); - // Return tag is used to jump out of the function. - eth::AssemblyItem returnTag = m_context.pushNewTag(); - fallback->accept(*this); - m_context << returnTag; + solAssert(fallback->isFallback(), ""); solAssert(FunctionType(*fallback).parameterTypes().empty(), ""); solAssert(FunctionType(*fallback).returnParameterTypes().empty(), ""); - // Return tag gets consumed. - m_context.adjustStackOffset(-1); + fallback->accept(*this); m_context << Instruction::STOP; } else @@ -536,7 +531,8 @@ bool ContractCompiler::visit(FunctionDefinition const& _function) m_context.adjustStackOffset(-(int)c_returnValuesSize); - if (!_function.isConstructor()) + /// The constructor and the fallback function doesn't to jump out. + if (!_function.isConstructor() && !_function.isFallback()) m_context.appendJump(eth::AssemblyItem::JumpType::OutOfFunction); return false; } diff --git a/libsolidity/codegen/ExpressionCompiler.cpp b/libsolidity/codegen/ExpressionCompiler.cpp index 82518e8c..02cc62be 100644 --- a/libsolidity/codegen/ExpressionCompiler.cpp +++ b/libsolidity/codegen/ExpressionCompiler.cpp @@ -174,7 +174,12 @@ void ExpressionCompiler::appendStateVariableAccessor(VariableDeclaration const& retSizeOnStack = returnTypes.front()->sizeOnStack(); } solAssert(retSizeOnStack == utils().sizeOnStack(returnTypes), ""); - solAssert(retSizeOnStack <= 15, "Stack is too deep."); + if (retSizeOnStack > 15) + BOOST_THROW_EXCEPTION( + CompilerError() << + errinfo_sourceLocation(_varDecl.location()) << + errinfo_comment("Stack too deep.") + ); m_context << dupInstruction(retSizeOnStack + 1); m_context.appendJump(eth::AssemblyItem::JumpType::OutOfFunction); } @@ -373,8 +378,7 @@ bool ExpressionCompiler::visit(UnaryOperation const& _unaryOperation) m_context << u256(0) << Instruction::SUB; break; default: - BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Invalid unary operator: " + - string(Token::toString(_unaryOperation.getOperator())))); + solAssert(false, "Invalid unary operator: " + string(Token::toString(_unaryOperation.getOperator()))); } return false; } @@ -895,7 +899,7 @@ bool ExpressionCompiler::visit(FunctionCall const& _functionCall) break; } default: - BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Invalid function type.")); + solAssert(false, "Invalid function type."); } } return false; @@ -1061,7 +1065,7 @@ bool ExpressionCompiler::visit(MemberAccess const& _memberAccess) true ); else - BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Invalid member access to integer.")); + solAssert(false, "Invalid member access to integer"); break; case Type::Category::Function: solAssert(!!_memberAccess.expression().annotation().type->memberType(member), @@ -1095,7 +1099,7 @@ bool ExpressionCompiler::visit(MemberAccess const& _memberAccess) m_context << u256(0) << Instruction::CALLDATALOAD << (u256(0xffffffff) << (256 - 32)) << Instruction::AND; else - BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Unknown magic member.")); + solAssert(false, "Unknown magic member."); break; case Type::Category::Struct: { @@ -1172,7 +1176,7 @@ bool ExpressionCompiler::visit(MemberAccess const& _memberAccess) break; } default: - BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Member access to unknown type.")); + solAssert(false, "Member access to unknown type."); } return false; } @@ -1327,7 +1331,7 @@ void ExpressionCompiler::endVisit(Identifier const& _identifier) } else { - BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Identifier type not expected in expression context.")); + solAssert(false, "Identifier type not expected in expression context."); } } @@ -1410,7 +1414,7 @@ void ExpressionCompiler::appendCompareOperatorCode(Token::Value _operator, Type m_context << (isSigned ? Instruction::SLT : Instruction::LT); break; default: - BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Unknown comparison operator.")); + solAssert(false, "Unknown comparison operator."); } } } @@ -1422,7 +1426,7 @@ void ExpressionCompiler::appendOrdinaryBinaryOperatorCode(Token::Value _operator else if (Token::isBitOp(_operator)) appendBitOperatorCode(_operator); else - BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Unknown binary operator.")); + solAssert(false, "Unknown binary operator."); } void ExpressionCompiler::appendArithmeticOperatorCode(Token::Value _operator, Type const& _type) @@ -1461,7 +1465,7 @@ void ExpressionCompiler::appendArithmeticOperatorCode(Token::Value _operator, Ty m_context << Instruction::EXP; break; default: - BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Unknown arithmetic operator.")); + solAssert(false, "Unknown arithmetic operator."); } } @@ -1479,7 +1483,7 @@ void ExpressionCompiler::appendBitOperatorCode(Token::Value _operator) m_context << Instruction::XOR; break; default: - BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Unknown bit operator.")); + solAssert(false, "Unknown bit operator."); } } @@ -1523,7 +1527,7 @@ void ExpressionCompiler::appendShiftOperatorCode(Token::Value _operator, Type co break; case Token::SHR: default: - BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Unknown shift operator.")); + solAssert(false, "Unknown shift operator."); } } @@ -1618,7 +1622,7 @@ void ExpressionCompiler::appendExternalFunctionCall( // zero bytes (which we cannot detect). solAssert(0 < retSize && retSize <= 32, ""); utils().fetchFreeMemoryPointer(); - m_context << Instruction::DUP1 << u256(0) << Instruction::MSTORE; + m_context << u256(0) << Instruction::DUP2 << Instruction::MSTORE; m_context << u256(32) << Instruction::ADD; utils().storeFreeMemoryPointer(); } diff --git a/libsolidity/inlineasm/AsmAnalysis.cpp b/libsolidity/inlineasm/AsmAnalysis.cpp index 7e00ffae..76b0bbd5 100644 --- a/libsolidity/inlineasm/AsmAnalysis.cpp +++ b/libsolidity/inlineasm/AsmAnalysis.cpp @@ -174,14 +174,20 @@ bool AsmAnalyzer::operator()(assembly::Assignment const& _assignment) bool AsmAnalyzer::operator()(assembly::VariableDeclaration const& _varDecl) { - int const expectedItems = _varDecl.variables.size(); - int const stackHeight = m_stackHeight; - bool success = boost::apply_visitor(*this, *_varDecl.value); - if ((m_stackHeight - stackHeight) != expectedItems) + bool success = true; + int const numVariables = _varDecl.variables.size(); + if (_varDecl.value) { - m_errorReporter.declarationError(_varDecl.location, "Variable count mismatch."); - return false; + int const stackHeight = m_stackHeight; + success = boost::apply_visitor(*this, *_varDecl.value); + if ((m_stackHeight - stackHeight) != numVariables) + { + m_errorReporter.declarationError(_varDecl.location, "Variable count mismatch."); + return false; + } } + else + m_stackHeight += numVariables; for (auto const& variable: _varDecl.variables) { diff --git a/libsolidity/inlineasm/AsmParser.cpp b/libsolidity/inlineasm/AsmParser.cpp index d282a30d..133f70b1 100644 --- a/libsolidity/inlineasm/AsmParser.cpp +++ b/libsolidity/inlineasm/AsmParser.cpp @@ -347,10 +347,15 @@ assembly::VariableDeclaration Parser::parseVariableDeclaration() else break; } - expectToken(Token::Colon); - expectToken(Token::Assign); - varDecl.value.reset(new Statement(parseExpression())); - varDecl.location.end = locationOf(*varDecl.value).end; + if (currentToken() == Token::Colon) + { + expectToken(Token::Colon); + expectToken(Token::Assign); + varDecl.value.reset(new Statement(parseExpression())); + varDecl.location.end = locationOf(*varDecl.value).end; + } + else + varDecl.location.end = varDecl.variables.back().location.end; return varDecl; } diff --git a/libsolidity/inlineasm/AsmPrinter.cpp b/libsolidity/inlineasm/AsmPrinter.cpp index 062ff453..4f96a3e9 100644 --- a/libsolidity/inlineasm/AsmPrinter.cpp +++ b/libsolidity/inlineasm/AsmPrinter.cpp @@ -128,8 +128,11 @@ string AsmPrinter::operator()(assembly::VariableDeclaration const& _variableDecl ), ", " ); - out += " := "; - out += boost::apply_visitor(*this, *_variableDeclaration.value); + if (_variableDeclaration.value) + { + out += " := "; + out += boost::apply_visitor(*this, *_variableDeclaration.value); + } return out; } diff --git a/libsolidity/inlineasm/AsmScopeFiller.cpp b/libsolidity/inlineasm/AsmScopeFiller.cpp index 5b3174b8..b70ae9ac 100644 --- a/libsolidity/inlineasm/AsmScopeFiller.cpp +++ b/libsolidity/inlineasm/AsmScopeFiller.cpp @@ -27,6 +27,8 @@ #include <libsolidity/interface/ErrorReporter.h> #include <libsolidity/interface/Exceptions.h> +#include <libdevcore/CommonData.h> + #include <boost/range/adaptor/reversed.hpp> #include <memory> diff --git a/libsolidity/interface/CompilerStack.cpp b/libsolidity/interface/CompilerStack.cpp index e2507821..9689b700 100644 --- a/libsolidity/interface/CompilerStack.cpp +++ b/libsolidity/interface/CompilerStack.cpp @@ -87,6 +87,7 @@ void CompilerStack::reset(bool _keepSources) m_stackState = Empty; m_sources.clear(); } + m_libraries.clear(); m_optimize = false; m_optimizeRuns = 200; m_globalContext.reset(); @@ -106,12 +107,6 @@ bool CompilerStack::addSource(string const& _name, string const& _content, bool return existed; } -void CompilerStack::setSource(string const& _sourceCode) -{ - reset(); - addSource("", _sourceCode); -} - bool CompilerStack::parse() { //reset @@ -252,44 +247,17 @@ bool CompilerStack::analyze() return false; } -bool CompilerStack::parse(string const& _sourceCode) -{ - setSource(_sourceCode); - return parse(); -} - bool CompilerStack::parseAndAnalyze() { return parse() && analyze(); } -bool CompilerStack::parseAndAnalyze(std::string const& _sourceCode) -{ - setSource(_sourceCode); - return parseAndAnalyze(); -} - -vector<string> CompilerStack::contractNames() const -{ - if (m_stackState < AnalysisSuccessful) - BOOST_THROW_EXCEPTION(CompilerError() << errinfo_comment("Parsing was not successful.")); - vector<string> contractNames; - for (auto const& contract: m_contracts) - contractNames.push_back(contract.first); - return contractNames; -} - - -bool CompilerStack::compile(bool _optimize, unsigned _runs, map<string, h160> const& _libraries) +bool CompilerStack::compile() { if (m_stackState < AnalysisSuccessful) if (!parseAndAnalyze()) return false; - m_optimize = _optimize; - m_optimizeRuns = _runs; - m_libraries = _libraries; - map<ContractDefinition const*, eth::Assembly const*> compiledContracts; for (Source const* source: m_sourceOrder) for (ASTPointer<ASTNode> const& node: source->ast->nodes()) @@ -300,11 +268,6 @@ bool CompilerStack::compile(bool _optimize, unsigned _runs, map<string, h160> co return true; } -bool CompilerStack::compile(string const& _sourceCode, bool _optimize, unsigned _runs) -{ - return parseAndAnalyze(_sourceCode) && compile(_optimize, _runs); -} - void CompilerStack::link() { for (auto& contract: m_contracts) @@ -315,6 +278,16 @@ void CompilerStack::link() } } +vector<string> CompilerStack::contractNames() const +{ + if (m_stackState < AnalysisSuccessful) + BOOST_THROW_EXCEPTION(CompilerError() << errinfo_comment("Parsing was not successful.")); + vector<string> contractNames; + for (auto const& contract: m_contracts) + contractNames.push_back(contract.first); + return contractNames; +} + eth::AssemblyItems const* CompilerStack::assemblyItems(string const& _contractName) const { Contract const& currentContract = contract(_contractName); @@ -451,18 +424,20 @@ Json::Value const& CompilerStack::natspec(Contract const& _contract, Documentati { case DocumentationType::NatspecUser: doc = &_contract.userDocumentation; + // caches the result + if (!*doc) + doc->reset(new Json::Value(Natspec::userDocumentation(*_contract.contract))); break; case DocumentationType::NatspecDev: doc = &_contract.devDocumentation; + // caches the result + if (!*doc) + doc->reset(new Json::Value(Natspec::devDocumentation(*_contract.contract))); break; default: - BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Illegal documentation type.")); + solAssert(false, "Illegal documentation type."); } - // caches the result - if (!*doc) - doc->reset(new Json::Value(Natspec::documentation(*_contract.contract, _type))); - return *(*doc); } @@ -474,12 +449,12 @@ Json::Value CompilerStack::methodIdentifiers(string const& _contractName) const return methodIdentifiers; } -string const& CompilerStack::onChainMetadata(string const& _contractName) const +string const& CompilerStack::metadata(string const& _contractName) const { if (m_stackState != CompilationSuccessful) BOOST_THROW_EXCEPTION(CompilerError() << errinfo_comment("Compilation was not successful.")); - return contract(_contractName).onChainMetadata; + return contract(_contractName).metadata; } Scanner const& CompilerStack::scanner(string const& _sourceName) const @@ -673,11 +648,11 @@ void CompilerStack::compileContract( shared_ptr<Compiler> compiler = make_shared<Compiler>(m_optimize, m_optimizeRuns); Contract& compiledContract = m_contracts.at(_contract.fullyQualifiedName()); - string onChainMetadata = createOnChainMetadata(compiledContract); + string metadata = createMetadata(compiledContract); bytes cborEncodedMetadata = - // CBOR-encoding of {"bzzr0": dev::swarmHash(onChainMetadata)} + // CBOR-encoding of {"bzzr0": dev::swarmHash(metadata)} bytes{0xa1, 0x65, 'b', 'z', 'z', 'r', '0', 0x58, 0x20} + - dev::swarmHash(onChainMetadata).asBytes(); + dev::swarmHash(metadata).asBytes(); solAssert(cborEncodedMetadata.size() <= 0xffff, "Metadata too large"); // 16-bit big endian length cborEncodedMetadata += toCompactBigEndian(cborEncodedMetadata.size(), 2); @@ -690,11 +665,11 @@ void CompilerStack::compileContract( } catch(eth::OptimizerException const&) { - BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Assembly optimizer exception for bytecode")); + solAssert(false, "Assembly optimizer exception for bytecode"); } catch(eth::AssemblyException const&) { - BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Assembly exception for bytecode")); + solAssert(false, "Assembly exception for bytecode"); } try @@ -703,14 +678,14 @@ void CompilerStack::compileContract( } catch(eth::OptimizerException const&) { - BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Assembly optimizer exception for deployed bytecode")); + solAssert(false, "Assembly optimizer exception for deployed bytecode"); } catch(eth::AssemblyException const&) { - BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Assembly exception for deployed bytecode")); + solAssert(false, "Assembly exception for deployed bytecode"); } - compiledContract.onChainMetadata = onChainMetadata; + compiledContract.metadata = metadata; _compiledContracts[compiledContract.contract] = &compiler->assembly(); try @@ -771,16 +746,25 @@ CompilerStack::Source const& CompilerStack::source(string const& _sourceName) co return it->second; } -string CompilerStack::createOnChainMetadata(Contract const& _contract) const +string CompilerStack::createMetadata(Contract const& _contract) const { Json::Value meta; meta["version"] = 1; meta["language"] = "Solidity"; meta["compiler"]["version"] = VersionStringStrict; + /// All the source files (including self), which should be included in the metadata. + set<string> referencedSources; + referencedSources.insert(_contract.contract->sourceUnit().annotation().path); + for (auto const sourceUnit: _contract.contract->sourceUnit().referencedSourceUnits(true)) + referencedSources.insert(sourceUnit->annotation().path); + meta["sources"] = Json::objectValue; for (auto const& s: m_sources) { + if (!referencedSources.count(s.first)) + continue; + solAssert(s.second.scanner, "Scanner not available"); meta["sources"][s.first]["keccak256"] = "0x" + toHex(dev::keccak256(s.second.scanner->source()).asBytes()); @@ -951,7 +935,7 @@ Json::Value CompilerStack::gasEstimates(string const& _contractName) const for (auto const& it: contract.definedFunctions()) { /// Exclude externally visible functions, constructor and the fallback function - if (it->isPartOfExternalInterface() || it->isConstructor() || it->name().empty()) + if (it->isPartOfExternalInterface() || it->isConstructor() || it->isFallback()) continue; size_t entry = functionEntryPoint(_contractName, *it); @@ -959,12 +943,14 @@ Json::Value CompilerStack::gasEstimates(string const& _contractName) const if (entry > 0) gas = GasEstimator::functionalEstimation(*items, entry, *it); + /// TODO: This could move into a method shared with externalSignature() FunctionType type(*it); string sig = it->name() + "("; auto paramTypes = type.parameterTypes(); for (auto it = paramTypes.begin(); it != paramTypes.end(); ++it) sig += (*it)->toString() + (it + 1 == paramTypes.end() ? "" : ","); sig += ")"; + internalFunctions[sig] = gasToJson(gas); } diff --git a/libsolidity/interface/CompilerStack.h b/libsolidity/interface/CompilerStack.h index 03a1b806..d287f224 100644 --- a/libsolidity/interface/CompilerStack.h +++ b/libsolidity/interface/CompilerStack.h @@ -93,87 +93,116 @@ public: m_errorList(), m_errorReporter(m_errorList) {} - /// Sets path remappings in the format "context:prefix=target" - void setRemappings(std::vector<std::string> const& _remappings); + /// @returns the list of errors that occured during parsing and type checking. + ErrorList const& errors() { return m_errorReporter.errors(); } + + /// @returns the current state. + State state() const { return m_stackState; } /// Resets the compiler to a state where the sources are not parsed or even removed. + /// Sets the state to SourcesSet if @a _keepSources is true, otherwise to Empty. + /// All settings, with the exception of remappings, are reset. void reset(bool _keepSources = false); - /// Adds a source object (e.g. file) to the parser. After this, parse has to be called again. - /// @returns true if a source object by the name already existed and was replaced. - void addSources(StringMap const& _nameContents, bool _isLibrary = false) + /// Sets path remappings in the format "context:prefix=target" + void setRemappings(std::vector<std::string> const& _remappings); + + /// Sets library addresses. Addresses are cleared iff @a _libraries is missing. + /// Will not take effect before running compile. + void setLibraries(std::map<std::string, h160> const& _libraries = std::map<std::string, h160>{}) { - for (auto const& i: _nameContents) addSource(i.first, i.second, _isLibrary); + m_libraries = _libraries; } + + /// Changes the optimiser settings. + /// Will not take effect before running compile. + void setOptimiserSettings(bool _optimize, unsigned _runs = 200) + { + m_optimize = _optimize; + m_optimizeRuns = _runs; + } + + /// Adds a source object (e.g. file) to the parser. After this, parse has to be called again. + /// @returns true if a source object by the name already existed and was replaced. bool addSource(std::string const& _name, std::string const& _content, bool _isLibrary = false); - void setSource(std::string const& _sourceCode); + /// Parses all source units that were added /// @returns false on error. bool parse(); - /// Sets the given source code as the only source unit apart from standard sources and parses it. - /// @returns false on error. - bool parse(std::string const& _sourceCode); - /// performs the analyisis steps (imports, scopesetting, syntaxCheck, referenceResolving, + + /// Performs the analysis steps (imports, scopesetting, syntaxCheck, referenceResolving, /// typechecking, staticAnalysis) on previously set sources /// @returns false on error. bool analyze(); + /// Parses and analyzes all source units that were added /// @returns false on error. bool parseAndAnalyze(); - /// Sets the given source code as the only source unit apart from standard sources and parses and analyzes it. - /// @returns false on error. - bool parseAndAnalyze(std::string const& _sourceCode); + /// @returns a list of the contract names in the sources. std::vector<std::string> contractNames() const; /// Compiles the source units that were previously added and parsed. /// @returns false on error. - bool compile( - bool _optimize = false, - unsigned _runs = 200, - std::map<std::string, h160> const& _libraries = std::map<std::string, h160>{} - ); - /// Parses and compiles the given source code. - /// @returns false on error. - bool compile(std::string const& _sourceCode, bool _optimize = false, unsigned _runs = 200); + bool compile(); + + /// @returns the list of sources (paths) used + std::vector<std::string> sourceNames() const; + + /// @returns a mapping assigning each source name its index inside the vector returned + /// by sourceNames(). + std::map<std::string, unsigned> sourceIndices() const; + + /// @returns the previously used scanner, useful for counting lines during error reporting. + Scanner const& scanner(std::string const& _sourceName = "") const; + + /// @returns the parsed source unit with the supplied name. + SourceUnit const& ast(std::string const& _sourceName = "") const; + + /// Helper function for logs printing. Do only use in error cases, it's quite expensive. + /// line and columns are numbered starting from 1 with following order: + /// start line, start column, end line, end column + std::tuple<int, int, int, int> positionFromSourceLocation(SourceLocation const& _sourceLocation) const; + + /// @returns either the contract's name or a mixture of its name and source file, sanitized for filesystem use + std::string const filesystemFriendlyName(std::string const& _contractName) const; /// @returns the assembled object for a contract. eth::LinkerObject const& object(std::string const& _contractName = "") const; + /// @returns the runtime object for the contract. eth::LinkerObject const& runtimeObject(std::string const& _contractName = "") const; + /// @returns the bytecode of a contract that uses an already deployed contract via DELEGATECALL. /// The returned bytes will contain a sequence of 20 bytes of the format "XXX...XXX" which have to /// substituted by the actual address. Note that this sequence starts end ends in three X /// characters but can contain anything in between. eth::LinkerObject const& cloneObject(std::string const& _contractName = "") const; + /// @returns normal contract assembly items eth::AssemblyItems const* assemblyItems(std::string const& _contractName = "") const; + /// @returns runtime contract assembly items eth::AssemblyItems const* runtimeAssemblyItems(std::string const& _contractName = "") const; + /// @returns the string that provides a mapping between bytecode and sourcecode or a nullptr /// if the contract does not (yet) have bytecode. std::string const* sourceMapping(std::string const& _contractName = "") const; + /// @returns the string that provides a mapping between runtime bytecode and sourcecode. /// if the contract does not (yet) have bytecode. std::string const* runtimeSourceMapping(std::string const& _contractName = "") const; - /// @returns either the contract's name or a mixture of its name and source file, sanitized for filesystem use - std::string const filesystemFriendlyName(std::string const& _contractName) const; - /// Streams a verbose version of the assembly to @a _outStream. /// @arg _sourceCodes is the map of input files to source code strings /// @arg _inJsonFromat shows whether the out should be in Json format /// Prerequisite: Successful compilation. Json::Value streamAssembly(std::ostream& _outStream, std::string const& _contractName = "", StringMap _sourceCodes = StringMap(), bool _inJsonFormat = false) const; - /// @returns the list of sources (paths) used - std::vector<std::string> sourceNames() const; - /// @returns a mapping assigning each source name its index inside the vector returned - /// by sourceNames(). - std::map<std::string, unsigned> sourceIndices() const; /// @returns a JSON representing the contract ABI. /// Prerequisite: Successful call to parse or compile. Json::Value const& contractABI(std::string const& _contractName = "") const; + /// @returns a JSON representing the contract's documentation. /// Prerequisite: Successful call to parse or compile. /// @param type The type of the documentation to get. @@ -183,27 +212,13 @@ public: /// @returns a JSON representing a map of method identifiers (hashes) to function names. Json::Value methodIdentifiers(std::string const& _contractName) const; - std::string const& onChainMetadata(std::string const& _contractName) const; + /// @returns the Contract Metadata + std::string const& metadata(std::string const& _contractName) const; void useMetadataLiteralSources(bool _metadataLiteralSources) { m_metadataLiteralSources = _metadataLiteralSources; } /// @returns a JSON representing the estimated gas usage for contract creation, internal and external functions Json::Value gasEstimates(std::string const& _contractName) const; - /// @returns the previously used scanner, useful for counting lines during error reporting. - Scanner const& scanner(std::string const& _sourceName = "") const; - /// @returns the parsed source unit with the supplied name. - SourceUnit const& ast(std::string const& _sourceName = "") const; - - /// Helper function for logs printing. Do only use in error cases, it's quite expensive. - /// line and columns are numbered starting from 1 with following order: - /// start line, start column, end line, end column - std::tuple<int, int, int, int> positionFromSourceLocation(SourceLocation const& _sourceLocation) const; - - /// @returns the list of errors that occured during parsing and type checking. - ErrorList const& errors() { return m_errorReporter.errors(); } - - State state() const { return m_stackState; } - private: /** * Information pertaining to one source unit, filled gradually during parsing and compilation. @@ -223,13 +238,14 @@ private: eth::LinkerObject object; eth::LinkerObject runtimeObject; eth::LinkerObject cloneObject; - std::string onChainMetadata; ///< The metadata json that will be hashed into the chain. + std::string metadata; ///< The metadata json that will be hashed into the chain. mutable std::unique_ptr<Json::Value const> abi; mutable std::unique_ptr<Json::Value const> userDocumentation; mutable std::unique_ptr<Json::Value const> devDocumentation; mutable std::unique_ptr<std::string const> sourceMapping; mutable std::unique_ptr<std::string const> runtimeSourceMapping; }; + /// Loads the missing sources from @a _ast (named @a _path) using the callback /// @a m_readFile and stores the absolute paths of all imports in the AST annotations. /// @returns the newly loaded sources. @@ -255,7 +271,7 @@ private: /// does not exist. ContractDefinition const& contractDefinition(std::string const& _contractName) const; - std::string createOnChainMetadata(Contract const& _contract) const; + std::string createMetadata(Contract const& _contract) const; std::string computeSourceMapping(eth::AssemblyItems const& _items) const; Json::Value const& contractABI(Contract const&) const; Json::Value const& natspec(Contract const&, DocumentationType _type) const; diff --git a/libsolidity/interface/ErrorReporter.cpp b/libsolidity/interface/ErrorReporter.cpp index 6e2667a5..f9ef4ceb 100644 --- a/libsolidity/interface/ErrorReporter.cpp +++ b/libsolidity/interface/ErrorReporter.cpp @@ -42,11 +42,23 @@ void ErrorReporter::warning(string const& _description) error(Error::Type::Warning, SourceLocation(), _description); } -void ErrorReporter::warning(SourceLocation const& _location, string const& _description) +void ErrorReporter::warning( + SourceLocation const& _location, + string const& _description +) { error(Error::Type::Warning, _location, _description); } +void ErrorReporter::warning( + SourceLocation const& _location, + string const& _description, + SecondarySourceLocation const& _secondaryLocation +) +{ + error(Error::Type::Warning, _location, _secondaryLocation, _description); +} + void ErrorReporter::error(Error::Type _type, SourceLocation const& _location, string const& _description) { auto err = make_shared<Error>(_type); diff --git a/libsolidity/interface/ErrorReporter.h b/libsolidity/interface/ErrorReporter.h index e5605d24..8b066a3e 100644 --- a/libsolidity/interface/ErrorReporter.h +++ b/libsolidity/interface/ErrorReporter.h @@ -41,30 +41,30 @@ public: ErrorReporter& operator=(ErrorReporter const& _errorReporter); - void warning(std::string const& _description = std::string()); + void warning(std::string const& _description); + + void warning(SourceLocation const& _location, std::string const& _description); void warning( - SourceLocation const& _location = SourceLocation(), - std::string const& _description = std::string() + SourceLocation const& _location, + std::string const& _description, + SecondarySourceLocation const& _secondaryLocation ); void error( Error::Type _type, - SourceLocation const& _location = SourceLocation(), - std::string const& _description = std::string() - ); - - void declarationError( SourceLocation const& _location, - SecondarySourceLocation const& _secondaryLocation = SecondarySourceLocation(), - std::string const& _description = std::string() + std::string const& _description ); void declarationError( SourceLocation const& _location, - std::string const& _description = std::string() + SecondarySourceLocation const& _secondaryLocation, + std::string const& _description ); + void declarationError(SourceLocation const& _location, std::string const& _description); + void fatalDeclarationError(SourceLocation const& _location, std::string const& _description); void parserError(SourceLocation const& _location, std::string const& _description); diff --git a/libsolidity/interface/Exceptions.cpp b/libsolidity/interface/Exceptions.cpp index 9f2a2d06..a837dce6 100644 --- a/libsolidity/interface/Exceptions.cpp +++ b/libsolidity/interface/Exceptions.cpp @@ -67,16 +67,3 @@ Error::Error(Error::Type _type, const std::string& _description, const SourceLoc *this << errinfo_sourceLocation(_location); *this << errinfo_comment(_description); } - -string Exception::lineInfo() const -{ - char const* const* file = boost::get_error_info<boost::throw_file>(*this); - int const* line = boost::get_error_info<boost::throw_line>(*this); - string ret; - if (file) - ret += *file; - ret += ':'; - if (line) - ret += boost::lexical_cast<string>(*line); - return ret; -} diff --git a/libsolidity/interface/Natspec.cpp b/libsolidity/interface/Natspec.cpp index 70486e23..7f7084ef 100644 --- a/libsolidity/interface/Natspec.cpp +++ b/libsolidity/interface/Natspec.cpp @@ -26,28 +26,11 @@ #include <libsolidity/interface/Natspec.h> #include <boost/range/irange.hpp> #include <libsolidity/ast/AST.h> -#include <libsolidity/interface/CompilerStack.h> using namespace std; using namespace dev; using namespace dev::solidity; -Json::Value Natspec::documentation( - ContractDefinition const& _contractDef, - DocumentationType _type -) -{ - switch(_type) - { - case DocumentationType::NatspecUser: - return userDocumentation(_contractDef); - case DocumentationType::NatspecDev: - return devDocumentation(_contractDef); - } - - BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Unknown documentation type")); -} - Json::Value Natspec::userDocumentation(ContractDefinition const& _contractDef) { Json::Value doc; diff --git a/libsolidity/interface/Natspec.h b/libsolidity/interface/Natspec.h index bec9acd2..9ac3efea 100644 --- a/libsolidity/interface/Natspec.h +++ b/libsolidity/interface/Natspec.h @@ -39,7 +39,6 @@ class ContractDefinition; class Type; using TypePointer = std::shared_ptr<Type const>; struct DocTag; -enum class DocumentationType: uint8_t; enum class DocTagType: uint8_t { @@ -61,15 +60,6 @@ enum class CommentOwner class Natspec { public: - /// Get the given type of documentation - /// @param _contractDef The contract definition - /// @param _type The type of the documentation. Can be one of the - /// types provided by @c DocumentationType - /// @return A JSON representation of provided type - static Json::Value documentation( - ContractDefinition const& _contractDef, - DocumentationType _type - ); /// Get the User documentation of the contract /// @param _contractDef The contract definition /// @return A JSON representation of the contract's user documentation diff --git a/libsolidity/interface/StandardCompiler.cpp b/libsolidity/interface/StandardCompiler.cpp index 15bb7592..dd135ce5 100644 --- a/libsolidity/interface/StandardCompiler.cpp +++ b/libsolidity/interface/StandardCompiler.cpp @@ -247,8 +247,9 @@ Json::Value StandardCompiler::compileInternal(Json::Value const& _input) m_compilerStack.setRemappings(remappings); Json::Value optimizerSettings = settings.get("optimizer", Json::Value()); - bool optimize = optimizerSettings.get("enabled", Json::Value(false)).asBool(); - unsigned optimizeRuns = optimizerSettings.get("runs", Json::Value(200u)).asUInt(); + bool const optimize = optimizerSettings.get("enabled", Json::Value(false)).asBool(); + unsigned const optimizeRuns = optimizerSettings.get("runs", Json::Value(200u)).asUInt(); + m_compilerStack.setOptimiserSettings(optimize, optimizeRuns); map<string, h160> libraries; Json::Value jsonLibraries = settings.get("libraries", Json::Value()); @@ -259,6 +260,7 @@ Json::Value StandardCompiler::compileInternal(Json::Value const& _input) // @TODO use libraries only for the given source libraries[library] = h160(jsonSourceName[library].asString()); } + m_compilerStack.setLibraries(libraries); Json::Value metadataSettings = settings.get("metadata", Json::Value()); m_compilerStack.useMetadataLiteralSources(metadataSettings.get("useLiteralContent", Json::Value(false)).asBool()); @@ -267,7 +269,7 @@ Json::Value StandardCompiler::compileInternal(Json::Value const& _input) try { - m_compilerStack.compile(optimize, optimizeRuns, libraries); + m_compilerStack.compile(); for (auto const& error: m_compilerStack.errors()) { @@ -283,24 +285,27 @@ Json::Value StandardCompiler::compileInternal(Json::Value const& _input) )); } } + /// This is only thrown in a very few locations. catch (Error const& _error) { - if (_error.type() == Error::Type::DocstringParsingError) - errors.append(formatError( - false, - "DocstringParsingError", - "general", - "Documentation parsing error: " + *boost::get_error_info<errinfo_comment>(_error) - )); - else - errors.append(formatErrorWithException( - _error, - false, - _error.typeName(), - "general", - "", - scannerFromSourceName - )); + errors.append(formatErrorWithException( + _error, + false, + _error.typeName(), + "general", + "Uncaught error: ", + scannerFromSourceName + )); + } + /// This should not be leaked from compile(). + catch (FatalError const& _exception) + { + errors.append(formatError( + false, + "FatalError", + "general", + "Uncaught fatal error: " + boost::diagnostic_information(_exception) + )); } catch (CompilerError const& _exception) { @@ -320,7 +325,8 @@ Json::Value StandardCompiler::compileInternal(Json::Value const& _input) false, "InternalCompilerError", "general", - "Internal compiler error (" + _exception.lineInfo() + ")", scannerFromSourceName + "Internal compiler error (" + _exception.lineInfo() + ")", + scannerFromSourceName )); } catch (UnimplementedFeatureError const& _exception) @@ -331,7 +337,8 @@ Json::Value StandardCompiler::compileInternal(Json::Value const& _input) "UnimplementedFeatureError", "general", "Unimplemented feature (" + _exception.lineInfo() + ")", - scannerFromSourceName)); + scannerFromSourceName + )); } catch (Exception const& _exception) { @@ -352,27 +359,27 @@ Json::Value StandardCompiler::compileInternal(Json::Value const& _input) )); } - Json::Value output = Json::objectValue; - - if (errors.size() > 0) - output["errors"] = errors; - - bool analysisSuccess = m_compilerStack.state() >= CompilerStack::State::AnalysisSuccessful; - bool compilationSuccess = m_compilerStack.state() == CompilerStack::State::CompilationSuccessful; + bool const analysisSuccess = m_compilerStack.state() >= CompilerStack::State::AnalysisSuccessful; + bool const compilationSuccess = m_compilerStack.state() == CompilerStack::State::CompilationSuccessful; /// Inconsistent state - stop here to receive error reports from users if (!compilationSuccess && (errors.size() == 0)) return formatFatalError("InternalCompilerError", "No error reported, but compilation failed."); + Json::Value output = Json::objectValue; + + if (errors.size() > 0) + output["errors"] = errors; + output["sources"] = Json::objectValue; unsigned sourceIndex = 0; - for (auto const& source: analysisSuccess ? m_compilerStack.sourceNames() : vector<string>()) + for (string const& sourceName: analysisSuccess ? m_compilerStack.sourceNames() : vector<string>()) { Json::Value sourceResult = Json::objectValue; sourceResult["id"] = sourceIndex++; - sourceResult["ast"] = ASTJsonConverter(false, m_compilerStack.sourceIndices()).toJson(m_compilerStack.ast(source)); - sourceResult["legacyAST"] = ASTJsonConverter(true, m_compilerStack.sourceIndices()).toJson(m_compilerStack.ast(source)); - output["sources"][source] = sourceResult; + sourceResult["ast"] = ASTJsonConverter(false, m_compilerStack.sourceIndices()).toJson(m_compilerStack.ast(sourceName)); + sourceResult["legacyAST"] = ASTJsonConverter(true, m_compilerStack.sourceIndices()).toJson(m_compilerStack.ast(sourceName)); + output["sources"][sourceName] = sourceResult; } Json::Value contractsOutput = Json::objectValue; @@ -386,7 +393,7 @@ Json::Value StandardCompiler::compileInternal(Json::Value const& _input) // ABI, documentation and metadata Json::Value contractData(Json::objectValue); contractData["abi"] = m_compilerStack.contractABI(contractName); - contractData["metadata"] = m_compilerStack.onChainMetadata(contractName); + contractData["metadata"] = m_compilerStack.metadata(contractName); contractData["userdoc"] = m_compilerStack.natspec(contractName, DocumentationType::NatspecUser); contractData["devdoc"] = m_compilerStack.natspec(contractName, DocumentationType::NatspecDev); diff --git a/libsolidity/parsing/Parser.cpp b/libsolidity/parsing/Parser.cpp index b0cf364e..b98991f3 100644 --- a/libsolidity/parsing/Parser.cpp +++ b/libsolidity/parsing/Parser.cpp @@ -87,7 +87,7 @@ ASTPointer<SourceUnit> Parser::parse(shared_ptr<Scanner> const& _scanner) nodes.push_back(parseContractDefinition(token)); break; default: - fatalParserError(string("Expected import directive or contract definition.")); + fatalParserError(string("Expected pragma, import directive or contract/interface/library definition.")); } } return nodeFactory.createNode<SourceUnit>(nodes); diff --git a/libsolidity/parsing/Token.cpp b/libsolidity/parsing/Token.cpp index 66312f69..9cec0303 100644 --- a/libsolidity/parsing/Token.cpp +++ b/libsolidity/parsing/Token.cpp @@ -70,7 +70,7 @@ void ElementaryTypeNameToken::assertDetails(Token::Value _baseType, unsigned con else if (_baseType == Token::UFixedMxN || _baseType == Token::FixedMxN) { solAssert( - _first + _second <= 256 && _first % 8 == 0 && _second % 8 == 0, + _first >= 8 && _first <= 256 && _first % 8 == 0 && _second <= 80, "No elementary type " + string(Token::toString(_baseType)) + to_string(_first) + "x" + to_string(_second) + "." ); } @@ -157,12 +157,8 @@ tuple<Token::Value, unsigned int, unsigned int> Token::fromIdentifierOrKeyword(s ) { int n = parseSize(positionX + 1, _literal.end()); if ( - 0 <= m && m <= 256 && - 8 <= n && n <= 256 && - m + n > 0 && - m + n <= 256 && - m % 8 == 0 && - n % 8 == 0 + 8 <= m && m <= 256 && m % 8 == 0 && + 0 <= n && n <= 80 ) { if (keyword == Token::UFixed) return make_tuple(Token::UFixedMxN, m, n); diff --git a/libsolidity/parsing/Token.h b/libsolidity/parsing/Token.h index 39c0eff9..d412b3f0 100644 --- a/libsolidity/parsing/Token.h +++ b/libsolidity/parsing/Token.h @@ -44,7 +44,7 @@ #include <libdevcore/Common.h> #include <libsolidity/interface/Exceptions.h> -#include <libdevcore/UndefMacros.h> +#include <libsolidity/parsing/UndefMacros.h> namespace dev { diff --git a/libdevcore/UndefMacros.h b/libsolidity/parsing/UndefMacros.h index d2da3323..d96e242e 100644 --- a/libdevcore/UndefMacros.h +++ b/libsolidity/parsing/UndefMacros.h @@ -19,7 +19,7 @@ * @date 2015 * * This header should be used to #undef some really evil macros defined by - * windows.h which result in conflict with our libsolidity/Token.h + * windows.h which result in conflict with our Token.h */ #pragma once diff --git a/scripts/isolate_tests.py b/scripts/isolate_tests.py index a1d1c75c..cfaef210 100755 --- a/scripts/isolate_tests.py +++ b/scripts/isolate_tests.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# This script reads C++ source files and writes all +# This script reads C++ or RST source files and writes all # multi-line strings into individual files. # This can be used to extract the Solidity test cases # into files for e.g. fuzz testing as @@ -12,7 +12,7 @@ import os import hashlib from os.path import join -def extract_cases(path): +def extract_test_cases(path): lines = open(path, 'rb').read().splitlines() inside = False @@ -34,6 +34,44 @@ def extract_cases(path): return tests +# Contract sources are indented by 4 spaces. +# Look for `pragma solidity` and abort a line not indented properly. +# If the comment `// This will not compile` is above the pragma, +# the code is skipped. +def extract_docs_cases(path): + # Note: this code works, because splitlines() removes empty new lines + # and thus even if the empty new lines are missing indentation + lines = open(path, 'rb').read().splitlines() + + ignore = False + inside = False + tests = [] + + for l in lines: + if inside: + # Abort if indentation is missing + m = re.search(r'^[^ ]+', l) + if m: + inside = False + else: + tests[-1] += l + '\n' + else: + m = re.search(r'^ // This will not compile', l) + if m: + ignore = True + + if ignore: + # Abort if indentation is missing + m = re.search(r'^[^ ]+', l) + if m: + ignore = False + else: + m = re.search(r'^ pragma solidity .*[0-9]+\.[0-9]+\.[0-9]+;$', l) + if m: + inside = True + tests += [l] + + return tests def write_cases(tests): for test in tests: @@ -41,8 +79,17 @@ def write_cases(tests): if __name__ == '__main__': path = sys.argv[1] + docs = False + if len(sys.argv) > 2 and sys.argv[2] == 'docs': + docs = True - for root, dir, files in os.walk(path): + for root, subdirs, files in os.walk(path): + if '_build' in subdirs: + subdirs.remove('_build') for f in files: - cases = extract_cases(join(root, f)) + path = join(root, f) + if docs: + cases = extract_docs_cases(path) + else: + cases = extract_test_cases(path) write_cases(cases) diff --git a/scripts/tests.sh b/scripts/tests.sh index 6b76c154..5d7eb0e1 100755 --- a/scripts/tests.sh +++ b/scripts/tests.sh @@ -33,10 +33,6 @@ REPO_ROOT="$(dirname "$0")"/.. echo "Running commandline tests..." "$REPO_ROOT/test/cmdlineTests.sh" -echo "Checking that StandardToken.sol, owned.sol and mortal.sol produce bytecode..." -output=$("$REPO_ROOT"/build/solc/solc --bin "$REPO_ROOT"/std/*.sol 2>/dev/null | grep "ffff" | wc -l) -test "${output//[[:blank:]]/}" = "3" - # This conditional is only needed because we don't have a working Homebrew # install for `eth` at the time of writing, so we unzip the ZIP file locally # instead. This will go away soon. diff --git a/snap/snapcraft.yaml b/snap/snapcraft.yaml index f0f3310a..db976bc3 100644 --- a/snap/snapcraft.yaml +++ b/snap/snapcraft.yaml @@ -1,5 +1,6 @@ name: solc -version: master +version: develop +version-script: git describe --exact-match --tags 2> /dev/null || echo "develop" summary: The Solidity Contract-Oriented Programming Language description: | Solidity is a contract-oriented, high-level language whose syntax is similar @@ -12,7 +13,7 @@ description: | It is possible to create contracts for voting, crowdfunding, blind auctions, multi-signature wallets and more. -grade: devel # must be 'stable' to release into candidate/stable channels +grade: stable confinement: strict apps: @@ -27,3 +28,8 @@ parts: plugin: cmake build-packages: [build-essential, libboost-all-dev] stage-packages: [libicu55] + prepare: | + if git describe --exact-match --tags 2> /dev/null + then + echo -n > ../src/prerelease.txt + fi diff --git a/solc/CMakeLists.txt b/solc/CMakeLists.txt index a5515d81..18e83e75 100644 --- a/solc/CMakeLists.txt +++ b/solc/CMakeLists.txt @@ -18,7 +18,7 @@ else() endif() if (EMSCRIPTEN) - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -s EXPORTED_FUNCTIONS='[\"_compileJSON\",\"_version\",\"_compileJSONMulti\",\"_compileJSONCallback\",\"_compileStandard\"]' -s RESERVED_FUNCTION_POINTERS=20") + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -s EXPORTED_FUNCTIONS='[\"_compileJSON\",\"_license\",\"_version\",\"_compileJSONMulti\",\"_compileJSONCallback\",\"_compileStandard\"]' -s RESERVED_FUNCTION_POINTERS=20") add_executable(soljson jsonCompiler.cpp ${HEADERS}) eth_use(soljson REQUIRED Solidity::solidity) else() diff --git a/solc/CommandLineInterface.cpp b/solc/CommandLineInterface.cpp index 0222ccb0..740061a1 100644 --- a/solc/CommandLineInterface.cpp +++ b/solc/CommandLineInterface.cpp @@ -292,12 +292,12 @@ void CommandLineInterface::handleSignatureHashes(string const& _contract) cout << "Function signatures: " << endl << out; } -void CommandLineInterface::handleOnChainMetadata(string const& _contract) +void CommandLineInterface::handleMetadata(string const& _contract) { if (!m_args.count(g_argMetadata)) return; - string data = m_compiler->onChainMetadata(_contract); + string data = m_compiler->metadata(_contract); if (m_args.count(g_argOutputDir)) createFile(m_compiler->filesystemFriendlyName(_contract) + "_meta.json", data); else @@ -774,10 +774,14 @@ bool CommandLineInterface::processInput() m_compiler->setRemappings(m_args[g_argInputFile].as<vector<string>>()); for (auto const& sourceCode: m_sourceCodes) m_compiler->addSource(sourceCode.first, sourceCode.second); + if (m_args.count(g_argLibraries)) + m_compiler->setLibraries(m_libraries); // TODO: Perhaps we should not compile unless requested bool optimize = m_args.count(g_argOptimize) > 0; unsigned runs = m_args[g_argOptimizeRuns].as<unsigned>(); - bool successful = m_compiler->compile(optimize, runs, m_libraries); + m_compiler->setOptimiserSettings(optimize, runs); + + bool successful = m_compiler->compile(); for (auto const& error: m_compiler->errors()) SourceReferenceFormatter::printExceptionInformation( @@ -850,7 +854,7 @@ void CommandLineInterface::handleCombinedJSON() if (requests.count(g_strAbi)) contractData[g_strAbi] = dev::jsonCompactPrint(m_compiler->contractABI(contractName)); if (requests.count("metadata")) - contractData["metadata"] = m_compiler->onChainMetadata(contractName); + contractData["metadata"] = m_compiler->metadata(contractName); if (requests.count(g_strBinary)) contractData[g_strBinary] = m_compiler->object(contractName).toHex(); if (requests.count(g_strBinaryRuntime)) @@ -1164,7 +1168,7 @@ void CommandLineInterface::outputCompilationResults() handleBytecode(contract); handleSignatureHashes(contract); - handleOnChainMetadata(contract); + handleMetadata(contract); handleABI(contract); handleNatspec(DocumentationType::NatspecDev, contract); handleNatspec(DocumentationType::NatspecUser, contract); diff --git a/solc/CommandLineInterface.h b/solc/CommandLineInterface.h index b482c20b..8a476ef5 100644 --- a/solc/CommandLineInterface.h +++ b/solc/CommandLineInterface.h @@ -64,7 +64,7 @@ private: void handleOpcode(std::string const& _contract); void handleBytecode(std::string const& _contract); void handleSignatureHashes(std::string const& _contract); - void handleOnChainMetadata(std::string const& _contract); + void handleMetadata(std::string const& _contract); void handleABI(std::string const& _contract); void handleNatspec(DocumentationType _type, std::string const& _contract); void handleGasEstimation(std::string const& _contract); diff --git a/test/RPCSession.h b/test/RPCSession.h index f3c3339a..f7fdd86e 100644 --- a/test/RPCSession.h +++ b/test/RPCSession.h @@ -21,7 +21,6 @@ #if defined(_WIN32) #include <windows.h> -#include "libdevcore/UndefMacros.h" #else #include <sys/types.h> #include <sys/socket.h> diff --git a/test/boostTest.cpp b/test/boostTest.cpp index 6fc1c925..c2121940 100644 --- a/test/boostTest.cpp +++ b/test/boostTest.cpp @@ -49,6 +49,8 @@ test_suite* init_unit_test_suite( int /*argc*/, char* /*argv*/[] ) "SolidityAuctionRegistrar", "SolidityFixedFeeRegistrar", "SolidityWallet", + "LLLERC20", + "LLLENS", "LLLEndToEndTest", "GasMeterTests", "SolidityEndToEndTest", diff --git a/test/cmdlineTests.sh b/test/cmdlineTests.sh index 4074ce55..eb5c714d 100755 --- a/test/cmdlineTests.sh +++ b/test/cmdlineTests.sh @@ -28,27 +28,87 @@ set -e -REPO_ROOT="$(dirname "$0")"/.. +REPO_ROOT=$(cd $(dirname "$0")/.. && pwd) +echo $REPO_ROOT SOLC="$REPO_ROOT/build/solc/solc" echo "Checking that the bug list is up to date..." "$REPO_ROOT"/scripts/update_bugs_by_version.py -echo "Compiling all files in std and examples..." +echo "Checking that StandardToken.sol, owned.sol and mortal.sol produce bytecode..." +output=$("$REPO_ROOT"/build/solc/solc --bin "$REPO_ROOT"/std/*.sol 2>/dev/null | grep "ffff" | wc -l) +test "${output//[[:blank:]]/}" = "3" -for f in "$REPO_ROOT"/std/*.sol -do - echo "Compiling $f..." +function compileFull() +{ + files="$*" + set +e + "$SOLC" --optimize \ + --combined-json abi,asm,ast,bin,bin-runtime,clone-bin,compact-format,devdoc,hashes,interface,metadata,opcodes,srcmap,srcmap-runtime,userdoc \ + $files >/dev/null 2>&1 + failed=$? + set -e + if [ $failed -ne 0 ] + then + echo "Compilation failed on:" + cat $files + false + fi +} + +function compileWithoutWarning() +{ + files="$*" set +e - output=$("$SOLC" "$f" 2>&1) + output=$("$SOLC" $files 2>&1) failed=$? # Remove the pre-release warning from the compiler output output=$(echo "$output" | grep -v 'pre-release') echo "$output" set -e test -z "$output" -a "$failed" -eq 0 +} + +echo "Compiling various other contracts and libraries..." +( +cd "$REPO_ROOT"/test/compilationTests/ +for dir in * +do + if [ "$dir" != "README.md" ] + then + echo " - $dir" + cd "$dir" + compileFull *.sol */*.sol + cd .. + fi +done +) + +echo "Compiling all files in std and examples..." + +for f in "$REPO_ROOT"/std/*.sol +do + echo "$f" + compileWithoutWarning "$f" done +echo "Compiling all examples from the documentation..." +TMPDIR=$(mktemp -d) +( + set -e + cd "$REPO_ROOT" + REPO_ROOT=$(pwd) # make it absolute + cd "$TMPDIR" + "$REPO_ROOT"/scripts/isolate_tests.py "$REPO_ROOT"/docs/ docs + for f in *.sol + do + echo "$f" + compileFull "$TMPDIR/$f" + done +) +rm -rf "$TMPDIR" +echo "Done." + echo "Testing library checksum..." echo '' | "$SOLC" --link --libraries a:0x90f20564390eAe531E810af625A22f51385Cd222 ! echo '' | "$SOLC" --link --libraries a:0x80f20564390eAe531E810af625A22f51385Cd222 2>/dev/null @@ -77,6 +137,7 @@ TMPDIR=$(mktemp -d) REPO_ROOT=$(pwd) # make it absolute cd "$TMPDIR" "$REPO_ROOT"/scripts/isolate_tests.py "$REPO_ROOT"/test/ + "$REPO_ROOT"/scripts/isolate_tests.py "$REPO_ROOT"/docs/ docs for f in *.sol do set +e diff --git a/test/compilationTests/MultiSigWallet/Factory.sol b/test/compilationTests/MultiSigWallet/Factory.sol new file mode 100644 index 00000000..f1be6884 --- /dev/null +++ b/test/compilationTests/MultiSigWallet/Factory.sol @@ -0,0 +1,28 @@ +contract Factory { + + event ContractInstantiation(address sender, address instantiation); + + mapping(address => bool) public isInstantiation; + mapping(address => address[]) public instantiations; + + /// @dev Returns number of instantiations by creator. + /// @param creator Contract creator. + /// @return Returns number of instantiations by creator. + function getInstantiationCount(address creator) + public + constant + returns (uint) + { + return instantiations[creator].length; + } + + /// @dev Registers contract in factory registry. + /// @param instantiation Address of contract instantiation. + function register(address instantiation) + internal + { + isInstantiation[instantiation] = true; + instantiations[msg.sender].push(instantiation); + ContractInstantiation(msg.sender, instantiation); + } +} diff --git a/test/compilationTests/MultiSigWallet/LICENSE b/test/compilationTests/MultiSigWallet/LICENSE new file mode 100644 index 00000000..94a9ed02 --- /dev/null +++ b/test/compilationTests/MultiSigWallet/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + <one line to give the program's name and a brief idea of what it does.> + Copyright (C) <year> <name of author> + + This program 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. + + This program 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 this program. If not, see <http://www.gnu.org/licenses/>. + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + <program> Copyright (C) <year> <name of author> + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +<http://www.gnu.org/licenses/>. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +<http://www.gnu.org/philosophy/why-not-lgpl.html>. diff --git a/test/compilationTests/MultiSigWallet/MultiSigWallet.sol b/test/compilationTests/MultiSigWallet/MultiSigWallet.sol new file mode 100644 index 00000000..a6f67c7a --- /dev/null +++ b/test/compilationTests/MultiSigWallet/MultiSigWallet.sol @@ -0,0 +1,366 @@ +pragma solidity ^0.4.4; + + +/// @title Multisignature wallet - Allows multiple parties to agree on transactions before execution. +/// @author Stefan George - <stefan.george@consensys.net> +contract MultiSigWallet { + + uint constant public MAX_OWNER_COUNT = 50; + + event Confirmation(address indexed sender, uint indexed transactionId); + event Revocation(address indexed sender, uint indexed transactionId); + event Submission(uint indexed transactionId); + event Execution(uint indexed transactionId); + event ExecutionFailure(uint indexed transactionId); + event Deposit(address indexed sender, uint value); + event OwnerAddition(address indexed owner); + event OwnerRemoval(address indexed owner); + event RequirementChange(uint required); + + mapping (uint => Transaction) public transactions; + mapping (uint => mapping (address => bool)) public confirmations; + mapping (address => bool) public isOwner; + address[] public owners; + uint public required; + uint public transactionCount; + + struct Transaction { + address destination; + uint value; + bytes data; + bool executed; + } + + modifier onlyWallet() { + if (msg.sender != address(this)) + throw; + _; + } + + modifier ownerDoesNotExist(address owner) { + if (isOwner[owner]) + throw; + _; + } + + modifier ownerExists(address owner) { + if (!isOwner[owner]) + throw; + _; + } + + modifier transactionExists(uint transactionId) { + if (transactions[transactionId].destination == 0) + throw; + _; + } + + modifier confirmed(uint transactionId, address owner) { + if (!confirmations[transactionId][owner]) + throw; + _; + } + + modifier notConfirmed(uint transactionId, address owner) { + if (confirmations[transactionId][owner]) + throw; + _; + } + + modifier notExecuted(uint transactionId) { + if (transactions[transactionId].executed) + throw; + _; + } + + modifier notNull(address _address) { + if (_address == 0) + throw; + _; + } + + modifier validRequirement(uint ownerCount, uint _required) { + if ( ownerCount > MAX_OWNER_COUNT + || _required > ownerCount + || _required == 0 + || ownerCount == 0) + throw; + _; + } + + /// @dev Fallback function allows to deposit ether. + function() + payable + { + if (msg.value > 0) + Deposit(msg.sender, msg.value); + } + + /* + * Public functions + */ + /// @dev Contract constructor sets initial owners and required number of confirmations. + /// @param _owners List of initial owners. + /// @param _required Number of required confirmations. + function MultiSigWallet(address[] _owners, uint _required) + public + validRequirement(_owners.length, _required) + { + for (uint i=0; i<_owners.length; i++) { + if (isOwner[_owners[i]] || _owners[i] == 0) + throw; + isOwner[_owners[i]] = true; + } + owners = _owners; + required = _required; + } + + /// @dev Allows to add a new owner. Transaction has to be sent by wallet. + /// @param owner Address of new owner. + function addOwner(address owner) + public + onlyWallet + ownerDoesNotExist(owner) + notNull(owner) + validRequirement(owners.length + 1, required) + { + isOwner[owner] = true; + owners.push(owner); + OwnerAddition(owner); + } + + /// @dev Allows to remove an owner. Transaction has to be sent by wallet. + /// @param owner Address of owner. + function removeOwner(address owner) + public + onlyWallet + ownerExists(owner) + { + isOwner[owner] = false; + for (uint i=0; i<owners.length - 1; i++) + if (owners[i] == owner) { + owners[i] = owners[owners.length - 1]; + break; + } + owners.length -= 1; + if (required > owners.length) + changeRequirement(owners.length); + OwnerRemoval(owner); + } + + /// @dev Allows to replace an owner with a new owner. Transaction has to be sent by wallet. + /// @param owner Address of owner to be replaced. + /// @param owner Address of new owner. + function replaceOwner(address owner, address newOwner) + public + onlyWallet + ownerExists(owner) + ownerDoesNotExist(newOwner) + { + for (uint i=0; i<owners.length; i++) + if (owners[i] == owner) { + owners[i] = newOwner; + break; + } + isOwner[owner] = false; + isOwner[newOwner] = true; + OwnerRemoval(owner); + OwnerAddition(newOwner); + } + + /// @dev Allows to change the number of required confirmations. Transaction has to be sent by wallet. + /// @param _required Number of required confirmations. + function changeRequirement(uint _required) + public + onlyWallet + validRequirement(owners.length, _required) + { + required = _required; + RequirementChange(_required); + } + + /// @dev Allows an owner to submit and confirm a transaction. + /// @param destination Transaction target address. + /// @param value Transaction ether value. + /// @param data Transaction data payload. + /// @return Returns transaction ID. + function submitTransaction(address destination, uint value, bytes data) + public + returns (uint transactionId) + { + transactionId = addTransaction(destination, value, data); + confirmTransaction(transactionId); + } + + /// @dev Allows an owner to confirm a transaction. + /// @param transactionId Transaction ID. + function confirmTransaction(uint transactionId) + public + ownerExists(msg.sender) + transactionExists(transactionId) + notConfirmed(transactionId, msg.sender) + { + confirmations[transactionId][msg.sender] = true; + Confirmation(msg.sender, transactionId); + executeTransaction(transactionId); + } + + /// @dev Allows an owner to revoke a confirmation for a transaction. + /// @param transactionId Transaction ID. + function revokeConfirmation(uint transactionId) + public + ownerExists(msg.sender) + confirmed(transactionId, msg.sender) + notExecuted(transactionId) + { + confirmations[transactionId][msg.sender] = false; + Revocation(msg.sender, transactionId); + } + + /// @dev Allows anyone to execute a confirmed transaction. + /// @param transactionId Transaction ID. + function executeTransaction(uint transactionId) + public + notExecuted(transactionId) + { + if (isConfirmed(transactionId)) { + Transaction tx = transactions[transactionId]; + tx.executed = true; + if (tx.destination.call.value(tx.value)(tx.data)) + Execution(transactionId); + else { + ExecutionFailure(transactionId); + tx.executed = false; + } + } + } + + /// @dev Returns the confirmation status of a transaction. + /// @param transactionId Transaction ID. + /// @return Confirmation status. + function isConfirmed(uint transactionId) + public + constant + returns (bool) + { + uint count = 0; + for (uint i=0; i<owners.length; i++) { + if (confirmations[transactionId][owners[i]]) + count += 1; + if (count == required) + return true; + } + } + + /* + * Internal functions + */ + /// @dev Adds a new transaction to the transaction mapping, if transaction does not exist yet. + /// @param destination Transaction target address. + /// @param value Transaction ether value. + /// @param data Transaction data payload. + /// @return Returns transaction ID. + function addTransaction(address destination, uint value, bytes data) + internal + notNull(destination) + returns (uint transactionId) + { + transactionId = transactionCount; + transactions[transactionId] = Transaction({ + destination: destination, + value: value, + data: data, + executed: false + }); + transactionCount += 1; + Submission(transactionId); + } + + /* + * Web3 call functions + */ + /// @dev Returns number of confirmations of a transaction. + /// @param transactionId Transaction ID. + /// @return Number of confirmations. + function getConfirmationCount(uint transactionId) + public + constant + returns (uint count) + { + for (uint i=0; i<owners.length; i++) + if (confirmations[transactionId][owners[i]]) + count += 1; + } + + /// @dev Returns total number of transactions after filers are applied. + /// @param pending Include pending transactions. + /// @param executed Include executed transactions. + /// @return Total number of transactions after filters are applied. + function getTransactionCount(bool pending, bool executed) + public + constant + returns (uint count) + { + for (uint i=0; i<transactionCount; i++) + if ( pending && !transactions[i].executed + || executed && transactions[i].executed) + count += 1; + } + + /// @dev Returns list of owners. + /// @return List of owner addresses. + function getOwners() + public + constant + returns (address[]) + { + return owners; + } + + /// @dev Returns array with owner addresses, which confirmed transaction. + /// @param transactionId Transaction ID. + /// @return Returns array of owner addresses. + function getConfirmations(uint transactionId) + public + constant + returns (address[] _confirmations) + { + address[] memory confirmationsTemp = new address[](owners.length); + uint count = 0; + uint i; + for (i=0; i<owners.length; i++) + if (confirmations[transactionId][owners[i]]) { + confirmationsTemp[count] = owners[i]; + count += 1; + } + _confirmations = new address[](count); + for (i=0; i<count; i++) + _confirmations[i] = confirmationsTemp[i]; + } + + /// @dev Returns list of transaction IDs in defined range. + /// @param from Index start position of transaction array. + /// @param to Index end position of transaction array. + /// @param pending Include pending transactions. + /// @param executed Include executed transactions. + /// @return Returns array of transaction IDs. + function getTransactionIds(uint from, uint to, bool pending, bool executed) + public + constant + returns (uint[] _transactionIds) + { + uint[] memory transactionIdsTemp = new uint[](transactionCount); + uint count = 0; + uint i; + for (i=0; i<transactionCount; i++) + if ( pending && !transactions[i].executed + || executed && transactions[i].executed) + { + transactionIdsTemp[count] = i; + count += 1; + } + _transactionIds = new uint[](to - from); + for (i=from; i<to; i++) + _transactionIds[i - from] = transactionIdsTemp[i]; + } +} diff --git a/test/compilationTests/MultiSigWallet/MultiSigWalletFactory.sol b/test/compilationTests/MultiSigWallet/MultiSigWalletFactory.sol new file mode 100644 index 00000000..cb58ab1c --- /dev/null +++ b/test/compilationTests/MultiSigWallet/MultiSigWalletFactory.sol @@ -0,0 +1,21 @@ +pragma solidity ^0.4.4; +import "Factory.sol"; +import "MultiSigWallet.sol"; + + +/// @title Multisignature wallet factory - Allows creation of multisig wallet. +/// @author Stefan George - <stefan.george@consensys.net> +contract MultiSigWalletFactory is Factory { + + /// @dev Allows verified creation of multisignature wallet. + /// @param _owners List of initial owners. + /// @param _required Number of required confirmations. + /// @return Returns wallet address. + function create(address[] _owners, uint _required) + public + returns (address wallet) + { + wallet = new MultiSigWallet(_owners, _required); + register(wallet); + } +} diff --git a/test/compilationTests/MultiSigWallet/MultiSigWalletWithDailyLimit.sol b/test/compilationTests/MultiSigWallet/MultiSigWalletWithDailyLimit.sol new file mode 100644 index 00000000..024d3ef4 --- /dev/null +++ b/test/compilationTests/MultiSigWallet/MultiSigWalletWithDailyLimit.sol @@ -0,0 +1,97 @@ +pragma solidity ^0.4.4; +import "MultiSigWallet.sol"; + + +/// @title Multisignature wallet with daily limit - Allows an owner to withdraw a daily limit without multisig. +/// @author Stefan George - <stefan.george@consensys.net> +contract MultiSigWalletWithDailyLimit is MultiSigWallet { + + event DailyLimitChange(uint dailyLimit); + + uint public dailyLimit; + uint public lastDay; + uint public spentToday; + + /* + * Public functions + */ + /// @dev Contract constructor sets initial owners, required number of confirmations and daily withdraw limit. + /// @param _owners List of initial owners. + /// @param _required Number of required confirmations. + /// @param _dailyLimit Amount in wei, which can be withdrawn without confirmations on a daily basis. + function MultiSigWalletWithDailyLimit(address[] _owners, uint _required, uint _dailyLimit) + public + MultiSigWallet(_owners, _required) + { + dailyLimit = _dailyLimit; + } + + /// @dev Allows to change the daily limit. Transaction has to be sent by wallet. + /// @param _dailyLimit Amount in wei. + function changeDailyLimit(uint _dailyLimit) + public + onlyWallet + { + dailyLimit = _dailyLimit; + DailyLimitChange(_dailyLimit); + } + + /// @dev Allows anyone to execute a confirmed transaction or ether withdraws until daily limit is reached. + /// @param transactionId Transaction ID. + function executeTransaction(uint transactionId) + public + notExecuted(transactionId) + { + Transaction tx = transactions[transactionId]; + bool confirmed = isConfirmed(transactionId); + if (confirmed || tx.data.length == 0 && isUnderLimit(tx.value)) { + tx.executed = true; + if (!confirmed) + spentToday += tx.value; + if (tx.destination.call.value(tx.value)(tx.data)) + Execution(transactionId); + else { + ExecutionFailure(transactionId); + tx.executed = false; + if (!confirmed) + spentToday -= tx.value; + } + } + } + + /* + * Internal functions + */ + /// @dev Returns if amount is within daily limit and resets spentToday after one day. + /// @param amount Amount to withdraw. + /// @return Returns if amount is under daily limit. + function isUnderLimit(uint amount) + internal + returns (bool) + { + if (now > lastDay + 24 hours) { + lastDay = now; + spentToday = 0; + } + if (spentToday + amount > dailyLimit || spentToday + amount < spentToday) + return false; + return true; + } + + /* + * Web3 call functions + */ + /// @dev Returns maximum withdraw amount. + /// @return Returns amount. + function calcMaxWithdraw() + public + constant + returns (uint) + { + if (now > lastDay + 24 hours) + return dailyLimit; + if (dailyLimit < spentToday) + return 0; + return dailyLimit - spentToday; + } +} diff --git a/test/compilationTests/MultiSigWallet/MultiSigWalletWithDailyLimitFactory.sol b/test/compilationTests/MultiSigWallet/MultiSigWalletWithDailyLimitFactory.sol new file mode 100644 index 00000000..8a2efa32 --- /dev/null +++ b/test/compilationTests/MultiSigWallet/MultiSigWalletWithDailyLimitFactory.sol @@ -0,0 +1,22 @@ +pragma solidity ^0.4.4; +import "Factory.sol"; +import "MultiSigWalletWithDailyLimit.sol"; + + +/// @title Multisignature wallet factory for daily limit version - Allows creation of multisig wallet. +/// @author Stefan George - <stefan.george@consensys.net> +contract MultiSigWalletWithDailyLimitFactory is Factory { + + /// @dev Allows verified creation of multisignature wallet. + /// @param _owners List of initial owners. + /// @param _required Number of required confirmations. + /// @param _dailyLimit Amount in wei, which can be withdrawn without confirmations on a daily basis. + /// @return Returns wallet address. + function create(address[] _owners, uint _required, uint _dailyLimit) + public + returns (address wallet) + { + wallet = new MultiSigWalletWithDailyLimit(_owners, _required, _dailyLimit); + register(wallet); + } +} diff --git a/test/compilationTests/MultiSigWallet/README.md b/test/compilationTests/MultiSigWallet/README.md new file mode 100644 index 00000000..2d96f3a1 --- /dev/null +++ b/test/compilationTests/MultiSigWallet/README.md @@ -0,0 +1,3 @@ +MultiSigWallet contracts, originally from + +https://github.com/ConsenSys/MultiSigWallet diff --git a/test/compilationTests/MultiSigWallet/TestToken.sol b/test/compilationTests/MultiSigWallet/TestToken.sol new file mode 100644 index 00000000..0f6cd20e --- /dev/null +++ b/test/compilationTests/MultiSigWallet/TestToken.sol @@ -0,0 +1,76 @@ +pragma solidity ^0.4.4; + + +/// @title Test token contract - Allows testing of token transfers with multisig wallet. +contract TestToken { + + event Transfer(address indexed from, address indexed to, uint256 value); + event Approval(address indexed owner, address indexed spender, uint256 value); + + mapping (address => uint256) balances; + mapping (address => mapping (address => uint256)) allowed; + uint256 public totalSupply; + + string constant public name = "Test Token"; + string constant public symbol = "TT"; + uint8 constant public decimals = 1; + + function issueTokens(address _to, uint256 _value) + public + { + balances[_to] += _value; + totalSupply += _value; + } + + function transfer(address _to, uint256 _value) + public + returns (bool success) + { + if (balances[msg.sender] < _value) { + throw; + } + balances[msg.sender] -= _value; + balances[_to] += _value; + Transfer(msg.sender, _to, _value); + return true; + } + + function transferFrom(address _from, address _to, uint256 _value) + public + returns (bool success) + { + if (balances[_from] < _value || allowed[_from][msg.sender] < _value) { + throw; + } + balances[_to] += _value; + balances[_from] -= _value; + allowed[_from][msg.sender] -= _value; + Transfer(_from, _to, _value); + return true; + } + + function approve(address _spender, uint256 _value) + public + returns (bool success) + { + allowed[msg.sender][_spender] = _value; + Approval(msg.sender, _spender, _value); + return true; + } + + function allowance(address _owner, address _spender) + constant + public + returns (uint256 remaining) + { + return allowed[_owner][_spender]; + } + + function balanceOf(address _owner) + constant + public + returns (uint256 balance) + { + return balances[_owner]; + } +} diff --git a/test/compilationTests/README.md b/test/compilationTests/README.md new file mode 100644 index 00000000..c827b348 --- /dev/null +++ b/test/compilationTests/README.md @@ -0,0 +1,5 @@ +This directory contains various Solidity contract source code files +that are compiled as part of the regular tests. + +These contracts are externally contributed and their presence in this +repository does not make any statement about their quality or usefulness. diff --git a/test/compilationTests/corion/LICENSE b/test/compilationTests/corion/LICENSE new file mode 100644 index 00000000..9cecc1d4 --- /dev/null +++ b/test/compilationTests/corion/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + {one line to give the program's name and a brief idea of what it does.} + Copyright (C) {year} {name of author} + + This program 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. + + This program 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 this program. If not, see <http://www.gnu.org/licenses/>. + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + {project} Copyright (C) {year} {fullname} + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +<http://www.gnu.org/licenses/>. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +<http://www.gnu.org/philosophy/why-not-lgpl.html>. diff --git a/test/compilationTests/corion/README.md b/test/compilationTests/corion/README.md new file mode 100644 index 00000000..f0bb8ea8 --- /dev/null +++ b/test/compilationTests/corion/README.md @@ -0,0 +1,3 @@ +CORION contracts, originally from + +https://github.com/CORIONplatform/solidity diff --git a/test/compilationTests/corion/announcementTypes.sol b/test/compilationTests/corion/announcementTypes.sol new file mode 100644 index 00000000..f31d580e --- /dev/null +++ b/test/compilationTests/corion/announcementTypes.sol @@ -0,0 +1,35 @@ +pragma solidity ^0.4.11;
+
+contract announcementTypes {
+
+ enum announcementType {
+ /*
+ type of announcements
+ */
+ newModule,
+ dropModule,
+ replaceModule,
+ replaceModuleHandler,
+ question,
+ transactionFeeRate,
+ transactionFeeMin,
+ transactionFeeMax,
+ transactionFeeBurn,
+ providerPublicFunds,
+ providerPrivateFunds,
+ providerPrivateClientLimit,
+ providerPublicMinRate,
+ providerPublicMaxRate,
+ providerPrivateMinRate,
+ providerPrivateMaxRate,
+ providerGasProtect,
+ providerInterestMinFunds,
+ providerRentRate,
+ schellingRoundBlockDelay,
+ schellingCheckRounds,
+ schellingCheckAboves,
+ schellingRate,
+ publisherMinAnnouncementDelay,
+ publisherOppositeRate
+ }
+}
\ No newline at end of file diff --git a/test/compilationTests/corion/ico.sol b/test/compilationTests/corion/ico.sol new file mode 100644 index 00000000..6c9f8cb2 --- /dev/null +++ b/test/compilationTests/corion/ico.sol @@ -0,0 +1,376 @@ +pragma solidity ^0.4.11; + +import "./safeMath.sol"; +import "./token.sol"; +import "./premium.sol"; +import "./moduleHandler.sol"; + +contract ico is safeMath { + + struct icoLevels_s { + uint256 block; + uint8 rate; + } + struct affiliate_s { + uint256 weight; + uint256 paid; + } + struct interest_s { + uint256 amount; + bool empty; + } + struct brought_s { + uint256 eth; + uint256 cor; + uint256 corp; + } + + uint256 constant oneSegment = 40320; + + address public owner; + address public tokenAddr; + address public premiumAddr; + uint256 public startBlock; + uint256 public icoDelay; + address public foundationAddress; + address public icoEtcPriceAddr; + uint256 public icoExchangeRate; + uint256 public icoExchangeRateSetBlock; + uint256 constant icoExchangeRateM = 1e4; + uint256 constant interestOnICO = 25; + uint256 constant interestOnICOM = 1e3; + uint256 constant interestBlockDelay = 720; + uint256 constant exchangeRateDelay = 125; + bool public aborted; + bool public closed; + icoLevels_s[] public icoLevels; + mapping (address => affiliate_s) public affiliate; + mapping (address => brought_s) public brought; + mapping (address => mapping(uint256 => interest_s)) public interestDB; + uint256 public totalMint; + uint256 public totalPremiumMint; + + function ico(address foundation, address priceSet, uint256 exchangeRate, uint256 startBlockNum, address[] genesisAddr, uint256[] genesisValue) { + /* + Installation function. + + @foundation The ETC address of the foundation + @priceSet The address which will be able to make changes on the rate later on. + @exchangeRate The current ETC/USD rate multiplied by 1e4. For example: 2.5 USD/ETC = 25000 + @startBlockNum The height (level) of the beginning of the ICO. If it is 0 then it will be the current array’s height. + @genesisAddr Array of Genesis addresses + @genesisValue Array of balance of genesis addresses + */ + foundationAddress = foundation; + icoExchangeRate = exchangeRate; + icoExchangeRateSetBlock = block.number + exchangeRateDelay; + icoEtcPriceAddr = priceSet; + owner = msg.sender; + if ( startBlockNum > 0 ) { + require( startBlockNum >= block.number ); + startBlock = startBlockNum; + } else { + startBlock = block.number; + } + icoLevels.push(icoLevels_s(startBlock + oneSegment * 1, 3)); + icoLevels.push(icoLevels_s(startBlock + oneSegment / 7, 5)); + icoLevels.push(icoLevels_s(startBlock, 10)); + icoDelay = startBlock + oneSegment * 3; + for ( uint256 a=0 ; a<genesisAddr.length ; a++ ) { + interestDB[genesisAddr[a]][0].amount = genesisValue[a]; + } + } + + function ICObonus() public constant returns(uint256 bonus) { + /* + Query of current bonus + + @bonus Bonus % + */ + for ( uint8 a=0 ; a<icoLevels.length ; a++ ) { + if ( block.number > icoLevels[a].block ) { + return icoLevels[a].rate; + } + } + } + + function setInterestDB(address addr, uint256 balance) external returns(bool success) { + /* + Setting interest database. It can be requested by Token contract only. + A database has to be built in order that after ICO closed everybody can get their compound interest on their capital accumulated + + @addr Sender + @balance Quantity + + @success Was the process successful or not + */ + require( msg.sender == tokenAddr ); + uint256 _num = (block.number - startBlock) / interestBlockDelay; + interestDB[addr][_num].amount = balance; + if ( balance == 0 ) { + interestDB[addr][_num].empty = true; + } + return true; + } + + function checkInterest(address addr) public constant returns(uint256 amount) { + /* + Query of compound interest + + @addr Address + + @amount Amount of compound interest + */ + uint256 _lastBal; + uint256 _tamount; + bool _empty; + interest_s memory _idb; + uint256 _to = (block.number - startBlock) / interestBlockDelay; + + if ( _to == 0 || aborted ) { return 0; } + + for ( uint256 r=0 ; r < _to ; r++ ) { + if ( r*interestBlockDelay+startBlock >= icoDelay ) { break; } + _idb = interestDB[addr][r]; + if ( _idb.amount > 0 ) { + if ( _empty ) { + _lastBal = _idb.amount + amount; + } else { + _lastBal = _idb.amount; + } + } + if ( _idb.empty ) { + _lastBal = 0; + _empty = _idb.empty; + } + _lastBal += _tamount; + _tamount = _lastBal * interestOnICO / interestOnICOM / 100; + amount += _tamount; + } + } + + function getInterest(address beneficiary) external { + /* + Request of compound interest. This is deleted from the database after the ICO closed and following the query of the compound interest. + + @beneficiary Beneficiary who will receive the interest + */ + uint256 _lastBal; + uint256 _tamount; + uint256 _amount; + bool _empty; + interest_s memory _idb; + address _addr = beneficiary; + uint256 _to = (block.number - startBlock) / interestBlockDelay; + if ( _addr == 0x00 ) { _addr = msg.sender; } + + require( block.number > icoDelay ); + require( ! aborted ); + + for ( uint256 r=0 ; r < _to ; r++ ) { + if ( r*interestBlockDelay+startBlock >= icoDelay ) { break; } + _idb = interestDB[msg.sender][r]; + if ( _idb.amount > 0 ) { + if ( _empty ) { + _lastBal = _idb.amount + _amount; + } else { + _lastBal = _idb.amount; + } + } + if ( _idb.empty ) { + _lastBal = 0; + _empty = _idb.empty; + } + _lastBal += _tamount; + _tamount = _lastBal * interestOnICO / interestOnICOM / 100; + _amount += _tamount; + delete interestDB[msg.sender][r]; + } + + require( _amount > 0 ); + token(tokenAddr).mint(_addr, _amount); + } + + function setICOEthPrice(uint256 value) external { + /* + Setting of the ICO ETC USD rates which can only be calle by a pre-defined address. + After this function is completed till the call of the next function (which is at least an exchangeRateDelay array) this rate counts. + With this process avoiding the sudden rate changes. + + @value The ETC/USD rate multiplied by 1e4. For example: 2.5 USD/ETC = 25000 + */ + require( isICO() ); + require( icoEtcPriceAddr == msg.sender ); + require( icoExchangeRateSetBlock < block.number); + icoExchangeRateSetBlock = block.number + exchangeRateDelay; + icoExchangeRate = value; + } + + function extendICO() external { + /* + Extend the period of the ICO with one segment. + + It is only possible during the ICO and only callable by the owner. + */ + require( isICO() ); + require( msg.sender == owner ); + icoDelay += oneSegment; + } + + function closeICO() external { + /* + Closing the ICO. + It is only possible when the ICO period passed and only by the owner. + The 96% of the whole amount of the token is generated to the address of the fundation. + Ethers which are situated in this contract will be sent to the address of the fundation. + */ + require( msg.sender == owner ); + require( block.number > icoDelay ); + require( ! closed ); + closed = true; + require( ! aborted ); + require( token(tokenAddr).mint(foundationAddress, token(tokenAddr).totalSupply() * 96 / 100) ); + require( premium(premiumAddr).mint(foundationAddress, totalMint / 5000 - totalPremiumMint) ); + require( foundationAddress.send(this.balance) ); + require( token(tokenAddr).closeIco() ); + require( premium(premiumAddr).closeIco() ); + } + + function abortICO() external { + /* + Withdrawal of the ICO. + It is only possible during the ICO period. + Only callable by the owner. + After this process only the receiveFunds function will be available for the customers. + */ + require( isICO() ); + require( msg.sender == owner ); + aborted = true; + } + + function connectTokens(address tokenContractAddr, address premiumContractAddr) external { + /* + Installation function which joins the two token contracts with this contract. + Only callable by the owner + + @tokenContractAddr Address of the corion token contract. + @premiumContractAddr Address of the corion premium token contract + */ + require( msg.sender == owner ); + require( tokenAddr == 0x00 && premiumAddr == 0x00 ); + tokenAddr = tokenContractAddr; + premiumAddr = premiumContractAddr; + } + + function receiveFunds() external { + /* + Refund the amount which was purchased during the ICO period. + This one is only callable if the ICO is withdrawn. + In this case the address gets back the 90% of the amount which was spent for token during the ICO period. + */ + require( aborted ); + require( brought[msg.sender].eth > 0 ); + uint256 _val = brought[msg.sender].eth * 90 / 100; + delete brought[msg.sender]; + require( msg.sender.send(_val) ); + } + + function () payable { + /* + Callback function. Simply calls the buy function as a beneficiary and there is no affilate address. + If they call the contract without any function then this process will be taken place. + */ + require( isICO() ); + require( buy(msg.sender, 0x00) ); + } + + function buy(address beneficiaryAddress, address affilateAddress) payable returns (bool success) { + /* + Buying a token + + If there is not at least 0.2 ether balance on the beneficiaryAddress then the amount of the ether which was intended for the purchase will be reduced by 0.2 and that will be sent to the address of the beneficiary. + From the remaining amount calculate the reward with the help of the getIcoReward function. + Only that affilate address is valid which has some token on it’s account. + If there is a valid affilate address then calculate and credit the reward as well in the following way: + With more than 1e12 token contract credit 5% reward based on the calculation that how many tokens did they buy when he was added as an affilate. + More than 1e11 token: 4% + More than 1e10 token: 3% + More than 1e9 token: 2% below 1% + @beneficiaryAddress The address of the accredited where the token will be sent. + @affilateAddress The address of the person who offered who will get the referral reward. It can not be equal with the beneficiaryAddress. + */ + require( isICO() ); + if ( beneficiaryAddress == 0x00) { beneficiaryAddress = msg.sender; } + if ( beneficiaryAddress == affilateAddress ) { + affilateAddress = 0x00; + } + uint256 _value = msg.value; + if ( beneficiaryAddress.balance < 0.2 ether ) { + require( beneficiaryAddress.send(0.2 ether) ); + _value = safeSub(_value, 0.2 ether); + } + var _reward = getIcoReward(_value); + require( _reward > 0 ); + require( token(tokenAddr).mint(beneficiaryAddress, _reward) ); + brought[beneficiaryAddress].eth = safeAdd(brought[beneficiaryAddress].eth, _value); + brought[beneficiaryAddress].cor = safeAdd(brought[beneficiaryAddress].cor, _reward); + totalMint = safeAdd(totalMint, _reward); + require( foundationAddress.send(_value * 10 / 100) ); + uint256 extra; + if ( affilateAddress != 0x00 && ( brought[affilateAddress].eth > 0 || interestDB[affilateAddress][0].amount > 0 ) ) { + affiliate[affilateAddress].weight = safeAdd(affiliate[affilateAddress].weight, _reward); + extra = affiliate[affilateAddress].weight; + uint256 rate; + if (extra >= 1e12) { + rate = 5; + } else if (extra >= 1e11) { + rate = 4; + } else if (extra >= 1e10) { + rate = 3; + } else if (extra >= 1e9) { + rate = 2; + } else { + rate = 1; + } + extra = safeSub(extra * rate / 100, affiliate[affilateAddress].paid); + affiliate[affilateAddress].paid = safeAdd(affiliate[affilateAddress].paid, extra); + token(tokenAddr).mint(affilateAddress, extra); + } + checkPremium(beneficiaryAddress); + EICO(beneficiaryAddress, _reward, affilateAddress, extra); + return true; + } + + function checkPremium(address owner) internal { + /* + Crediting the premium token + + @owner The corion token balance of this address will be set based on the calculation which shows that how many times can be the amount of the purchased tokens devided by 5000. So after each 5000 token we give 1 premium token. + */ + uint256 _reward = (brought[owner].cor / 5e9) - brought[owner].corp; + if ( _reward > 0 ) { + require( premium(premiumAddr).mint(owner, _reward) ); + brought[owner].corp = safeAdd(brought[owner].corp, _reward); + totalPremiumMint = safeAdd(totalPremiumMint, _reward); + } + } + + function getIcoReward(uint256 value) public constant returns (uint256 reward) { + /* + Expected token volume at token purchase + + @value The amount of ether for the purchase + @reward Amount of the token + x = (value * 1e6 * USD_ETC_exchange rate / 1e4 / 1e18) * bonus percentage + 2.700000 token = (1e18 * 1e6 * 22500 / 1e4 / 1e18) * 1.20 + */ + reward = (value * 1e6 * icoExchangeRate / icoExchangeRateM / 1 ether) * (ICObonus() + 100) / 100; + if ( reward < 5e6) { return 0; } + } + + function isICO() public constant returns (bool success) { + return startBlock <= block.number && block.number <= icoDelay && ( ! aborted ) && ( ! closed ); + } + + event EICO(address indexed Address, uint256 indexed value, address Affilate, uint256 AffilateValue); +} diff --git a/test/compilationTests/corion/module.sol b/test/compilationTests/corion/module.sol new file mode 100644 index 00000000..d64044cb --- /dev/null +++ b/test/compilationTests/corion/module.sol @@ -0,0 +1,143 @@ +pragma solidity ^0.4.11; + +contract abstractModuleHandler { + function transfer(address from, address to, uint256 value, bool fee) external returns (bool success) {} + function balanceOf(address owner) public constant returns (bool success, uint256 value) {} +} + +contract module { + /* + Module + */ + + enum status { + New, + Connected, + Disconnected, + Disabled + } + + status public moduleStatus; + uint256 public disabledUntil; + address public moduleHandlerAddress; + + function disableModule(bool forever) external onlyForModuleHandler returns (bool success) { + _disableModule(forever); + return true; + } + function _disableModule(bool forever) internal { + /* + Disable the module for one week, if the forever true then for forever. + This function calls the Publisher module. + + @forever For forever or not + */ + if ( forever ) { moduleStatus = status.Disabled; } + else { disabledUntil = block.number + 5760; } + } + + function replaceModuleHandler(address newModuleHandlerAddress) external onlyForModuleHandler returns (bool success) { + _replaceModuleHandler(newModuleHandlerAddress); + return true; + } + function _replaceModuleHandler(address newModuleHandlerAddress) internal { + /* + Replace the ModuleHandler address. + This function calls the Publisher module. + + @newModuleHandlerAddress New module handler address + */ + require( moduleStatus == status.Connected ); + moduleHandlerAddress = newModuleHandlerAddress; + } + + function connectModule() external onlyForModuleHandler returns (bool success) { + _connectModule(); + return true; + } + function _connectModule() internal { + /* + Registering and/or connecting-to ModuleHandler. + This function is called by ModuleHandler load or by Publisher. + */ + require( moduleStatus == status.New ); + moduleStatus = status.Connected; + } + + function disconnectModule() external onlyForModuleHandler returns (bool success) { + _disconnectModule(); + return true; + } + function _disconnectModule() internal { + /* + Disconnect the module from the ModuleHandler. + This function calls the Publisher module. + */ + require( moduleStatus != status.New && moduleStatus != status.Disconnected ); + moduleStatus = status.Disconnected; + } + + function replaceModule(address newModuleAddress) external onlyForModuleHandler returns (bool success) { + _replaceModule(newModuleAddress); + return true; + } + function _replaceModule(address newModuleAddress) internal { + /* + Replace the module for an another new module. + This function calls the Publisher module. + We send every Token and ether to the new module. + + @newModuleAddress New module handler address + */ + require( moduleStatus != status.New && moduleStatus != status.Disconnected); + var (_success, _balance) = abstractModuleHandler(moduleHandlerAddress).balanceOf(address(this)); + require( _success ); + if ( _balance > 0 ) { + require( abstractModuleHandler(moduleHandlerAddress).transfer(address(this), newModuleAddress, _balance, false) ); + } + if ( this.balance > 0 ) { + require( newModuleAddress.send(this.balance) ); + } + moduleStatus = status.Disconnected; + } + + function transferEvent(address from, address to, uint256 value) external onlyForModuleHandler returns (bool success) { + return true; + } + function newSchellingRoundEvent(uint256 roundID, uint256 reward) external onlyForModuleHandler returns (bool success) { + return true; + } + + function registerModuleHandler(address _moduleHandlerAddress) internal { + /* + Module constructor function for registering ModuleHandler address. + */ + moduleHandlerAddress = _moduleHandlerAddress; + } + function isModuleHandler(address addr) internal returns (bool ret) { + /* + Test for ModuleHandler address. + If the module is not connected then returns always false. + + @addr Address to check + + @ret This is the module handler address or not + */ + if ( moduleHandlerAddress == 0x00 ) { return true; } + if ( moduleStatus != status.Connected ) { return false; } + return addr == moduleHandlerAddress; + } + function isActive() public constant returns (bool success, bool active) { + /* + Check self for ready for functions or not. + + @success Function call was successfull or not + @active Ready for functions or not + */ + return (true, moduleStatus == status.Connected && block.number >= disabledUntil); + } + modifier onlyForModuleHandler() { + require( msg.sender == moduleHandlerAddress ); + _; + } +} diff --git a/test/compilationTests/corion/moduleHandler.sol b/test/compilationTests/corion/moduleHandler.sol new file mode 100644 index 00000000..682f81dd --- /dev/null +++ b/test/compilationTests/corion/moduleHandler.sol @@ -0,0 +1,448 @@ +pragma solidity ^0.4.11; + +import "./module.sol"; +import "./announcementTypes.sol"; +import "./multiOwner.sol"; + +import "./publisher.sol"; +import "./token.sol"; +import "./provider.sol"; +import "./schelling.sol"; +import "./premium.sol"; +import "./ico.sol"; + +contract abstractModule { + function connectModule() external returns (bool success) {} + function disconnectModule() external returns (bool success) {} + function replaceModule(address addr) external returns (bool success) {} + function disableModule(bool forever) external returns (bool success) {} + function isActive() public constant returns (bool success) {} + function replaceModuleHandler(address newHandler) external returns (bool success) {} + function transferEvent(address from, address to, uint256 value) external returns (bool success) {} + function newSchellingRoundEvent(uint256 roundID, uint256 reward) external returns (bool success) {} +} + +contract moduleHandler is multiOwner, announcementTypes { + + struct modules_s { + address addr; + bytes32 name; + bool schellingEvent; + bool transferEvent; + } + + modules_s[] public modules; + address public foundationAddress; + uint256 debugModeUntil = block.number + 1000000; + + function moduleHandler(address[] newOwners) multiOwner(newOwners) {} + + function load(address foundation, bool forReplace, address Token, address Premium, address Publisher, address Schelling, address Provider) { + /* + Loading modulest to ModuleHandler. + + This module can be called only once and only by the owner, if every single module and its database are already put on the blockchain. + If forReaplace is true, than the ModuleHandler will be replaced. Before the publishing of its replace, the new contract must be already on the blockchain. + + @foundation Address of foundation. + @forReplace Is it for replace or not. If not, it will be connected to the module. + @Token address of token. + @Publisher address of publisher. + @Schelling address of Schelling. + @Provider address of provider + */ + require( owners[msg.sender] ); + require( modules.length == 0 ); + foundationAddress = foundation; + addModule( modules_s(Token, sha3('Token'), false, false), ! forReplace); + addModule( modules_s(Premium, sha3('Premium'), false, false), ! forReplace); + addModule( modules_s(Publisher, sha3('Publisher'), false, true), ! forReplace); + addModule( modules_s(Schelling, sha3('Schelling'), false, true), ! forReplace); + addModule( modules_s(Provider, sha3('Provider'), true, true), ! forReplace); + } + function addModule(modules_s input, bool call) internal { + /* + Inside function for registration of the modules in the database. + If the call is false, wont happen any direct call. + + @input _Structure of module. + @call Is connect to the module or not. + */ + if ( call ) { require( abstractModule(input.addr).connectModule() ); } + var (success, found, id) = getModuleIDByAddress(input.addr); + require( success && ! found ); + (success, found, id) = getModuleIDByHash(input.name); + require( success && ! found ); + (success, found, id) = getModuleIDByAddress(0x00); + require( success ); + if ( ! found ) { + id = modules.length; + modules.length++; + } + modules[id] = input; + } + function getModuleAddressByName(string name) public constant returns( bool success, bool found, address addr ) { + /* + Search by name for module. The result is an Ethereum address. + + @name Name of module. + @addr Address of module. + @found Is there any result. + @success Was the transaction succesfull or not. + */ + var (_success, _found, _id) = getModuleIDByName(name); + if ( _success && _found ) { return (true, true, modules[_id].addr); } + return (true, false, 0x00); + } + function getModuleIDByHash(bytes32 hashOfName) public constant returns( bool success, bool found, uint256 id ) { + /* + Search by hash of name in the module array. The result is an index array. + + @name Name of module. + @id Index of module. + @found Was there any result or not. + */ + for ( uint256 a=0 ; a<modules.length ; a++ ) { + if ( modules[a].name == hashOfName ) { + return (true, true, a); + } + } + return (true, false, 0); + } + function getModuleIDByName(string name) public constant returns( bool success, bool found, uint256 id ) { + /* + Search by name for module. The result is an index array. + + @name Name of module. + @id Index of module. + @found Was there any result or not. + */ + bytes32 _name = sha3(name); + for ( uint256 a=0 ; a<modules.length ; a++ ) { + if ( modules[a].name == _name ) { + return (true, true, a); + } + } + return (true, false, 0); + } + function getModuleIDByAddress(address addr) public constant returns( bool success, bool found, uint256 id ) { + /* + Search by ethereum address for module. The result is an index array. + + @name Name of module. + @id Index of module. + @found Was there any result or not. + */ + for ( uint256 a=0 ; a<modules.length ; a++ ) { + if ( modules[a].addr == addr ) { + return (true, true, a); + } + } + return (true, false, 0); + } + function replaceModule(string name, address addr, bool callCallback) external returns (bool success) { + /* + Module replace, can be called only by the Publisher contract. + + @name Name of module. + @addr Address of module. + @bool Was there any result or not. + @callCallback Call the replaceable module to confirm replacement or not. + */ + var (_success, _found, _id) = getModuleIDByAddress(msg.sender); + require( _success ); + if ( ! ( _found && modules[_id].name == sha3('Publisher') )) { + require( block.number < debugModeUntil ); + if ( ! insertAndCheckDo(calcDoHash("replaceModule", sha3(name, addr, callCallback))) ) { + return true; + } + } + (_success, _found, _id) = getModuleIDByName(name); + require( _success && _found ); + if ( callCallback ) { + require( abstractModule(modules[_id].addr).replaceModule(addr) ); + } + require( abstractModule(addr).connectModule() ); + modules[_id].addr = addr; + return true; + } + + function callReplaceCallback(string moduleName, address newModule) external returns (bool success) { + require( block.number < debugModeUntil ); + if ( ! insertAndCheckDo(calcDoHash("callReplaceCallback", sha3(moduleName, newModule))) ) { + return true; + } + var (_success, _found, _id) = getModuleIDByName(moduleName); + require( _success); + require( abstractModule(modules[_id].addr).replaceModule(newModule) ); + return true; + } + + function newModule(string name, address addr, bool schellingEvent, bool transferEvent) external returns (bool success) { + /* + Adding new module to the database. Can be called only by the Publisher contract. + + @name Name of module. + @addr Address of module. + @schellingEvent Gets it new Schelling round notification? + @transferEvent Gets it new transaction notification? + @bool Was there any result or not. + */ + var (_success, _found, _id) = getModuleIDByAddress(msg.sender); + require( _success ); + if ( ! ( _found && modules[_id].name == sha3('Publisher') )) { + require( block.number < debugModeUntil ); + if ( ! insertAndCheckDo(calcDoHash("newModule", sha3(name, addr, schellingEvent, transferEvent))) ) { + return true; + } + } + addModule( modules_s(addr, sha3(name), schellingEvent, transferEvent), true); + return true; + } + function dropModule(string name, bool callCallback) external returns (bool success) { + /* + Deleting module from the database. Can be called only by the Publisher contract. + + @name Name of module to delete. + @bool Was the function successfull? + @callCallback Call the replaceable module to confirm replacement or not. + */ + var (_success, _found, _id) = getModuleIDByAddress(msg.sender); + require( _success ); + if ( ! ( _found && modules[_id].name == sha3('Publisher') )) { + require( block.number < debugModeUntil ); + if ( ! insertAndCheckDo(calcDoHash("replaceModule", sha3(name, callCallback))) ) { + return true; + } + } + (_success, _found, _id) = getModuleIDByName(name); + require( _success && _found ); + if( callCallback ) { + abstractModule(modules[_id].addr).disableModule(true); + } + delete modules[_id]; + return true; + } + + function callDisableCallback(string moduleName) external returns (bool success) { + require( block.number < debugModeUntil ); + if ( ! insertAndCheckDo(calcDoHash("callDisableCallback", sha3(moduleName))) ) { + return true; + } + var (_success, _found, _id) = getModuleIDByName(moduleName); + require( _success); + require( abstractModule(modules[_id].addr).disableModule(true) ); + return true; + } + + function broadcastTransfer(address from, address to, uint256 value) external returns (bool success) { + /* + Announcing transactions for the modules. + + Can be called only by the token module. + Only the configured modules get notifications.( transferEvent ) + + @from from who. + @to to who. + @value amount. + @bool Was the function successfull? + */ + var (_success, _found, _id) = getModuleIDByAddress(msg.sender); + require( _success && _found && modules[_id].name == sha3('Token') ); + for ( uint256 a=0 ; a<modules.length ; a++ ) { + if ( modules[a].transferEvent && abstractModule(modules[a].addr).isActive() ) { + require( abstractModule(modules[a].addr).transferEvent(from, to, value) ); + } + } + return true; + } + function broadcastSchellingRound(uint256 roundID, uint256 reward) external returns (bool success) { + /* + Announcing new Schelling round for the modules. + Can be called only by the Schelling module. + Only the configured modules get notifications( schellingEvent ). + + @roundID Number of Schelling round. + @reward Coin emission in this Schelling round. + @bool Was the function successfull? + */ + var (_success, _found, _id) = getModuleIDByAddress(msg.sender); + require( _success && _found && modules[_id].name == sha3('Schelling') ); + for ( uint256 a=0 ; a<modules.length ; a++ ) { + if ( modules[a].schellingEvent && abstractModule(modules[a].addr).isActive() ) { + require( abstractModule(modules[a].addr).newSchellingRoundEvent(roundID, reward) ); + } + } + return true; + } + function replaceModuleHandler(address newHandler) external returns (bool success) { + /* + Replacing ModuleHandler. + + Can be called only by the publisher. + Every module will be informed about the ModuleHandler replacement. + + @newHandler Address of the new ModuleHandler. + @bool Was the function successfull? + */ + var (_success, _found, _id) = getModuleIDByAddress(msg.sender); + require( _success ); + if ( ! ( _found && modules[_id].name == sha3('Publisher') )) { + require( block.number < debugModeUntil ); + if ( ! insertAndCheckDo(calcDoHash("replaceModuleHandler", sha3(newHandler))) ) { + return true; + } + } + for ( uint256 a=0 ; a<modules.length ; a++ ) { + require( abstractModule(modules[a].addr).replaceModuleHandler(newHandler) ); + } + return true; + } + function balanceOf(address owner) public constant returns (bool success, uint256 value) { + /* + Query of token balance. + + @owner address + @value balance. + @success was the function successfull? + */ + var (_success, _found, _id) = getModuleIDByName('Token'); + require( _success && _found ); + return (true, token(modules[_id].addr).balanceOf(owner)); + } + function totalSupply() public constant returns (bool success, uint256 value) { + /* + Query of the whole token amount. + + @value amount. + @success was the function successfull? + */ + var (_success, _found, _id) = getModuleIDByName('Token'); + require( _success && _found ); + return (true, token(modules[_id].addr).totalSupply()); + } + function isICO() public constant returns (bool success, bool ico) { + /* + Query of ICO state + + @ico Is ICO in progress?. + @success was the function successfull? + */ + var (_success, _found, _id) = getModuleIDByName('Token'); + require( _success && _found ); + return (true, token(modules[_id].addr).isICO()); + } + function getCurrentSchellingRoundID() public constant returns (bool success, uint256 round) { + /* + Query of number of the actual Schelling round. + + @round Schelling round. + @success was the function successfull? + */ + var (_success, _found, _id) = getModuleIDByName('Schelling'); + require( _success && _found ); + return (true, schelling(modules[_id].addr).getCurrentSchellingRoundID()); + } + function mint(address to, uint256 value) external returns (bool success) { + /* + Token emission request. Can be called only by the provider. + + @to Place of new token + @value Token amount + + @success Was the function successfull? + */ + var (_success, _found, _id) = getModuleIDByAddress(msg.sender); + require( _success && _found && modules[_id].name == sha3('Provider') ); + (_success, _found, _id) = getModuleIDByName('Token'); + require( _success && _found ); + require( token(modules[_id].addr).mint(to, value) ); + return true; + } + function transfer(address from, address to, uint256 value, bool fee) external returns (bool success) { + /* + Token transaction request. Can be called only by a module. + + @from from who. + @to To who. + @value Token amount. + @fee Transaction fee will be charged or not? + @success Was the function successfull? + */ + var (_success, _found, _id) = getModuleIDByAddress(msg.sender); + require( _success && _found ); + (_success, _found, _id) = getModuleIDByName('Token'); + require( _success && _found ); + require( token(modules[_id].addr).transferFromByModule(from, to, value, fee) ); + return true; + } + function processTransactionFee(address from, uint256 value) external returns (bool success) { + /* + Token transaction fee. Can be called only by the provider. + + @from From who. + @value Token amount. + @success Was the function successfull? + */ + var (_success, _found, _id) = getModuleIDByAddress(msg.sender); + require( _success && _found && modules[_id].name == sha3('Provider') ); + (_success, _found, _id) = getModuleIDByName('Token'); + require( _success && _found ); + require( token(modules[_id].addr).processTransactionFee(from, value) ); + return true; + } + function burn(address from, uint256 value) external returns (bool success) { + /* + Token burn. Can be called only by Schelling. + + @from From who. + @value Token amount. + @success Was the function successfull? + */ + var (_success, _found, _id) = getModuleIDByAddress(msg.sender); + require( _success && _found && modules[_id].name == sha3('Schelling') ); + (_success, _found, _id) = getModuleIDByName('Token'); + require( _success && _found ); + require( token(modules[_id].addr).burn(from, value) ); + return true; + } + function configureModule(string moduleName, announcementType aType, uint256 value) external returns (bool success) { + /* + Changing configuration of a module. Can be called only by Publisher or while debug mode by owners. + + @moduleName Module name which will be configured + @aType Type of variable (announcementType). + @value New value + @success Was the function successfull? + */ + var (_success, _found, _id) = getModuleIDByAddress(msg.sender); + require( _success ); + if ( ! ( _found && modules[_id].name == sha3('Publisher') )) { + require( block.number < debugModeUntil ); + if ( ! insertAndCheckDo(calcDoHash("configureModule", sha3(moduleName, aType, value))) ) { + return true; + } + } + (_success, _found, _id) = getModuleIDByName(moduleName); + require( _success && _found ); + require( schelling(modules[_id].addr).configure(aType, value) ); + return true; + } + function freezing(bool forever) external { + /* + Freezing CORION Platform. Can be called only by the owner. + Freez can not be recalled! + + @forever Is it forever or not? + */ + require( owners[msg.sender] ); + if ( forever ) { + if ( ! insertAndCheckDo(calcDoHash("freezing", sha3(forever))) ) { + return; + } + } + for ( uint256 a=0 ; a<modules.length ; a++ ) { + require( abstractModule(modules[a].addr).disableModule(forever) ); + } + } +} diff --git a/test/compilationTests/corion/multiOwner.sol b/test/compilationTests/corion/multiOwner.sol new file mode 100644 index 00000000..9aae0ebd --- /dev/null +++ b/test/compilationTests/corion/multiOwner.sol @@ -0,0 +1,83 @@ +pragma solidity ^0.4.11; + +import "./safeMath.sol"; + +contract multiOwner is safeMath { + + mapping(address => bool) public owners; + uint256 public ownerCount; + + mapping(bytes32 => address[]) public doDB; + + /* + Constructor + */ + function multiOwner(address[] newOwners) { + for ( uint256 a=0 ; a<newOwners.length ; a++ ) { + _addOwner(newOwners[a]); + } + } + /* + Externals + */ + function insertOwner(address addr) external { + if ( insertAndCheckDo(calcDoHash("insertOwner", sha3(addr))) ) { + _addOwner(addr); + } + } + function dropOwner(address addr) external { + if ( insertAndCheckDo(calcDoHash("dropOwner", sha3(addr))) ) { + _delOwner(addr); + } + } + function cancelDo(bytes32 doHash) external { + if ( insertAndCheckDo(calcDoHash("cancelDo", doHash)) ) { + delete doDB[doHash]; + } + } + /* + Constants + */ + function ownersForChange() public constant returns (uint256 owners) { + return ownerCount * 75 / 100; + } + function calcDoHash(string job, bytes32 data) public constant returns (bytes32 hash) { + return sha3(job, data); + } + function validDoHash(bytes32 doHash) public constant returns (bool valid) { + return doDB[doHash].length > 0; + } + /* + Internals + */ + function insertAndCheckDo(bytes32 doHash) internal returns (bool success) { + require( owners[msg.sender] ); + if (doDB[doHash].length >= ownersForChange()) { + delete doDB[doHash]; + return true; + } + for ( uint256 a=0 ; a<doDB[doHash].length ; a++ ) { + require( doDB[doHash][a] != msg.sender ); + } + if ( doDB[doHash].length+1 >= ownersForChange() ) { + delete doDB[doHash]; + return true; + } else { + doDB[doHash].push(msg.sender); + return false; + } + } + /* + Privates + */ + function _addOwner(address addr) private { + if ( owners[addr] ) { return; } + owners[addr] = true; + ownerCount = safeAdd(ownerCount, 1); + } + function _delOwner(address addr) private { + if ( ! owners[addr] ) { return; } + delete owners[addr]; + ownerCount = safeSub(ownerCount, 1); + } +} diff --git a/test/compilationTests/corion/owned.sol b/test/compilationTests/corion/owned.sol new file mode 100644 index 00000000..bd187775 --- /dev/null +++ b/test/compilationTests/corion/owned.sol @@ -0,0 +1,28 @@ +pragma solidity ^0.4.11;
+
+contract ownedDB {
+ address private owner;
+
+ function replaceOwner(address newOwner) external returns(bool) {
+ /*
+ Owner replace.
+
+ @newOwner Address of new owner.
+ */
+ require( isOwner() );
+ owner = newOwner;
+ return true;
+ }
+
+ function isOwner() internal returns(bool) {
+ /*
+ Check of owner address.
+
+ @bool Owner has called the contract or not
+ */
+ if ( owner == 0x00 ) {
+ return true;
+ }
+ return owner == msg.sender;
+ }
+}
diff --git a/test/compilationTests/corion/premium.sol b/test/compilationTests/corion/premium.sol new file mode 100644 index 00000000..be2c5de0 --- /dev/null +++ b/test/compilationTests/corion/premium.sol @@ -0,0 +1,346 @@ +pragma solidity ^0.4.11; + +import "./safeMath.sol"; +import "./tokenDB.sol"; +import "./module.sol"; + +contract thirdPartyPContractAbstract { + function receiveCorionPremiumToken(address, uint256, bytes) external returns (bool, uint256) {} + function approvedCorionPremiumToken(address, uint256, bytes) external returns (bool) {} +} + +contract ptokenDB is tokenDB {} + +contract premium is module, safeMath { + function replaceModule(address addr) external returns (bool success) { + require( super.isModuleHandler(msg.sender) ); + require( db.replaceOwner(addr) ); + super._replaceModule(addr); + return true; + } + modifier isReady { + var (_success, _active) = super.isActive(); + require( _success && _active ); + _; + } + /** + * + * @title Corion Platform Premium Token + * @author iFA @ Corion Platform + * + */ + + string public name = "Corion Premium"; + string public symbol = "CORP"; + uint8 public decimals = 0; + + address public icoAddr; + tokenDB public db; + bool public isICO; + + mapping(address => bool) public genesis; + + function premium(bool forReplace, address moduleHandler, address dbAddress, address icoContractAddr, address[] genesisAddr, uint256[] genesisValue) { + /* + Setup function. + If an ICOaddress is defined then the balance of the genesis addresses will be set as well. + + @forReplace This address will be replaced with the old one or not. + @moduleHandler Modulhandler’s address + @dbAddress Address of database + @icoContractAddr Address of ico contract. + @genesisAddr Array of the genesis addresses. + @genesisValue Array of the balance of the genesis addresses + */ + super.registerModuleHandler(moduleHandler); + require( dbAddress != 0x00 ); + db = ptokenDB(dbAddress); + if ( ! forReplace ) { + require( db.replaceOwner(this) ); + isICO = true; + icoAddr = icoContractAddr; + assert( genesisAddr.length == genesisValue.length ); + for ( uint256 a=0 ; a<genesisAddr.length ; a++ ) { + genesis[genesisAddr[a]] = true; + require( db.increase(genesisAddr[a], genesisValue[a]) ); + Mint(genesisAddr[a], genesisValue[a]); + } + } + } + + function closeIco() external returns (bool success) { + /* + Finishing the ICO. Can be invited only by an ICO contract. + + @success If the function was successful. + */ + require( isICO ); + isICO = false; + return true; + } + + /** + * @notice `msg.sender` approves `spender` to spend `amount` tokens on its behalf. + * @param spender The address of the account able to transfer the tokens + * @param amount The amount of tokens to be approved for transfer + * @param nonce The transaction count of the authorised address + * @return True if the approval was successful + */ + function approve(address spender, uint256 amount, uint256 nonce) isReady external returns (bool success) { + /* + Authorize another address to use an exact amount of the principal’s balance. + + @spender Address of authorised party + @amount Token quantity + @nonce Transaction count + + @success Was the Function successful? + */ + _approve(spender, amount, nonce); + return true; + } + + /** + * @notice `msg.sender` approves `spender` to spend `amount` tokens on its behalf and notify the spender from your approve with your `extraData` data. + * @param spender The address of the account able to transfer the tokens + * @param amount The amount of tokens to be approved for transfer + * @param nonce The transaction count of the authorised address + * @param extraData Data to give forward to the receiver + * @return True if the approval was successful + */ + function approveAndCall(address spender, uint256 amount, uint256 nonce, bytes extraData) isReady external returns (bool success) { + /* + Authorize another address to use an exact amount of the principal’s balance. + After the transaction the approvedCorionPremiumToken function of the address will be called with the given data. + + @spender Authorized address + @amount Token quantity + @extraData Extra data to be received by the receiver + @nonce Transaction count + + @sucess Was the Function successful? + */ + _approve(spender, amount, nonce); + require( thirdPartyPContractAbstract(spender).approvedCorionPremiumToken(msg.sender, amount, extraData) ); + return true; + } + + function _approve(address spender, uint256 amount, uint256 nonce) isReady internal { + /* + Inner function to authorize another address to use an exact amount of the principal’s balance. + If the transaction count not match the authorise fails. + + @spender Address of authorised party + @amount Token quantity + @nonce Transaction count + */ + require( msg.sender != spender ); + require( db.balanceOf(msg.sender) >= amount ); + require( db.setAllowance(msg.sender, spender, amount, nonce) ); + Approval(msg.sender, spender, amount); + } + + function allowance(address owner, address spender) constant returns (uint256 remaining, uint256 nonce) { + /* + Get the quantity of tokens given to be used + + @owner Authorising address + @spender Authorised address + + @remaining Tokens to be spent + @nonce Transaction count + */ + var (_success, _remaining, _nonce) = db.getAllowance(owner, spender); + require( _success ); + return (_remaining, _nonce); + } + + /** + * @notice Send `amount` Corion tokens to `to` from `msg.sender` + * @param to The address of the recipient + * @param amount The amount of tokens to be transferred + * @return Whether the transfer was successful or not + */ + function transfer(address to, uint256 amount) isReady external returns (bool success) { + /* + Launch a transaction where the token is sent from the sender’s address to the receiver’s address. + Transaction fee is going to be added as well. + If the receiver is not a natural address but also a person then she/he will be invited as well. + + @to For who + @amount Amount + + @success Was the function successful? + */ + bytes memory _data; + if ( isContract(to) ) { + transferToContract(msg.sender, to, amount, _data); + } else { + _transfer(msg.sender, to, amount); + } + Transfer(msg.sender, to, amount, _data); + return true; + } + + /** + * @notice Send `amount` tokens to `to` from `from` on the condition it is approved by `from` + * @param from The address holding the tokens being transferred + * @param to The address of the recipient + * @param amount The amount of tokens to be transferred + * @return True if the transfer was successful + */ + function transferFrom(address from, address to, uint256 amount) isReady external returns (bool success) { + /* + Launch a transaction where we transfer from a given address to another one. It can only be called by an address which was allowed before. + Transaction fee will be charged too. + If the receiver is not a natural address but also a person then she/he will be invited as well + + @from From who? + @to For who? + @amount Amount + + @success If the function was successful. + */ + if ( from != msg.sender ) { + var (_success, _reamining, _nonce) = db.getAllowance(from, msg.sender); + require( _success ); + _reamining = safeSub(_reamining, amount); + _nonce = safeAdd(_nonce, 1); + require( db.setAllowance(from, msg.sender, _reamining, _nonce) ); + AllowanceUsed(msg.sender, from, amount); + } + bytes memory _data; + if ( isContract(to) ) { + transferToContract(from, to, amount, _data); + } else { + _transfer( from, to, amount); + } + Transfer(from, to, amount, _data); + return true; + } + + /** + * @notice Send `amount` Corion tokens to `to` from `msg.sender` and notify the receiver from your transaction with your `extraData` data + * @param to The contract address of the recipient + * @param amount The amount of tokens to be transferred + * @param extraData Data to give forward to the receiver + * @return Whether the transfer was successful or not + */ + function transfer(address to, uint256 amount, bytes extraData) isReady external returns (bool success) { + /* + Launch a transaction where we transfer from a given address to another one. + After thetransaction the approvedCorionPremiumToken function of the receiver’s address is going to be called with the given data. + + @to For who? + @amount Amount + @extraData Extra data that will be given to the receiver + + @success If the function was successful. + */ + if ( isContract(to) ) { + transferToContract(msg.sender, to, amount, extraData); + } else { + _transfer( msg.sender, to, amount); + } + Transfer(msg.sender, to, amount, extraData); + return true; + } + + function transferToContract(address from, address to, uint256 amount, bytes extraData) internal { + /* + Inner function in order to transact a contract. + + @to For who? + @amount Amount + @extraData Extra data that will be given to the receiver + */ + _transfer(from, to, amount); + var (_success, _back) = thirdPartyPContractAbstract(to).receiveCorionPremiumToken(from, amount, extraData); + require( _success ); + require( amount > _back ); + if ( _back > 0 ) { + _transfer(to, from, _back); + } + } + + function _transfer(address from, address to, uint256 amount) isReady internal { + /* + Inner function to launch a transaction. + During the ICO transactions are only possible from the genesis address. + 0xa636a97578d26a3b76b060bbc18226d954cf3757 address is blacklisted. + + @from From how? + @to For who? + @amount Amount + */ + require( from != 0x00 && to != 0x00 && to != 0xa636a97578d26a3b76b060bbc18226d954cf3757 ); + require( ( ! isICO) || genesis[from] ); + require( db.decrease(from, amount) ); + require( db.increase(to, amount) ); + } + + function mint(address owner, uint256 value) external returns (bool success) { + /* + Generating tokens. It can be called only by ICO contract. + + @owner Address + @value Amount. + + @success Was the Function successful? + */ + require( msg.sender == icoAddr || isICO ); + _mint(owner, value); + return true; + } + + function _mint(address owner, uint256 value) isReady internal { + /* + Inner function to create a token. + + @owner Address of crediting the token. + @value Amount + */ + require( db.increase(owner, value) ); + Mint(owner, value); + } + + function isContract(address addr) internal returns (bool success) { + /* + Inner function in order to check if the given address is a natural address or a contract. + + @addr The address which is needed to be checked. + + @success Is the address crontact or not + */ + uint256 _codeLength; + assembly { + _codeLength := extcodesize(addr) + } + return _codeLength > 0; + } + + function balanceOf(address owner) constant returns (uint256 value) { + /* + Token balance query + + @owner Address + @value Balance of address + */ + return db.balanceOf(owner); + } + + function totalSupply() constant returns (uint256 value) { + /* + Total token quantity query + + @value Total token quantity + */ + return db.totalSupply(); + } + + event AllowanceUsed(address indexed spender, address indexed owner, uint256 indexed value); + event Mint(address indexed addr, uint256 indexed value); + event Burn(address indexed addr, uint256 indexed value); + event Approval(address indexed _owner, address indexed _spender, uint256 _value); + event Transfer(address indexed _from, address indexed _to, uint256 _value, bytes _extraData); +} diff --git a/test/compilationTests/corion/provider.sol b/test/compilationTests/corion/provider.sol new file mode 100644 index 00000000..5fa90fcd --- /dev/null +++ b/test/compilationTests/corion/provider.sol @@ -0,0 +1,797 @@ +pragma solidity ^0.4.11; + +import "./module.sol"; +import "./moduleHandler.sol"; +import "./safeMath.sol"; +import "./announcementTypes.sol"; + +contract provider is module, safeMath, announcementTypes { + /* + module callbacks + */ + function connectModule() external returns (bool success) { + require( super.isModuleHandler(msg.sender) ); + super._connectModule(); + var (_success, currentSchellingRound) = moduleHandler(moduleHandlerAddress).getCurrentSchellingRoundID(); + require( _success ); + return true; + } + function transferEvent(address from, address to, uint256 value) external returns (bool success) { + /* + Transaction completed. This function is ony available for the modulehandler. + It should be checked if the sender or the acceptor does not connect to the provider or it is not a provider itself if so than the change should be recorded. + + @from From whom? + @to For who? + @value amount + @bool Was the function successful? + */ + require( super.isModuleHandler(msg.sender) ); + transferEvent_(from, value, true); + transferEvent_(to, value, false); + return true; + } + function newSchellingRoundEvent(uint256 roundID, uint256 reward) external returns (bool success) { + /* + New schelling round. This function is only available for the moduleHandler. + We are recording the new schelling round and we are storing the whole current quantity of the tokens. + We generate a reward quantity of tokens directed to the providers address. The collected interest will be tranfered from this contract. + + @roundID Number of the schelling round. + @reward token emission + @bool Was the function successful? + */ + require( super.isModuleHandler(msg.sender) ); + globalFunds[roundID].reward = reward; + globalFunds[roundID].supply = globalFunds[roundID-1].supply; + currentSchellingRound = roundID; + require( moduleHandler(moduleHandlerAddress).mint(address(this), reward) ); + return true; + } + modifier isReady { + var (_success, _active) = super.isActive(); + require( _success && _active ); + _; + } + /* + Provider module + */ + uint256 private minFundsForPublic = 3000; + uint256 private minFundsForPrivate = 8000; + uint256 private privateProviderLimit = 250; + uint8 private publicMinRate = 30; + uint8 private privateMinRate = 0; + uint8 private publicMaxRate = 70; + uint8 private privateMaxRate = 100; + uint256 private gasProtectMaxRounds = 630; + uint256 private interestMinFunds = 25000; + uint256 private rentRate = 20; + + struct _rate { + uint8 value; + bool valid; + } + struct __providers { + address admin; + string name; + string website; + string country; + string info; + bool isForRent; + mapping(uint256 => _rate) rateHistory; + uint8 currentRate; + bool priv; + uint256 clientsCount; + mapping(address => bool) allowedUsers; + mapping(uint256 => uint256) supply; + uint256 lastSupplyID; + mapping(uint256 => uint256) ownSupply; + uint256 lastOwnSupplyID; + uint256 paidUpTo; + uint8 lastPaidRate; + uint256 create; + uint256 close; + bool valid; + } + struct _providers { + mapping(uint256 => __providers) data; + uint256 currentHeight; + } + mapping(address => _providers) private providers; + + struct _globalFunds { + uint256 reward; + uint256 supply; + } + mapping(uint256 => _globalFunds) private globalFunds; + + struct _client{ + address providerAddress; + uint256 providerHeight; + uint256 providerConnected; + uint8 lastRate; + mapping(uint256 => uint256) supply; + uint256 lastSupplyID; + uint256 paidUpTo; + } + mapping(address => _client) private clients; + + uint256 private currentSchellingRound = 1; + + function provider(address _moduleHandler) { + /* + Install function. + + @_moduleHandler Address of the moduleHandler. + */ + super.registerModuleHandler(_moduleHandler); + } + function configure(announcementType a, uint256 b) external returns(bool) { + /* + Configuration of the provider. Can be invited just by the moduleHandler. + + @a Type of the setting + @b value + */ + require( super.isModuleHandler(msg.sender) ); + if ( a == announcementType.providerPublicFunds ) { minFundsForPublic = b; } + else if ( a == announcementType.providerPrivateFunds ) { minFundsForPrivate = b; } + else if ( a == announcementType.providerPrivateClientLimit ) { privateProviderLimit = b; } + else if ( a == announcementType.providerPublicMinRate ) { publicMinRate = uint8(b); } + else if ( a == announcementType.providerPublicMaxRate ) { publicMaxRate = uint8(b); } + else if ( a == announcementType.providerPrivateMinRate ) { privateMinRate = uint8(b); } + else if ( a == announcementType.providerPrivateMaxRate ) { privateMaxRate = uint8(b); } + else if ( a == announcementType.providerGasProtect ) { gasProtectMaxRounds = b; } + else if ( a == announcementType.providerInterestMinFunds ) { interestMinFunds = b; } + else if ( a == announcementType.providerRentRate ) { rentRate = b; } + else { return false; } + return true; + } + function getUserDetails(address addr, uint256 schellingRound) public constant returns (address ProviderAddress, uint256 ProviderHeight, uint256 ConnectedOn, uint256 value) { + /* + Collecting the datas of the client. + + @addr Address of the client. + @schellingRound Number of the schelling round. If it is not defined then the current one. + @ProviderAddress Address of the provider the one where connected to + @ProviderHeight The height (level) of the provider where is connected. + @ConnectedOn Time of connection + @value Quantity of the client’s token + */ + if ( schellingRound == 0 ) { + schellingRound = currentSchellingRound; + } + if ( clients[addr].providerAddress != 0 ) { + ProviderAddress = clients[addr].providerAddress; + ProviderHeight = clients[addr].providerHeight; + ConnectedOn = clients[addr].providerConnected; + value = clients[addr].supply[schellingRound]; + } + } + function rightForInterest(uint256 value, bool priv) internal returns (bool) { + /* + the share from the token emission. + In case is a private provider it has to be checked if it has enough connected capital to be able to accept share from the token emission. + The provider’s account counts as a capital for the emission as well. + + @value amount of the connected capital + @priv Is the provider private or not? + @bool Gets the share from the token emission. + */ + if ( priv ) { + return ( value >= interestMinFunds ); + } + return true; + } + function setRightForInterest(uint256 oldValue, uint256 newValue, bool priv) internal { + /* + It checks if the provider has enough connected captital to be able to get from the token emission. + In case the provider is not able to get the share from the token emission then the connected capital will not count to the value of the globalFunds, to the current schelling round. + + @oldValue old + @newValue new + @priv Is the provider private? + */ + var a = rightForInterest(oldValue, priv); + var b = rightForInterest(newValue, priv); + if ( a && b ) { + globalFunds[currentSchellingRound].supply = globalFunds[currentSchellingRound].supply - oldValue + newValue; + } else if ( a && ! b ) { + globalFunds[currentSchellingRound].supply -= oldValue; + } else if ( ! a && b ) { + globalFunds[currentSchellingRound].supply += newValue; + } + } + function checkCorrectRate(bool priv, uint8 rate) internal returns(bool) { + /* + Inner function which checks if the amount of interest what is given by the provider is fits to the criteria. + + @priv Is the provider private or not? + @rate Percentage/rate of the interest + @bool Correct or not? + */ + return ( ! priv && ( rate >= publicMinRate && rate <= publicMaxRate ) ) || + ( priv && ( rate >= privateMinRate && rate <= privateMaxRate ) ); + } + function createProvider(bool priv, string name, string website, string country, string info, uint8 rate, bool isForRent, address admin) isReady external { + /* + Creating a provider. + During the ICO its not allowed to create provider. + To one address only one provider can belong to. + Address, how is connected to the provider can not create a provider. + For opening, has to have enough capital. + All the functions of the provider except of the closing are going to be handled by the admin. + The provider can be start as a rent as well, in this case the isForRent has to be true/correct. In case it runs as a rent the 20% of the profit will belong to the leser and the rest goes to the admin. + + @priv Privat szolgaltato e. Is private provider? + @name Provider’s name. + @website Provider’s website + @country Provider’s country + @info Provider’s short introduction. + @rate Rate of the emission what is going to be transfered to the client by the provider. + @isForRent is for Rent or not? + @admin The admin’s address + */ + require( ! providers[msg.sender].data[providers[msg.sender].currentHeight].valid ); + require( clients[msg.sender].providerAddress == 0x00 ); + require( ! checkICO() ); + if ( priv ) { + require( getTokenBalance(msg.sender) >= minFundsForPrivate ); + } else { + require( getTokenBalance(msg.sender) >= minFundsForPublic ); + } + require( checkCorrectRate(priv, rate) ); + + providers[msg.sender].currentHeight++; + var currHeight = providers[msg.sender].currentHeight; + providers[msg.sender].data[currHeight].valid = true; + if ( admin == 0x00 ) { + providers[msg.sender].data[currHeight].admin = msg.sender; + } else { + providers[msg.sender].data[currHeight].admin = admin; + } + providers[msg.sender].data[currHeight].name = name; + providers[msg.sender].data[currHeight].website = website; + providers[msg.sender].data[currHeight].isForRent = isForRent; + providers[msg.sender].data[currHeight].country = country; + providers[msg.sender].data[currHeight].info = info; + providers[msg.sender].data[currHeight].currentRate = rate; + providers[msg.sender].data[currHeight].create = now; + providers[msg.sender].data[currHeight].lastPaidRate = rate; + providers[msg.sender].data[currHeight].priv = priv; + providers[msg.sender].data[currHeight].lastSupplyID = currentSchellingRound; + providers[msg.sender].data[currHeight].paidUpTo = currentSchellingRound; + if ( priv ) { + providers[msg.sender].data[currHeight].supply[currentSchellingRound] = getTokenBalance(msg.sender); + providers[msg.sender].data[currHeight].ownSupply[currentSchellingRound] = getTokenBalance(msg.sender); + providers[msg.sender].data[currHeight].lastOwnSupplyID = currentSchellingRound; + } else { + delete providers[msg.sender].data[currHeight].supply[currentSchellingRound]; + } + EProviderOpen(msg.sender, currHeight); + } + function setProviderDetails(address addr, string website, string country, string info, uint8 rate, address admin) isReady external { + /* + Modifying the datas of the provider. + This can only be invited by the provider’s admin. + The emission rate is only valid for the next schelling round for this one it is not. + The admin can only be changed by the address of the provider. + + @addr Address of the provider. + @website Website. + @admin The new address of the admin. If we do not want to set it then we should enter 0X00. + @country Country + @info Short intro. + @rate Rate of the emission what will be given to the client. + */ + var currHeight = providers[addr].currentHeight; + require( providers[addr].data[currHeight].valid ); + require( checkCorrectRate(providers[addr].data[currHeight].priv, rate) ); + require( providers[addr].data[currHeight].admin == msg.sender || msg.sender == addr ); + if ( admin != 0x00 ) { + require( msg.sender == addr ); + providers[addr].data[currHeight].admin = admin; + } + providers[addr].data[currHeight].rateHistory[currentSchellingRound] = _rate( rate, true ); + providers[addr].data[currHeight].website = website; + providers[addr].data[currHeight].country = country; + providers[addr].data[currHeight].info = info; + providers[addr].data[currHeight].currentRate = rate; + EProviderDetailsChanged(addr, currHeight, website, country, info, rate, admin); + } + function getProviderInfo(address addr, uint256 height) public constant returns (string name, string website, string country, string info, uint256 create) { + /* + for the infos of the provider. + In case the height is unknown then the system will use the last known height. + + @addr Addr of the provider + @height Height + @name Name of the provider. + @website Website of the provider. + @country Country of the provider. + @info Short intro of the provider. + @create Timestamp of creating the provider + */ + if ( height == 0 ) { + height = providers[addr].currentHeight; + } + name = providers[addr].data[height].name; + website = providers[addr].data[height].website; + country = providers[addr].data[height].country; + info = providers[addr].data[height].info; + create = providers[addr].data[height].create; + } + function getProviderDetails(address addr, uint256 height) public constant returns (uint8 rate, bool isForRent, uint256 clientsCount, bool priv, bool getInterest, bool valid) { + /* + Asking for the datas of the provider. + In case the height is unknown then the system will use the last known height. + + @addr Address of the provider + @height Height + @rate The rate of the emission which will be transfered to the client. + @isForRent Rent or not. + @clientsCount Number of the clients. + @priv Private or not? + @getInterest Does get from the token emission? + @valid Is an active provider? + */ + if ( height == 0 ) { + height = providers[addr].currentHeight; + } + rate = providers[addr].data[height].currentRate; + isForRent = providers[addr].data[height].isForRent; + clientsCount = providers[addr].data[height].clientsCount; + priv = providers[addr].data[height].priv; + getInterest = rightForInterest(getProviderCurrentSupply(addr), providers[addr].data[height].priv ); + valid = providers[addr].data[height].valid; + } + function getProviderCurrentSupply(address addr) internal returns (uint256) { + /* + Inner function for polling the current height and the current quantity of the connected capital of the schelling round. + + @addr Provider’s address. + @uint256 Amount of the connected capital + */ + return providers[addr].data[providers[addr].currentHeight].supply[currentSchellingRound]; + } + function closeProvider() isReady external { + /* + Closing and inactivate the provider. + It is only possible to close that active provider which is owned by the sender itself after calling the whole share of the emission. + Whom were connected to the provider those clients will have to disconnect after they’ve called their share of emission which was not called before. + */ + var currHeight = providers[msg.sender].currentHeight; + require( providers[msg.sender].data[currHeight].valid ); + require( providers[msg.sender].data[currHeight].paidUpTo == currentSchellingRound ); + + providers[msg.sender].data[currHeight].valid = false; + providers[msg.sender].data[currHeight].close = currentSchellingRound; + setRightForInterest(getProviderCurrentSupply(msg.sender), 0, providers[msg.sender].data[currHeight].priv); + EProviderClose(msg.sender, currHeight); + } + function allowUsers(address provider, address[] addr) isReady external { + /* + Permition of the user to be able to connect to the provider. + This can only be invited by the provider’s admin. + With this kind of call only 100 address can be permited. + + @addr Array of the addresses for whom the connection is allowed. + */ + var currHeight = providers[provider].currentHeight; + require( providers[provider].data[currHeight].valid ); + require( providers[provider].data[currHeight].priv ); + require( providers[provider].data[currHeight].admin == msg.sender ); + require( addr.length <= 100 ); + + for ( uint256 a=0 ; a<addr.length ; a++ ) { + providers[provider].data[currHeight].allowedUsers[addr[a]] = true; + } + } + function disallowUsers(address provider, address[] addr) isReady external { + /* + Disable of the user not to be able to connect to the provider. + It is can called only for the admin of the provider. + With this kind of call only 100 address can be permited. + + @addr Array of the addresses for whom the connection is allowed. + */ + var currHeight = providers[provider].currentHeight; + require( providers[provider].data[currHeight].valid ); + require( providers[provider].data[currHeight].priv ); + require( providers[provider].data[currHeight].admin == msg.sender ); + require( addr.length <= 100 ); + + for ( uint256 a=0 ; a<addr.length ; a++ ) { + delete providers[provider].data[currHeight].allowedUsers[addr[a]]; + } + } + function joinProvider(address provider) isReady external { + /* + Connection to the provider. + Providers can not connect to other providers. + If is a client at any provider, then it is not possible to connect to other provider one. + It is only possible to connect to valid and active providers. + If is an active provider then the client can only connect, if address is permited at the provider (Whitelist). + At private providers, the number of the client is restricted. If it reaches the limit no further clients are allowed to connect. + This process has a transaction fee based on the senders whole token quantity. + + @provider Address of the provider. + */ + var currHeight = providers[provider].currentHeight; + require( ! providers[msg.sender].data[currHeight].valid ); + require( clients[msg.sender].providerAddress == 0x00 ); + require( providers[provider].data[currHeight].valid ); + if ( providers[provider].data[currHeight].priv ) { + require( providers[provider].data[currHeight].allowedUsers[msg.sender] && + providers[provider].data[currHeight].clientsCount < privateProviderLimit ); + } + var bal = getTokenBalance(msg.sender); + require( moduleHandler(moduleHandlerAddress).processTransactionFee(msg.sender, bal) ); + + checkFloatingSupply(provider, currHeight, false, bal); + providers[provider].data[currHeight].clientsCount++; + clients[msg.sender].providerAddress = provider; + clients[msg.sender].providerHeight = currHeight; + clients[msg.sender].supply[currentSchellingRound] = bal; + clients[msg.sender].lastSupplyID = currentSchellingRound; + clients[msg.sender].paidUpTo = currentSchellingRound; + clients[msg.sender].lastRate = providers[provider].data[currHeight].currentRate; + clients[msg.sender].providerConnected = now; + ENewClient(msg.sender, provider, currHeight, bal); + } + function partProvider() isReady external { + /* + Disconnecting from the provider. + Before disconnecting we should poll our share from the token emission even if there was nothing factually. + It is only possible to disconnect those providers who were connected by us before. + */ + var provider = clients[msg.sender].providerAddress; + require( provider != 0x0 ); + var currHeight = clients[msg.sender].providerHeight; + bool providerHasClosed = false; + if ( providers[provider].data[currHeight].close > 0 ) { + providerHasClosed = true; + require( clients[msg.sender].paidUpTo == providers[provider].data[currHeight].close ); + } else { + require( clients[msg.sender].paidUpTo == currentSchellingRound ); + } + + var bal = getTokenBalance(msg.sender); + if ( ! providerHasClosed ) { + providers[provider].data[currHeight].clientsCount--; + checkFloatingSupply(provider, currHeight, true, bal); + } + delete clients[msg.sender].providerAddress; + delete clients[msg.sender].providerHeight; + delete clients[msg.sender].lastSupplyID; + delete clients[msg.sender].paidUpTo; + delete clients[msg.sender].lastRate; + delete clients[msg.sender].providerConnected; + EClientLost(msg.sender, provider, currHeight, bal); + } + function checkReward(address addr) public constant returns (uint256 reward) { + /* + Polling the share from the token emission for clients and for providers. + + @addr The address want to check. + @reward Accumulated amount. + */ + if ( providers[addr].data[providers[addr].currentHeight].valid ) { + uint256 a; + (reward, a) = getProviderReward(addr, 0); + } else if ( clients[addr].providerAddress != 0x0 ) { + reward = getClientReward(0); + } + } + function getReward(address beneficiary, uint256 limit, address provider) isReady external returns (uint256 reward) { + /* + Polling the share from the token emission token emission for clients and for providers. + + It is optionaly possible to give an address of a beneficiary for whom we can transfer the accumulated amount. In case we don’t enter any address then the amount will be transfered to the caller’s address. + As the interest should be checked at each schelling round in order to get the share from that so to avoid the overflow of the gas the number of the check-rounds should be limited. + Opcionalisan megadhato az ellenorzes koreinek szama. It is possible to enter optionaly the number of the check-rounds. If it is 0 then it is automatic. + Provider variable should only be entered if the real owner of the provider is not the caller’s address. + In case the client/provider was far behind then it is possible that this function should be called several times to check the total generated schelling rounds and to collect the share. + If is neighter a client nor a provider then the function is not available. + The tokens will be sent to the beneficiary from the address of the provider without any transaction fees. + + @beneficiary Address of the beneficiary + @limit Quota of the check-rounds. + @provider Address of the provider + @reward Accumulated amount from the previous rounds. + */ + var _limit = limit; + var _beneficiary = beneficiary; + var _provider = provider; + if ( _limit == 0 ) { _limit = gasProtectMaxRounds; } + if ( _beneficiary == 0x00 ) { _beneficiary = msg.sender; } + if ( _provider == 0x00 ) { _provider = msg.sender; } + uint256 clientReward; + uint256 providerReward; + if ( providers[_provider].data[providers[_provider].currentHeight].valid ) { + require( providers[_provider].data[providers[_provider].currentHeight].admin == msg.sender || msg.sender == _provider ); + (providerReward, clientReward) = getProviderReward(_provider, _limit); + } else if ( clients[msg.sender].providerAddress != 0x00 ) { + clientReward = getClientReward(_limit); + } else { + throw; + } + if ( clientReward > 0 ) { + require( moduleHandler(moduleHandlerAddress).transfer(address(this), _beneficiary, clientReward, false) ); + } + if ( providerReward > 0 ) { + require( moduleHandler(moduleHandlerAddress).transfer(address(this), provider, providerReward, false) ); + } + EReward(msg.sender, provider, clientReward, providerReward); + } + function getClientReward(uint256 limit) internal returns (uint256 reward) { + /* + Inner function for the client in order to collect the share from the token emission + + @limit Quota of checking the schelling-rounds. + @reward Collected token amount from the checked rounds. + */ + uint256 value; + uint256 steps; + address provAddr; + uint256 provHeight; + bool interest = false; + var rate = clients[msg.sender].lastRate; + for ( uint256 a = (clients[msg.sender].paidUpTo + 1) ; a <= currentSchellingRound ; a++ ) { + if (globalFunds[a].reward > 0 && globalFunds[a].supply > 0) { + provAddr = clients[msg.sender].providerAddress; + provHeight = clients[msg.sender].providerHeight; + if ( providers[provAddr].data[provHeight].rateHistory[a].valid ) { + rate = providers[provAddr].data[provHeight].rateHistory[a].value; + } + if ( rate > 0 ) { + if ( a > providers[provAddr].data[provHeight].lastSupplyID ) { + interest = rightForInterest(providers[provAddr].data[provHeight].supply[providers[provAddr].data[provHeight].lastSupplyID], providers[provAddr].data[provHeight].priv); + } else { + interest = rightForInterest(providers[provAddr].data[provHeight].supply[a], providers[provAddr].data[provHeight].priv); + } + if ( interest ) { + if ( limit > 0 && steps > limit ) { + a--; + break; + } + if (clients[msg.sender].lastSupplyID < a) { + value = clients[msg.sender].supply[clients[msg.sender].lastSupplyID]; + } else { + value = clients[msg.sender].supply[a]; + } + if ( globalFunds[a].supply > 0) { + reward += value * globalFunds[a].reward / globalFunds[a].supply * uint256(rate) / 100; + } + steps++; + } + } + } + } + clients[msg.sender].lastRate = rate; + clients[msg.sender].paidUpTo = a-1; + } + function getProviderReward(address addr, uint256 limit) internal returns (uint256 providerReward, uint256 adminReward) { + /* + Inner function for the provider in order to collect the share from the token emission + @addr Address of the provider. + @limit Quota of the check-rounds. + @providerReward The reward of the provider’s address from the checked rounds. + @adminReward Admin’s reward from the checked rounds. + */ + uint256 reward; + uint256 ownReward; + uint256 value; + uint256 steps; + uint256 currHeight = providers[addr].currentHeight; + uint256 LTSID = providers[addr].data[currHeight].lastSupplyID; + var rate = providers[addr].data[currHeight].lastPaidRate; + for ( uint256 a = (providers[addr].data[currHeight].paidUpTo + 1) ; a <= currentSchellingRound ; a++ ) { + if (globalFunds[a].reward > 0 && globalFunds[a].supply > 0) { + if ( providers[addr].data[currHeight].rateHistory[a].valid ) { + rate = providers[addr].data[currHeight].rateHistory[a].value; + } + if ( rate > 0 ) { + if ( ( a > LTSID && rightForInterest(providers[addr].data[currHeight].supply[LTSID], providers[addr].data[currHeight].priv) || + rightForInterest(providers[addr].data[currHeight].supply[a], providers[addr].data[currHeight].priv) ) ) { + if ( limit > 0 && steps > limit ) { + a--; + break; + } + if ( LTSID < a ) { + value = providers[addr].data[currHeight].supply[LTSID]; + } else { + value = providers[addr].data[currHeight].supply[a]; + } + if ( globalFunds[a].supply > 0) { + reward += value * globalFunds[a].reward / globalFunds[a].supply * ( 100 - uint256(rate) ) / 100; + if ( providers[addr].data[currHeight].priv ) { + LTSID = providers[addr].data[currHeight].lastOwnSupplyID; + if ( LTSID < a ) { + value = providers[addr].data[currHeight].ownSupply[LTSID]; + } else { + value = providers[addr].data[currHeight].ownSupply[a]; + } + ownReward += value * globalFunds[a].reward / globalFunds[a].supply; + } + } + steps++; + } + } + } + } + providers[addr].data[currHeight].lastPaidRate = uint8(rate); + providers[addr].data[currHeight].paidUpTo = a-1; + if ( providers[addr].data[currHeight].isForRent ) { + providerReward = reward * rentRate / 100; + adminReward = reward - providerReward; + if ( providers[addr].data[currHeight].priv ) { providerReward += ownReward; } + } else { + providerReward = reward + ownReward; + } + } + function checkFloatingSupply(address providerAddress, uint256 providerHeight, bool neg, uint256 value) internal { + /* + Inner function for updating the database when some token change has happened. + In this case we are checking if despite the changes the provider is still entitled to the token emission. In case the legitimacy changes then the global supply should be set as well. + + @providerAddress Provider address. + @providerHeight Provider height. + @neg the change was negative or not + @value Rate of the change + */ + uint256 LSID = providers[providerAddress].data[providerHeight].lastSupplyID; + if ( currentSchellingRound != LSID ) { + if ( neg ) { + setRightForInterest( + providers[providerAddress].data[providerHeight].supply[LSID], + providers[providerAddress].data[providerHeight].supply[LSID] - value, + providers[providerAddress].data[providerHeight].priv + ); + providers[providerAddress].data[providerHeight].supply[currentSchellingRound] = providers[providerAddress].data[providerHeight].supply[LSID] - value; + } else { + setRightForInterest( + providers[providerAddress].data[providerHeight].supply[LSID], + providers[providerAddress].data[providerHeight].supply[LSID] + value, + providers[providerAddress].data[providerHeight].priv + ); + providers[providerAddress].data[providerHeight].supply[currentSchellingRound] = providers[providerAddress].data[providerHeight].supply[LSID] + value; + } + providers[providerAddress].data[providerHeight].lastSupplyID = currentSchellingRound; + } else { + if ( neg ) { + setRightForInterest( + getProviderCurrentSupply(providerAddress), + getProviderCurrentSupply(providerAddress) - value, + providers[providerAddress].data[providerHeight].priv + ); + providers[providerAddress].data[providerHeight].supply[currentSchellingRound] -= value; + } else { + setRightForInterest( + getProviderCurrentSupply(providerAddress), + getProviderCurrentSupply(providerAddress) + value, + providers[providerAddress].data[providerHeight].priv + ); + providers[providerAddress].data[providerHeight].supply[currentSchellingRound] += value; + } + } + } + function checkFloatingOwnSupply(address providerAddress, uint256 providerHeight, bool neg, uint256 value) internal { + /* + Inner function for updating the database in case token change has happened. + In this case we check if the provider despite the changes is still entitled to the token emission. + We just call this only if the private provider and it’s own capital bears emission. + + @providerAddress Provider address. + @providerHeight Provider height. + @neg Was the change negative? + @value Rate of the change. + */ + uint256 LSID = providers[providerAddress].data[providerHeight].lastOwnSupplyID; + if ( currentSchellingRound != LSID ) { + if ( neg ) { + setRightForInterest( + providers[providerAddress].data[providerHeight].ownSupply[LSID], + providers[providerAddress].data[providerHeight].ownSupply[LSID] - value, + true + ); + providers[providerAddress].data[providerHeight].ownSupply[currentSchellingRound] = providers[providerAddress].data[providerHeight].ownSupply[LSID] - value; + } else { + setRightForInterest( + providers[providerAddress].data[providerHeight].ownSupply[LSID], + providers[providerAddress].data[providerHeight].ownSupply[LSID] + value, + true + ); + providers[providerAddress].data[providerHeight].ownSupply[currentSchellingRound] = providers[providerAddress].data[providerHeight].ownSupply[LSID] + value; + } + providers[providerAddress].data[providerHeight].lastOwnSupplyID = currentSchellingRound; + } else { + if ( neg ) { + setRightForInterest( + getProviderCurrentSupply(providerAddress), + getProviderCurrentSupply(providerAddress) - value, + true + ); + providers[providerAddress].data[providerHeight].ownSupply[currentSchellingRound] -= value; + } else { + setRightForInterest( + getProviderCurrentSupply(providerAddress), + getProviderCurrentSupply(providerAddress) + value, + true + ); + providers[providerAddress].data[providerHeight].ownSupply[currentSchellingRound] += value; + } + } + } + function TEMath(uint256 a, uint256 b, bool neg) internal returns (uint256) { + /* + Inner function for the changes of the numbers + + @a First number + @b 2nd number + @neg Operation with numbers. If it is TRUE then subtraction, if it is FALSE then addition. + */ + if ( neg ) { return a-b; } + else { return a+b; } + } + function transferEvent_(address addr, uint256 value, bool neg) internal { + /* + Inner function for perceiving the changes of the balance and updating the database. + If the address is a provider and the balance is decreasing than can not let it go under the minimum level. + + @addr The address where the change happened. + @value Rate of the change. + @neg ype of the change. If it is TRUE then the balance has been decreased if it is FALSE then it has been increased. + */ + if ( clients[addr].providerAddress != 0 ) { + checkFloatingSupply(clients[addr].providerAddress, providers[clients[addr].providerAddress].currentHeight, ! neg, value); + if (clients[addr].lastSupplyID != currentSchellingRound) { + clients[addr].supply[currentSchellingRound] = TEMath(clients[addr].supply[clients[addr].lastSupplyID], value, neg); + clients[addr].lastSupplyID = currentSchellingRound; + } else { + clients[addr].supply[currentSchellingRound] = TEMath(clients[addr].supply[currentSchellingRound], value, neg); + } + } else if ( providers[addr].data[providers[addr].currentHeight].valid ) { + var currentHeight = providers[addr].currentHeight; + if ( neg ) { + uint256 balance = getTokenBalance(addr); + if ( providers[addr].data[currentHeight].priv ) { + require( balance-value >= minFundsForPrivate ); + } else { + require( balance-value >= minFundsForPublic ); + } + } + if ( providers[addr].data[currentHeight].priv ) { + checkFloatingOwnSupply(addr, currentHeight, ! neg, value); + } + } + } + function getTokenBalance(address addr) internal returns (uint256 balance) { + /* + Inner function in order to poll the token balance of the address. + + @addr Address + + @balance Balance of the address. + */ + var (_success, _balance) = moduleHandler(moduleHandlerAddress).balanceOf(addr); + require( _success ); + return _balance; + } + function checkICO() internal returns (bool isICO) { + /* + Inner function to check the ICO status. + + @isICO Is the ICO in proccess or not? + */ + var (_success, _isICO) = moduleHandler(moduleHandlerAddress).isICO(); + require( _success ); + return _isICO; + } + event EProviderOpen(address addr, uint256 height); + event EClientLost(address indexed client, address indexed provider, uint256 height, uint256 indexed value); + event ENewClient(address indexed client, address indexed provider, uint256 height, uint256 indexed value); + event EProviderClose(address indexed addr, uint256 height); + event EProviderDetailsChanged(address indexed addr, uint256 height, string website, string country, string info, uint8 rate, address admin); + event EReward(address indexed client, address indexed provider, uint256 clientreward, uint256 providerReward); +} diff --git a/test/compilationTests/corion/publisher.sol b/test/compilationTests/corion/publisher.sol new file mode 100644 index 00000000..e94b9a92 --- /dev/null +++ b/test/compilationTests/corion/publisher.sol @@ -0,0 +1,278 @@ +pragma solidity ^0.4.11;
+
+import "./announcementTypes.sol";
+import "./module.sol";
+import "./moduleHandler.sol";
+import "./safeMath.sol";
+
+contract publisher is announcementTypes, module, safeMath {
+ /*
+ module callbacks
+ */
+ function transferEvent(address from, address to, uint256 value) external returns (bool success) {
+ /*
+ Transaction completed. This function is available only for moduleHandler
+ If a transaction is carried out from or to an address which participated in the objection of an announcement, its objection purport is automatically set
+ */
+ require( super.isModuleHandler(msg.sender) );
+ uint256 announcementID;
+ uint256 a;
+ // need reverse lookup
+ for ( a=0 ; a<opponents[from].length ; a++ ) {
+ announcementID = opponents[msg.sender][a];
+ if ( announcements[announcementID].end < block.number && announcements[announcementID].open ) {
+ announcements[announcementID].oppositionWeight = safeSub(announcements[a].oppositionWeight, value);
+ }
+ }
+ for ( a=0 ; a<opponents[to].length ; a++ ) {
+ announcementID = opponents[msg.sender][a];
+ if ( announcements[announcementID].end < block.number && announcements[announcementID].open ) {
+ announcements[announcementID].oppositionWeight = safeAdd(announcements[a].oppositionWeight, value);
+ }
+ }
+ return true;
+ }
+
+ /*
+ Pool
+ */
+
+ uint256 public minAnnouncementDelay = 40320;
+ uint256 public minAnnouncementDelayOnICO = 17280;
+ uint8 public oppositeRate = 33;
+
+ struct announcements_s {
+ announcementType Type;
+ uint256 start;
+ uint256 end;
+ bool open;
+ string announcement;
+ string link;
+ bool oppositable;
+ uint256 oppositionWeight;
+ bool result;
+
+ string _str;
+ uint256 _uint;
+ address _addr;
+ }
+ mapping(uint256 => announcements_s) public announcements;
+ uint256 announcementsLength = 1;
+
+ mapping (address => uint256[]) public opponents;
+
+ function publisher(address moduleHandler) {
+ /*
+ Installation function. The installer will be registered in the admin list automatically
+
+ @moduleHandler Address of moduleHandler
+ */
+ super.registerModuleHandler(moduleHandler);
+ }
+
+ function Announcements(uint256 id) public constant returns (uint256 Type, uint256 Start, uint256 End, bool Closed, string Announcement, string Link, bool Opposited, string _str, uint256 _uint, address _addr) {
+ /*
+ Announcement data query
+
+ @id Its identification
+
+ @Type Subject of announcement
+ @Start Height of announcement block
+ @End Planned completion of announcement
+ @Closed Closed or not
+ @Announcement Announcement text
+ @Link Link perhaps to a Forum
+ @Opposited Objected or not
+ @_str Text value
+ @_uint Number value
+ @_addr Address value
+ */
+ Type = uint256(announcements[id].Type);
+ Start = announcements[id].start;
+ End = announcements[id].end;
+ Closed = ! announcements[id].open;
+ Announcement = announcements[id].announcement;
+ Link = announcements[id].link;
+ if ( checkOpposited(announcements[id].oppositionWeight, announcements[id].oppositable) ) {
+ Opposited = true;
+ }
+ _str = announcements[id]._str;
+ _uint = announcements[id]._uint;
+ _addr = announcements[id]._addr;
+ }
+
+ function checkOpposited(uint256 weight, bool oppositable) public constant returns (bool success) {
+ /*
+ Veto check
+
+ @weight Purport of objections so far
+ @oppositable Opposable at all
+
+ @success Opposed or not
+ */
+ if ( ! oppositable ) { return false; }
+ var (_success, _amount) = moduleHandler(moduleHandlerAddress).totalSupply();
+ require( _success );
+ return _amount * oppositeRate / 100 > weight;
+ }
+
+ function newAnnouncement(announcementType Type, string Announcement, string Link, bool Oppositable, string _str, uint256 _uint, address _addr) onlyOwner external {
+ /*
+ New announcement. Can be called only by those in the admin list
+
+ @Type Topic of announcement
+ @Start height of announcement block
+ @End planned completion of announcement
+ @Closed Completed or not
+ @Announcement Announcement text
+ @Link link to a Forum
+ @Opposition opposed or not
+ @_str text box
+ @_uint number box
+ @_addr address box
+ */
+ announcementsLength++;
+ announcements[announcementsLength].Type = Type;
+ announcements[announcementsLength].start = block.number;
+ if ( checkICO() ) {
+ announcements[announcementsLength].end = block.number + minAnnouncementDelayOnICO;
+ } else {
+ announcements[announcementsLength].end = block.number + minAnnouncementDelay;
+ }
+ announcements[announcementsLength].open = true;
+ announcements[announcementsLength].announcement = Announcement;
+ announcements[announcementsLength].link = Link;
+ announcements[announcementsLength].oppositable = Oppositable;
+ announcements[announcementsLength].oppositionWeight = 0;
+ announcements[announcementsLength].result = false;
+ announcements[announcementsLength]._str = _str;
+ announcements[announcementsLength]._uint = _uint;
+ announcements[announcementsLength]._addr = _addr;
+ ENewAnnouncement(announcementsLength, Type);
+ }
+
+ function closeAnnouncement(uint256 id) onlyOwner external {
+ /*
+ Close announcement. It can be closed only by those in the admin list. Windup is allowed only after the announcement is completed.
+
+ @id Announcement identification
+ */
+ require( announcements[id].open && announcements[id].end < block.number );
+ if ( ! checkOpposited(announcements[id].oppositionWeight, announcements[id].oppositable) ) {
+ announcements[id].result = true;
+ if ( announcements[id].Type == announcementType.newModule ) {
+ require( moduleHandler(moduleHandlerAddress).newModule(announcements[id]._str, announcements[id]._addr, true, true) );
+ } else if ( announcements[id].Type == announcementType.dropModule ) {
+ require( moduleHandler(moduleHandlerAddress).dropModule(announcements[id]._str, true) );
+ } else if ( announcements[id].Type == announcementType.replaceModule ) {
+ require( moduleHandler(moduleHandlerAddress).replaceModule(announcements[id]._str, announcements[id]._addr, true) );
+ } else if ( announcements[id].Type == announcementType.replaceModuleHandler) {
+ require( moduleHandler(moduleHandlerAddress).replaceModuleHandler(announcements[id]._addr) );
+ } else if ( announcements[id].Type == announcementType.transactionFeeRate ||
+ announcements[id].Type == announcementType.transactionFeeMin ||
+ announcements[id].Type == announcementType.transactionFeeMax ||
+ announcements[id].Type == announcementType.transactionFeeBurn ) {
+ require( moduleHandler(moduleHandlerAddress).configureModule("token", announcements[id].Type, announcements[id]._uint) );
+ } else if ( announcements[id].Type == announcementType.providerPublicFunds ||
+ announcements[id].Type == announcementType.providerPrivateFunds ||
+ announcements[id].Type == announcementType.providerPrivateClientLimit ||
+ announcements[id].Type == announcementType.providerPublicMinRate ||
+ announcements[id].Type == announcementType.providerPublicMaxRate ||
+ announcements[id].Type == announcementType.providerPrivateMinRate ||
+ announcements[id].Type == announcementType.providerPrivateMaxRate ||
+ announcements[id].Type == announcementType.providerGasProtect ||
+ announcements[id].Type == announcementType.providerInterestMinFunds ||
+ announcements[id].Type == announcementType.providerRentRate ) {
+ require( moduleHandler(moduleHandlerAddress).configureModule("provider", announcements[id].Type, announcements[id]._uint) );
+ } else if ( announcements[id].Type == announcementType.schellingRoundBlockDelay ||
+ announcements[id].Type == announcementType.schellingCheckRounds ||
+ announcements[id].Type == announcementType.schellingCheckAboves ||
+ announcements[id].Type == announcementType.schellingRate ) {
+ require( moduleHandler(moduleHandlerAddress).configureModule("schelling", announcements[id].Type, announcements[id]._uint) );
+ } else if ( announcements[id].Type == announcementType.publisherMinAnnouncementDelay) {
+ minAnnouncementDelay = announcements[id]._uint;
+ } else if ( announcements[id].Type == announcementType.publisherOppositeRate) {
+ oppositeRate = uint8(announcements[id]._uint);
+ }
+ }
+ announcements[id].end = block.number;
+ announcements[id].open = false;
+ }
+
+ function oppositeAnnouncement(uint256 id) external {
+ /*
+ Opposition of announcement
+ If announcement is opposable, anyone owning a token can oppose it
+ Opposition is automatically with the total amount of tokens
+ If the quantity of his tokens changes, the purport of his opposition changes automatically
+ The prime time is the windup of the announcement, because this is the moment when the number of tokens in opposition are counted.
+ One address is entitled to be in oppositon only once. An opposition cannot be withdrawn.
+ Running announcements can be opposed only.
+
+ @id Announcement identification
+ */
+ uint256 newArrayID = 0;
+ bool foundEmptyArrayID = false;
+ require( announcements[id].open );
+ require( announcements[id].oppositable );
+ for ( uint256 a=0 ; a<opponents[msg.sender].length ; a++ ) {
+ require( opponents[msg.sender][a] != id );
+ if ( ! announcements[opponents[msg.sender][a]].open) {
+ delete opponents[msg.sender][a];
+ if ( ! foundEmptyArrayID ) {
+ foundEmptyArrayID = true;
+ newArrayID = a;
+ }
+ }
+ if ( ! foundEmptyArrayID ) {
+ foundEmptyArrayID = true;
+ newArrayID = a;
+ }
+ }
+ var (_success, _balance) = moduleHandler(moduleHandlerAddress).balanceOf(msg.sender);
+ require( _success );
+ require( _balance > 0);
+ if ( foundEmptyArrayID ) {
+ opponents[msg.sender][newArrayID] = id;
+ } else {
+ opponents[msg.sender].push(id);
+ }
+ announcements[id].oppositionWeight += _balance;
+ EOppositeAnnouncement(id, msg.sender, _balance);
+ }
+
+ function invalidateAnnouncement(uint256 id) onlyOwner external {
+ /*
+ Withdraw announcement. Only those in the admin list can withdraw it.
+
+ @id Announcement identification
+ */
+ require( announcements[id].open );
+ announcements[id].end = block.number;
+ announcements[id].open = false;
+ EInvalidateAnnouncement(id);
+ }
+
+ modifier onlyOwner() {
+ /*
+ Only the owner is allowed to call it.
+ */
+ require( moduleHandler(moduleHandlerAddress).owners(msg.sender) );
+ _;
+ }
+
+ function checkICO() internal returns (bool isICO) {
+ /*
+ Inner function to check the ICO status.
+ @bool Is the ICO in proccess or not?
+ */
+ var (_success, _isICO) = moduleHandler(moduleHandlerAddress).isICO();
+ require( _success );
+ return _isICO;
+ }
+
+ event ENewAnnouncement(uint256 id, announcementType typ);
+ event EOppositeAnnouncement(uint256 id, address addr, uint256 value);
+ event EInvalidateAnnouncement(uint256 id);
+ event ECloseAnnouncement(uint256 id);
+}
diff --git a/test/compilationTests/corion/safeMath.sol b/test/compilationTests/corion/safeMath.sol new file mode 100644 index 00000000..9e27d379 --- /dev/null +++ b/test/compilationTests/corion/safeMath.sol @@ -0,0 +1,33 @@ +pragma solidity ^0.4.11; + +contract safeMath { + function safeAdd(uint256 a, uint256 b) internal returns(uint256) { + /* + Biztonsagos hozzadas. Tulcsordulas elleni vedelem. + A vegeredmeny nem lehet kevesebb mint az @a, ha igen megall a kod. + + @a Amihez hozzaadni kell + @b Amennyit hozzaadni kell. + @uint256 Vegeredmeny. + */ + if ( b > 0 ) { + assert( a + b > a ); + } + return a + b; + } + + function safeSub(uint256 a, uint256 b) internal returns(uint256) { + /* + Biztonsagos kivonas. Tulcsordulas elleni vedelem. + A vegeredmeny nem lehet tobb mint az @a, ha igen megall a kod. + + @a Amibol kivonni kell. + @b Amennyit kivonni kell. + @uint256 Vegeredmeny. + */ + if ( b > 0 ) { + assert( a - b < a ); + } + return a - b; + } +}
\ No newline at end of file diff --git a/test/compilationTests/corion/schelling.sol b/test/compilationTests/corion/schelling.sol new file mode 100644 index 00000000..8c8e093c --- /dev/null +++ b/test/compilationTests/corion/schelling.sol @@ -0,0 +1,577 @@ +pragma solidity ^0.4.11; + +import "./announcementTypes.sol"; +import "./module.sol"; +import "./moduleHandler.sol"; +import "./safeMath.sol"; + +contract schellingVars { + /* + Common enumerations and structures of the Schelling and Database contract. + */ + enum voterStatus { + base, + afterPrepareVote, + afterSendVoteOk, + afterSendVoteBad + } + struct _rounds { + uint256 totalAboveWeight; + uint256 totalBelowWeight; + uint256 reward; + uint256 blockHeight; + bool voted; + } + struct _voter { + uint256 roundID; + bytes32 hash; + voterStatus status; + bool voteResult; + uint256 rewards; + } +} + +contract schellingDB is safeMath, schellingVars { + /* + Schelling database contract. + */ + address private owner; + function replaceOwner(address newOwner) external returns(bool) { + require( owner == 0x00 || msg.sender == owner ); + owner = newOwner; + return true; + } + modifier isOwner { require( msg.sender == owner ); _; } + /* + Constructor + */ + function schellingDB() { + rounds.length = 2; + rounds[0].blockHeight = block.number; + currentSchellingRound = 1; + } + /* + Funds + */ + mapping(address => uint256) private funds; + function getFunds(address _owner) constant returns(bool, uint256) { + return (true, funds[_owner]); + } + function setFunds(address _owner, uint256 _amount) isOwner external returns(bool) { + funds[_owner] = _amount; + return true; + } + /* + Rounds + */ + _rounds[] private rounds; + function getRound(uint256 _id) constant returns(bool, uint256, uint256, uint256, uint256, bool) { + if ( rounds.length <= _id ) { return (false, 0, 0, 0, 0, false); } + else { return (true, rounds[_id].totalAboveWeight, rounds[_id].totalBelowWeight, rounds[_id].reward, rounds[_id].blockHeight, rounds[_id].voted); } + } + function pushRound(uint256 _totalAboveWeight, uint256 _totalBelowWeight, uint256 _reward, uint256 _blockHeight, bool _voted) isOwner external returns(bool, uint256) { + return (true, rounds.push(_rounds(_totalAboveWeight, _totalBelowWeight, _reward, _blockHeight, _voted))); + } + function setRound(uint256 _id, uint256 _totalAboveWeight, uint256 _totalBelowWeight, uint256 _reward, uint256 _blockHeight, bool _voted) isOwner external returns(bool) { + rounds[_id] = _rounds(_totalAboveWeight, _totalBelowWeight, _reward, _blockHeight, _voted); + return true; + } + function getCurrentRound() constant returns(bool, uint256) { + return (true, rounds.length-1); + } + /* + Voter + */ + mapping(address => _voter) private voter; + function getVoter(address _owner) constant returns(bool success, uint256 roundID, + bytes32 hash, voterStatus status, bool voteResult, uint256 rewards) { + roundID = voter[_owner].roundID; + hash = voter[_owner].hash; + status = voter[_owner].status; + voteResult = voter[_owner].voteResult; + rewards = voter[_owner].rewards; + success = true; + } + function setVoter(address _owner, uint256 _roundID, bytes32 _hash, voterStatus _status, bool _voteResult, uint256 _rewards) isOwner external returns(bool) { + voter[_owner] = _voter( + _roundID, + _hash, + _status, + _voteResult, + _rewards + ); + return true; + } + /* + Schelling Token emission + */ + mapping(uint256 => uint256) private schellingExpansion; + function getSchellingExpansion(uint256 _id) constant returns(bool, uint256) { + return (true, schellingExpansion[_id]); + } + function setSchellingExpansion(uint256 _id, uint256 _expansion) isOwner external returns(bool) { + schellingExpansion[_id] = _expansion; + return true; + } + /* + Current Schelling Round + */ + uint256 private currentSchellingRound; + function setCurrentSchellingRound(uint256 _id) isOwner external returns(bool) { + currentSchellingRound = _id; + return true; + } + function getCurrentSchellingRound() constant returns(bool, uint256) { + return (true, currentSchellingRound); + } +} + +contract schelling is module, announcementTypes, schellingVars { + /* + Schelling contract + */ + /* + module callbacks + */ + function replaceModule(address addr) external returns (bool) { + require( super.isModuleHandler(msg.sender) ); + require( db.replaceOwner(addr) ); + super._replaceModule(addr); + return true; + } + function transferEvent(address from, address to, uint256 value) external returns (bool) { + /* + Transaction completed. This function can be called only by the ModuleHandler. + If this contract is the receiver, the amount will be added to the prize pool of the current round. + + @from From who + @to To who + @value Amount + @bool Was the transaction succesfull? + */ + require( super.isModuleHandler(msg.sender) ); + if ( to == address(this) ) { + var currentRound = getCurrentRound(); + var round = getRound(currentRound); + round.reward += value; + setRound(currentRound, round); + } + return true; + } + modifier isReady { + var (_success, _active) = super.isActive(); + require( _success && _active ); + _; + } + /* + Schelling database functions. + */ + function getFunds(address addr) internal returns (uint256) { + var (a, b) = db.getFunds(addr); + require( a ); + return b; + } + function setFunds(address addr, uint256 amount) internal { + require( db.setFunds(addr, amount) ); + } + function setVoter(address owner, _voter voter) internal { + require( db.setVoter(owner, + voter.roundID, + voter.hash, + voter.status, + voter.voteResult, + voter.rewards + ) ); + } + function getVoter(address addr) internal returns (_voter) { + var (a, b, c, d, e, f) = db.getVoter(addr); + require( a ); + return _voter(b, c, d, e, f); + } + function setRound(uint256 id, _rounds round) internal { + require( db.setRound(id, + round.totalAboveWeight, + round.totalBelowWeight, + round.reward, + round.blockHeight, + round.voted + ) ); + } + function pushRound(_rounds round) internal returns (uint256) { + var (a, b) = db.pushRound( + round.totalAboveWeight, + round.totalBelowWeight, + round.reward, + round.blockHeight, + round.voted + ); + require( a ); + return b; + } + function getRound(uint256 id) internal returns (_rounds) { + var (a, b, c, d, e, f) = db.getRound(id); + require( a ); + return _rounds(b, c, d, e, f); + } + function getCurrentRound() internal returns (uint256) { + var (a, b) = db.getCurrentRound(); + require( a ); + return b; + } + function setCurrentSchellingRound(uint256 id) internal { + require( db.setCurrentSchellingRound(id) ); + } + function getCurrentSchellingRound() internal returns(uint256) { + var (a, b) = db.getCurrentSchellingRound(); + require( a ); + return b; + } + function setSchellingExpansion(uint256 id, uint256 amount) internal { + require( db.setSchellingExpansion(id, amount) ); + } + function getSchellingExpansion(uint256 id) internal returns(uint256) { + var (a, b) = db.getSchellingExpansion(id); + require( a ); + return b; + } + /* + Schelling module + */ + uint256 private roundBlockDelay = 720; + uint8 private interestCheckRounds = 7; + uint8 private interestCheckAboves = 4; + uint256 private interestRate = 300; + uint256 private interestRateM = 1e3; + + bytes1 public aboveChar = 0x31; + bytes1 public belowChar = 0x30; + schellingDB private db; + + function schelling(address _moduleHandler, address _db, bool _forReplace) { + /* + Installation function. + + @_moduleHandler Address of ModuleHandler. + @_db Address of the database. + @_forReplace This address will be replaced with the old one or not. + @_icoExpansionAddress This address can turn schelling runds during ICO. + */ + db = schellingDB(_db); + super.registerModuleHandler(_moduleHandler); + if ( ! _forReplace ) { + require( db.replaceOwner(this) ); + } + } + function configure(announcementType a, uint256 b) external returns(bool) { + /* + Can be called only by the ModuleHandler. + + @a Sort of configuration + @b Value + */ + require( super.isModuleHandler(msg.sender) ); + if ( a == announcementType.schellingRoundBlockDelay ) { roundBlockDelay = b; } + else if ( a == announcementType.schellingCheckRounds ) { interestCheckRounds = uint8(b); } + else if ( a == announcementType.schellingCheckAboves ) { interestCheckAboves = uint8(b); } + else if ( a == announcementType.schellingRate ) { interestRate = b; } + else { return false; } + return true; + } + function prepareVote(bytes32 votehash, uint256 roundID) isReady noContract external { + /* + Initializing manual vote. + Only the hash of vote will be sent. (Envelope sending). + The address must be in default state, that is there are no vote in progress. + Votes can be sent only on the actually Schelling round. + + @votehash Hash of the vote + @roundID Number of Schelling round + */ + nextRound(); + + var currentRound = getCurrentRound(); + var round = getRound(currentRound); + _voter memory voter; + uint256 funds; + + require( roundID == currentRound ); + + voter = getVoter(msg.sender); + funds = getFunds(msg.sender); + + require( funds > 0 ); + require( voter.status == voterStatus.base ); + voter.roundID = currentRound; + voter.hash = votehash; + voter.status = voterStatus.afterPrepareVote; + + setVoter(msg.sender, voter); + round.voted = true; + + setRound(currentRound, round); + } + function sendVote(string vote) isReady noContract external { + /* + Check vote (Envelope opening) + Only the sent “envelopes” can be opened. + Envelope opening only in the next Schelling round. + If the vote invalid, the deposit will be lost. + If the “envelope” was opened later than 1,5 Schelling round, the vote is automatically invalid, and deposit can be lost. + Lost deposits will be 100% burned. + + @vote Hash of the content of the vote. + */ + nextRound(); + + var currentRound = getCurrentRound(); + _rounds memory round; + _voter memory voter; + uint256 funds; + + bool lostEverything; + voter = getVoter(msg.sender); + round = getRound(voter.roundID); + funds = getFunds(msg.sender); + + require( voter.status == voterStatus.afterPrepareVote ); + require( voter.roundID < currentRound ); + if ( sha3(vote) == voter.hash ) { + delete voter.hash; + if (round.blockHeight+roundBlockDelay/2 >= block.number) { + if ( bytes(vote)[0] == aboveChar ) { + voter.status = voterStatus.afterSendVoteOk; + round.totalAboveWeight += funds; + voter.voteResult = true; + } else if ( bytes(vote)[0] == belowChar ) { + voter.status = voterStatus.afterSendVoteOk; + round.totalBelowWeight += funds; + } else { lostEverything = true; } + } else { + voter.status = voterStatus.afterSendVoteBad; + } + } else { lostEverything = true; } + if ( lostEverything ) { + require( moduleHandler(moduleHandlerAddress).burn(address(this), funds) ); + delete funds; + delete voter.status; + } + + setVoter(msg.sender, voter); + setRound(voter.roundID, round); + setFunds(msg.sender, funds); + } + function checkVote() isReady noContract external { + /* + Checking votes. + Vote checking only after the envelope opening Schelling round. + Deposit will be lost, if the vote wrong, or invalid. + The right votes take share of deposits. + */ + nextRound(); + + var currentRound = getCurrentRound(); + _rounds memory round; + _voter memory voter; + uint256 funds; + + voter = getVoter(msg.sender); + round = getRound(voter.roundID); + funds = getFunds(msg.sender); + + require( voter.status == voterStatus.afterSendVoteOk || + voter.status == voterStatus.afterSendVoteBad ); + if ( round.blockHeight+roundBlockDelay/2 <= block.number ) { + if ( isWinner(round, voter.voteResult) && voter.status == voterStatus.afterSendVoteOk ) { + voter.rewards += funds * round.reward / getRoundWeight(round.totalAboveWeight, round.totalBelowWeight); + } else { + require( moduleHandler(moduleHandlerAddress).burn(address(this), funds) ); + delete funds; + } + delete voter.status; + delete voter.roundID; + } else { throw; } + + setVoter(msg.sender, voter); + setFunds(msg.sender, funds); + } + function getRewards(address beneficiary) isReady noContract external { + /* + Redeem of prize. + The prizes will be collected here, and with this function can be transferred to the account of the user. + Optionally there can be an address of a beneficiary added, which address the prize will be sent to. Without beneficiary, the owner is the default address. + Prize will be sent from the Schelling address without any transaction fee. + + @beneficiary Address of the beneficiary + */ + var voter = getVoter(msg.sender); + var funds = getFunds(msg.sender); + + address _beneficiary = msg.sender; + if (beneficiary != 0x0) { _beneficiary = beneficiary; } + uint256 reward; + require( voter.rewards > 0 ); + require( voter.status == voterStatus.base ); + reward = voter.rewards; + delete voter.rewards; + require( moduleHandler(moduleHandlerAddress).transfer(address(this), _beneficiary, reward, false) ); + + setVoter(msg.sender, voter); + } + function checkReward() public constant returns (uint256 reward) { + /* + Withdraw of the amount of the prize (it’s only information). + + @reward Prize + */ + var voter = getVoter(msg.sender); + return voter.rewards; + } + function nextRound() internal returns (bool) { + /* + Inside function, checks the time of the Schelling round and if its needed, creates a new Schelling round. + */ + var currentRound = getCurrentRound(); + var round = getRound(currentRound); + _rounds memory newRound; + _rounds memory prevRound; + var currentSchellingRound = getCurrentSchellingRound(); + + if ( round.blockHeight+roundBlockDelay > block.number) { return false; } + + newRound.blockHeight = block.number; + if ( ! round.voted ) { + newRound.reward = round.reward; + } + uint256 aboves; + for ( uint256 a=currentRound ; a>=currentRound-interestCheckRounds ; a-- ) { + if (a == 0) { break; } + prevRound = getRound(a); + if ( prevRound.totalAboveWeight > prevRound.totalBelowWeight ) { aboves++; } + } + uint256 expansion; + if ( aboves >= interestCheckAboves ) { + expansion = getTotalSupply() * interestRate / interestRateM / 100; + } + + currentSchellingRound++; + + pushRound(newRound); + setSchellingExpansion(currentSchellingRound, expansion); + require( moduleHandler(moduleHandlerAddress).broadcastSchellingRound(currentSchellingRound, expansion) ); + return true; + } + function addFunds(uint256 amount) isReady noContract external { + /* + Deposit taking. + Every participant entry with his own deposit. + In case of wrong vote only this amount of deposit will be burn. + The deposit will be sent to the address of Schelling, charged with transaction fee. + + @amount Amount of deposit. + */ + var voter = getVoter(msg.sender); + var funds = getFunds(msg.sender); + + var (a, b) = moduleHandler(moduleHandlerAddress).isICO(); + require( b && b ); + require( voter.status == voterStatus.base ); + require( amount > 0 ); + require( moduleHandler(moduleHandlerAddress).transfer(msg.sender, address(this), amount, true) ); + funds += amount; + + setFunds(msg.sender, funds); + } + function getFunds() isReady noContract external { + /* + Deposit withdrawn. + If the deposit isn’t lost, it can be withdrawn. + By withdrawn, the deposit will be sent from Schelling address to the users address, charged with transaction fee.. + */ + var voter = getVoter(msg.sender); + var funds = getFunds(msg.sender); + + require( funds > 0 ); + require( voter.status == voterStatus.base ); + setFunds(msg.sender, 0); + + require( moduleHandler(moduleHandlerAddress).transfer(address(this), msg.sender, funds, true) ); + } + function getCurrentSchellingRoundID() public constant returns (uint256) { + /* + Number of actual Schelling round. + + @uint256 Schelling round. + */ + return getCurrentSchellingRound(); + } + function getSchellingRound(uint256 id) public constant returns (uint256 expansion) { + /* + Amount of token emission of the Schelling round. + + @id Number of Schelling round + @expansion Amount of token emission + */ + return getSchellingExpansion(id); + } + function getRoundWeight(uint256 aboveW, uint256 belowW) internal returns (uint256) { + /* + Inside function for calculating the weights of the votes. + + @aboveW Weight of votes: ABOVE + @belowW Weight of votes: BELOW + @uint256 Calculatet weight + */ + if ( aboveW == belowW ) { + return aboveW + belowW; + } else if ( aboveW > belowW ) { + return aboveW; + } else if ( aboveW < belowW) { + return belowW; + } + } + function isWinner(_rounds round, bool aboveVote) internal returns (bool) { + /* + Inside function for calculating the result of the game. + + @round Structure of Schelling round. + @aboveVote Is the vote = ABOVE or not + @bool Result + */ + if ( round.totalAboveWeight == round.totalBelowWeight || + ( round.totalAboveWeight > round.totalBelowWeight && aboveVote ) ) { + return true; + } + return false; + } + + function getTotalSupply() internal returns (uint256 amount) { + /* + Inside function for querying the whole amount of the tokens. + + @uint256 Whole token amount + */ + var (_success, _amount) = moduleHandler(moduleHandlerAddress).totalSupply(); + require( _success ); + return _amount; + } + + function getTokenBalance(address addr) internal returns (uint256 balance) { + /* + Inner function in order to poll the token balance of the address. + + @addr Address + + @balance Balance of the address. + */ + var (_success, _balance) = moduleHandler(moduleHandlerAddress).balanceOf(addr); + require( _success ); + return _balance; + } + + modifier noContract { + /* + Contract can’t call this function, only a natural address. + */ + require( msg.sender == tx.origin ); _; + } +} diff --git a/test/compilationTests/corion/token.sol b/test/compilationTests/corion/token.sol new file mode 100644 index 00000000..3aa0bf23 --- /dev/null +++ b/test/compilationTests/corion/token.sol @@ -0,0 +1,518 @@ +pragma solidity ^0.4.11; + +import "./announcementTypes.sol"; +import "./safeMath.sol"; +import "./module.sol"; +import "./moduleHandler.sol"; +import "./tokenDB.sol"; + +contract thirdPartyContractAbstract { + function receiveCorionToken(address, uint256, bytes) external returns (bool, uint256) {} + function approvedCorionToken(address, uint256, bytes) external returns (bool) {} +} + +contract token is safeMath, module, announcementTypes { + /* + module callbacks + */ + function replaceModule(address addr) external returns (bool success) { + require( super.isModuleHandler(msg.sender) ); + require( db.replaceOwner(addr) ); + super._replaceModule(addr); + return true; + } + modifier isReady { + var (_success, _active) = super.isActive(); + require( _success && _active ); + _; + } + /** + * + * @title Corion Platform Token + * @author iFA @ Corion Platform + * + */ + string public name = "Corion"; + string public symbol = "COR"; + uint8 public decimals = 6; + + tokenDB public db; + address public icoAddr; + uint256 public transactionFeeRate = 20; + uint256 public transactionFeeRateM = 1e3; + uint256 public transactionFeeMin = 20000; + uint256 public transactionFeeMax = 5000000; + uint256 public transactionFeeBurn = 80; + address public exchangeAddress; + bool public isICO = true; + + mapping(address => bool) public genesis; + + function token(bool forReplace, address moduleHandler, address dbAddr, address icoContractAddr, address exchangeContractAddress, address[] genesisAddr, uint256[] genesisValue) payable { + /* + Installation function + + When _icoAddr is defined, 0.2 ether has to be attached as many times as many genesis addresses are given + + @forReplace This address will be replaced with the old one or not. + @moduleHandler Modulhandler's address + @dbAddr Address of database + @icoContractAddr Address of ICO contract + @exchangeContractAddress Address of Market in order to buy gas during ICO + @genesisAddr Array of Genesis addresses + @genesisValue Array of balance of genesis addresses + */ + super.registerModuleHandler(moduleHandler); + require( dbAddr != 0x00 ); + require( icoContractAddr != 0x00 ); + require( exchangeContractAddress != 0x00 ); + db = tokenDB(dbAddr); + icoAddr = icoContractAddr; + exchangeAddress = exchangeContractAddress; + isICO = ! forReplace; + if ( ! forReplace ) { + require( db.replaceOwner(this) ); + assert( genesisAddr.length == genesisValue.length ); + require( this.balance >= genesisAddr.length * 0.2 ether ); + for ( uint256 a=0 ; a<genesisAddr.length ; a++ ) { + genesis[genesisAddr[a]] = true; + require( db.increase(genesisAddr[a], genesisValue[a]) ); + if ( ! genesisAddr[a].send(0.2 ether) ) {} + Mint(genesisAddr[a], genesisValue[a]); + } + } + } + + function closeIco() external returns (bool success) { + /* + ICO finished. It can be called only by ICO contract + + @success Was the Function successful? + */ + require( msg.sender == icoAddr ); + isICO = false; + return true; + } + + /** + * @notice `msg.sender` approves `spender` to spend `amount` tokens on its behalf. + * @param spender The address of the account able to transfer the tokens + * @param amount The amount of tokens to be approved for transfer + * @param nonce The transaction count of the authorised address + * @return True if the approval was successful + */ + function approve(address spender, uint256 amount, uint256 nonce) isReady external returns (bool success) { + /* + Authorise another address to use a certain quantity of the authorising owner’s balance + + @spender Address of authorised party + @amount Token quantity + @nonce Transaction count + + @success Was the Function successful? + */ + _approve(spender, amount, nonce); + return true; + } + + /** + * @notice `msg.sender` approves `spender` to spend `amount` tokens on its behalf and notify the spender from your approve with your `extraData` data. + * @param spender The address of the account able to transfer the tokens + * @param amount The amount of tokens to be approved for transfer + * @param nonce The transaction count of the authorised address + * @param extraData Data to give forward to the receiver + * @return True if the approval was successful + */ + function approveAndCall(address spender, uint256 amount, uint256 nonce, bytes extraData) isReady external returns (bool success) { + /* + Authorise another address to use a certain quantity of the authorising owner’s balance + Following the transaction the receiver address `approvedCorionToken` function is called by the given data + + @spender Authorized address + @amount Token quantity + @extraData Extra data to be received by the receiver + @nonce Transaction count + + @success Was the Function successful? + */ + _approve(spender, amount, nonce); + require( thirdPartyContractAbstract(spender).approvedCorionToken(msg.sender, amount, extraData) ); + return true; + } + + function _approve(address spender, uint256 amount, uint256 nonce) internal { + /* + Internal Function to authorise another address to use a certain quantity of the authorising owner’s balance. + If the transaction count not match the authorise fails. + + @spender Address of authorised party + @amount Token quantity + @nonce Transaction count + */ + require( msg.sender != spender ); + require( db.balanceOf(msg.sender) >= amount ); + require( db.setAllowance(msg.sender, spender, amount, nonce) ); + Approval(msg.sender, spender, amount); + } + + function allowance(address owner, address spender) constant returns (uint256 remaining, uint256 nonce) { + /* + Get the quantity of tokens given to be used + + @owner Authorising address + @spender Authorised address + + @remaining Tokens to be spent + @nonce Transaction count + */ + var (_success, _remaining, _nonce) = db.getAllowance(owner, spender); + require( _success ); + return (_remaining, _nonce); + } + + /** + * @notice Send `amount` Corion tokens to `to` from `msg.sender` + * @param to The address of the recipient + * @param amount The amount of tokens to be transferred + * @return Whether the transfer was successful or not + */ + function transfer(address to, uint256 amount) isReady external returns (bool success) { + /* + Start transaction, token is sent from caller’s address to receiver’s address + Transaction fee is to be deducted. + If receiver is not a natural address but a person, he will be called + + @to To who + @amount Quantity + + @success Was the Function successful? + */ + bytes memory _data; + if ( isContract(to) ) { + _transferToContract(msg.sender, to, amount, _data); + } else { + _transfer( msg.sender, to, amount, true); + } + Transfer(msg.sender, to, amount, _data); + return true; + } + + /** + * @notice Send `amount` tokens to `to` from `from` on the condition it is approved by `from` + * @param from The address holding the tokens being transferred + * @param to The address of the recipient + * @param amount The amount of tokens to be transferred + * @return True if the transfer was successful + */ + function transferFrom(address from, address to, uint256 amount) isReady external returns (bool success) { + /* + Start transaction to send a quantity from a given address to another address. (approve / allowance). This can be called only by the address approved in advance + Transaction fee is to be deducted + If receiver is not a natural address but a person, he will be called + + @from From who. + @to To who + @amount Quantity + + @success Was the Function successful? + */ + if ( from != msg.sender ) { + var (_success, _reamining, _nonce) = db.getAllowance(from, msg.sender); + require( _success ); + _reamining = safeSub(_reamining, amount); + _nonce = safeAdd(_nonce, 1); + require( db.setAllowance(from, msg.sender, _reamining, _nonce) ); + AllowanceUsed(msg.sender, from, amount); + } + bytes memory _data; + if ( isContract(to) ) { + _transferToContract(from, to, amount, _data); + } else { + _transfer( from, to, amount, true); + } + Transfer(from, to, amount, _data); + return true; + } + + /** + * @notice Send `amount` tokens to `to` from `from` on the condition it is approved by `from` + * @param from The address holding the tokens being transferred + * @param to The address of the recipient + * @param amount The amount of tokens to be transferred + * @return True if the transfer was successful + */ + function transferFromByModule(address from, address to, uint256 amount, bool fee) isReady external returns (bool success) { + /* + Start transaction to send a quantity from a given address to another address + Only ModuleHandler can call it + + @from From who + @to To who. + @amount Quantity + @fee Deduct transaction fee - yes or no? + + @success Was the Function successful? + */ + bytes memory _data; + require( super.isModuleHandler(msg.sender) ); + _transfer( from, to, amount, fee); + Transfer(from, to, amount, _data); + return true; + } + + /** + * @notice Send `amount` Corion tokens to `to` from `msg.sender` and notify the receiver from your transaction with your `extraData` data + * @param to The contract address of the recipient + * @param amount The amount of tokens to be transferred + * @param extraData Data to give forward to the receiver + * @return Whether the transfer was successful or not + */ + function transfer(address to, uint256 amount, bytes extraData) isReady external returns (bool success) { + /* + Start transaction to send a quantity from a given address to another address + After transaction the function `receiveCorionToken`of the receiver is called by the given data + When sending an amount, it is possible the total amount cannot be processed, the remaining amount is sent back with no fee charged + + @to To who. + @amount Quantity + @extraData Extra data the receiver will get + + @success Was the Function successful? + */ + if ( isContract(to) ) { + _transferToContract(msg.sender, to, amount, extraData); + } else { + _transfer( msg.sender, to, amount, true); + } + Transfer(msg.sender, to, amount, extraData); + return true; + } + + function _transferToContract(address from, address to, uint256 amount, bytes extraData) internal { + /* + Internal function to start transactions to a contract + + @from From who + @to To who. + @amount Quantity + @extraData Extra data the receiver will get + */ + _transfer(from, to, amount, exchangeAddress == to); + var (_success, _back) = thirdPartyContractAbstract(to).receiveCorionToken(from, amount, extraData); + require( _success ); + require( amount > _back ); + if ( _back > 0 ) { + _transfer(to, from, _back, false); + } + _processTransactionFee(from, amount - _back); + } + + function _transfer(address from, address to, uint256 amount, bool fee) internal { + /* + Internal function to start transactions. When Tokens are sent, transaction fee is charged + During ICO transactions are allowed only from genesis addresses. + After sending the tokens, the ModuleHandler is notified and it will broadcast the fact among members + + The 0xa636a97578d26a3b76b060bbc18226d954cf3757 address are blacklisted. + + @from From who + @to To who + @amount Quantity + @fee Deduct transaction fee - yes or no? + */ + if( fee ) { + var (success, _fee) = getTransactionFee(amount); + require( success ); + require( db.balanceOf(from) >= amount + _fee ); + } + require( from != 0x00 && to != 0x00 && to != 0xa636a97578d26a3b76b060bbc18226d954cf3757 ); + require( ( ! isICO) || genesis[from] ); + require( db.decrease(from, amount) ); + require( db.increase(to, amount) ); + if ( fee ) { _processTransactionFee(from, amount); } + if ( isICO ) { + require( ico(icoAddr).setInterestDB(from, db.balanceOf(from)) ); + require( ico(icoAddr).setInterestDB(to, db.balanceOf(to)) ); + } + require( moduleHandler(moduleHandlerAddress).broadcastTransfer(from, to, amount) ); + } + + /** + * @notice Transaction fee will be deduced from `owner` for transacting `value` + * @param owner The address where will the transaction fee deduced + * @param value The base for calculating the fee + * @return True if the transfer was successful + */ + function processTransactionFee(address owner, uint256 value) isReady external returns (bool success) { + /* + Charge transaction fee. It can be called only by moduleHandler + + @owner From who. + @value Quantity to calculate the fee + + @success Was the Function successful? + */ + require( super.isModuleHandler(msg.sender) ); + _processTransactionFee(owner, value); + return true; + } + + function _processTransactionFee(address owner, uint256 value) internal { + /* + Internal function to charge the transaction fee. A certain quantity is burnt, the rest is sent to the Schelling game prize pool. + No transaction fee during ICO. + + @owner From who + @value Quantity to calculate the fee + */ + if ( isICO ) { return; } + var (_success, _fee) = getTransactionFee(value); + require( _success ); + uint256 _forBurn = _fee * transactionFeeBurn / 100; + uint256 _forSchelling = _fee - _forBurn; + bool _found; + address _schellingAddr; + (_success, _found, _schellingAddr) = moduleHandler(moduleHandlerAddress).getModuleAddressByName('Schelling'); + require( _success ); + if ( _schellingAddr != 0x00 && _found) { + require( db.decrease(owner, _forSchelling) ); + require( db.increase(_schellingAddr, _forSchelling) ); + _burn(owner, _forBurn); + bytes memory _data; + Transfer(owner, _schellingAddr, _forSchelling, _data); + require( moduleHandler(moduleHandlerAddress).broadcastTransfer(owner, _schellingAddr, _forSchelling) ); + } else { + _burn(owner, _fee); + } + } + + function getTransactionFee(uint256 value) public constant returns (bool success, uint256 fee) { + /* + Transaction fee query. + + @value Quantity to calculate the fee + + @success Was the Function successful? + @fee Amount of Transaction fee + */ + if ( isICO ) { return (true, 0); } + fee = value * transactionFeeRate / transactionFeeRateM / 100; + if ( fee > transactionFeeMax ) { fee = transactionFeeMax; } + else if ( fee < transactionFeeMin ) { fee = transactionFeeMin; } + return (true, fee); + } + + function mint(address owner, uint256 value) isReady external returns (bool success) { + /* + Generating tokens. It can be called only by ICO contract or the moduleHandler. + + @owner Address + @value Amount. + + @success Was the Function successful? + */ + require( super.isModuleHandler(msg.sender) || msg.sender == icoAddr ); + _mint(owner, value); + return true; + } + + function _mint(address owner, uint256 value) internal { + /* + Internal function to generate tokens + + @owner Token is credited to this address + @value Quantity + */ + require( db.increase(owner, value) ); + require( moduleHandler(moduleHandlerAddress).broadcastTransfer(0x00, owner, value) ); + if ( isICO ) { + require( ico(icoAddr).setInterestDB(owner, db.balanceOf(owner)) ); + } + Mint(owner, value); + } + + function burn(address owner, uint256 value) isReady external returns (bool success) { + /* + Burning the token. Can call only modulehandler + + @owner Burn the token from this address + @value Quantity + + @success Was the Function successful? + */ + require( super.isModuleHandler(msg.sender) ); + _burn(owner, value); + return true; + } + + function _burn(address owner, uint256 value) internal { + /* + Internal function to burn the token + + @owner Burn the token from this address + @value Quantity + */ + require( db.decrease(owner, value) ); + require( moduleHandler(moduleHandlerAddress).broadcastTransfer(owner, 0x00, value) ); + Burn(owner, value); + } + + function isContract(address addr) internal returns (bool success) { + /* + Internal function to check if the given address is natural, or a contract + + @addr Address to be checked + + @success Is the address crontact or not + */ + uint256 _codeLength; + assembly { + _codeLength := extcodesize(addr) + } + return _codeLength > 0; + } + + function balanceOf(address owner) constant returns (uint256 value) { + /* + Token balance query + + @owner Address + + @value Balance of address + */ + return db.balanceOf(owner); + } + + function totalSupply() constant returns (uint256 value) { + /* + Total token quantity query + + @value Total token quantity + */ + return db.totalSupply(); + } + + function configure(announcementType aType, uint256 value) isReady external returns(bool success) { + /* + Token settings configuration.It can be call only by moduleHandler + + @aType Type of setting + @value Value + + @success Was the Function successful? + */ + require( super.isModuleHandler(msg.sender) ); + if ( aType == announcementType.transactionFeeRate ) { transactionFeeRate = value; } + else if ( aType == announcementType.transactionFeeMin ) { transactionFeeMin = value; } + else if ( aType == announcementType.transactionFeeMax ) { transactionFeeMax = value; } + else if ( aType == announcementType.transactionFeeBurn ) { transactionFeeBurn = value; } + else { return false; } + return true; + } + + event AllowanceUsed(address indexed spender, address indexed owner, uint256 indexed value); + event Mint(address indexed addr, uint256 indexed value); + event Burn(address indexed addr, uint256 indexed value); + event Approval(address indexed _owner, address indexed _spender, uint256 _value); + event Transfer(address indexed _from, address indexed _to, uint256 indexed _value, bytes _extraData); +} diff --git a/test/compilationTests/corion/tokenDB.sol b/test/compilationTests/corion/tokenDB.sol new file mode 100644 index 00000000..6de1b6c3 --- /dev/null +++ b/test/compilationTests/corion/tokenDB.sol @@ -0,0 +1,77 @@ +pragma solidity ^0.4.11;
+
+import "./safeMath.sol";
+import "./owned.sol";
+
+contract tokenDB is safeMath, ownedDB {
+
+ struct allowance_s {
+ uint256 amount;
+ uint256 nonce;
+ }
+
+ mapping(address => mapping(address => allowance_s)) public allowance;
+ mapping (address => uint256) public balanceOf;
+ uint256 public totalSupply;
+
+ function increase(address owner, uint256 value) external returns(bool success) {
+ /*
+ Increase of balance of the address in database. Only owner can call it.
+
+ @owner Address
+ @value Quantity
+
+ @success Was the Function successful?
+ */
+ require( isOwner() );
+ balanceOf[owner] = safeAdd(balanceOf[owner], value);
+ totalSupply = safeAdd(totalSupply, value);
+ return true;
+ }
+
+ function decrease(address owner, uint256 value) external returns(bool success) {
+ /*
+ Decrease of balance of the address in database. Only owner can call it.
+
+ @owner Address
+ @value Quantity
+
+ @success Was the Function successful?
+ */
+ require( isOwner() );
+ balanceOf[owner] = safeSub(balanceOf[owner], value);
+ totalSupply = safeSub(totalSupply, value);
+ return true;
+ }
+
+ function setAllowance(address owner, address spender, uint256 amount, uint256 nonce) external returns(bool success) {
+ /*
+ Set allowance in the database. Only owner can call it.
+
+ @owner Owner address
+ @spender Spender address
+ @amount Amount to set
+ @nonce Transaction count
+
+ @success Was the Function successful?
+ */
+ require( isOwner() );
+ allowance[owner][spender].amount = amount;
+ allowance[owner][spender].nonce = nonce;
+ return true;
+ }
+
+ function getAllowance(address owner, address spender) constant returns(bool success, uint256 remaining, uint256 nonce) {
+ /*
+ Get allowance from the database.
+
+ @owner Owner address
+ @spender Spender address
+
+ @success Was the Function successful?
+ @remaining Remaining amount of the allowance
+ @nonce Transaction count
+ */
+ return ( true, allowance[owner][spender].amount, allowance[owner][spender].nonce );
+ }
+}
diff --git a/test/compilationTests/gnosis/Events/CategoricalEvent.sol b/test/compilationTests/gnosis/Events/CategoricalEvent.sol new file mode 100644 index 00000000..fbd1d744 --- /dev/null +++ b/test/compilationTests/gnosis/Events/CategoricalEvent.sol @@ -0,0 +1,53 @@ +pragma solidity ^0.4.11; +import "../Events/Event.sol"; + + +/// @title Categorical event contract - Categorical events resolve to an outcome from a set of outcomes +/// @author Stefan George - <stefan@gnosis.pm> +contract CategoricalEvent is Event { + + /* + * Public functions + */ + /// @dev Contract constructor validates and sets basic event properties + /// @param _collateralToken Tokens used as collateral in exchange for outcome tokens + /// @param _oracle Oracle contract used to resolve the event + /// @param outcomeCount Number of event outcomes + function CategoricalEvent( + Token _collateralToken, + Oracle _oracle, + uint8 outcomeCount + ) + public + Event(_collateralToken, _oracle, outcomeCount) + { + + } + + /// @dev Exchanges sender's winning outcome tokens for collateral tokens + /// @return Sender's winnings + function redeemWinnings() + public + returns (uint winnings) + { + // Winning outcome has to be set + require(isOutcomeSet); + // Calculate winnings + winnings = outcomeTokens[uint(outcome)].balanceOf(msg.sender); + // Revoke tokens from winning outcome + outcomeTokens[uint(outcome)].revoke(msg.sender, winnings); + // Payout winnings + require(collateralToken.transfer(msg.sender, winnings)); + WinningsRedemption(msg.sender, winnings); + } + + /// @dev Calculates and returns event hash + /// @return Event hash + function getEventHash() + public + constant + returns (bytes32) + { + return keccak256(collateralToken, oracle, outcomeTokens.length); + } +} diff --git a/test/compilationTests/gnosis/Events/Event.sol b/test/compilationTests/gnosis/Events/Event.sol new file mode 100644 index 00000000..9aa257c4 --- /dev/null +++ b/test/compilationTests/gnosis/Events/Event.sol @@ -0,0 +1,128 @@ +pragma solidity ^0.4.11; +import "../Tokens/Token.sol"; +import "../Tokens/OutcomeToken.sol"; +import "../Oracles/Oracle.sol"; + + +/// @title Event contract - Provide basic functionality required by different event types +/// @author Stefan George - <stefan@gnosis.pm> +contract Event { + + /* + * Events + */ + event OutcomeTokenCreation(OutcomeToken outcomeToken, uint8 index); + event OutcomeTokenSetIssuance(address indexed buyer, uint collateralTokenCount); + event OutcomeTokenSetRevocation(address indexed seller, uint outcomeTokenCount); + event OutcomeAssignment(int outcome); + event WinningsRedemption(address indexed receiver, uint winnings); + + /* + * Storage + */ + Token public collateralToken; + Oracle public oracle; + bool public isOutcomeSet; + int public outcome; + OutcomeToken[] public outcomeTokens; + + /* + * Public functions + */ + /// @dev Contract constructor validates and sets basic event properties + /// @param _collateralToken Tokens used as collateral in exchange for outcome tokens + /// @param _oracle Oracle contract used to resolve the event + /// @param outcomeCount Number of event outcomes + function Event(Token _collateralToken, Oracle _oracle, uint8 outcomeCount) + public + { + // Validate input + require(address(_collateralToken) != 0 && address(_oracle) != 0 && outcomeCount >= 2); + collateralToken = _collateralToken; + oracle = _oracle; + // Create an outcome token for each outcome + for (uint8 i = 0; i < outcomeCount; i++) { + OutcomeToken outcomeToken = new OutcomeToken(); + outcomeTokens.push(outcomeToken); + OutcomeTokenCreation(outcomeToken, i); + } + } + + /// @dev Buys equal number of tokens of all outcomes, exchanging collateral tokens and sets of outcome tokens 1:1 + /// @param collateralTokenCount Number of collateral tokens + function buyAllOutcomes(uint collateralTokenCount) + public + { + // Transfer collateral tokens to events contract + require(collateralToken.transferFrom(msg.sender, this, collateralTokenCount)); + // Issue new outcome tokens to sender + for (uint8 i = 0; i < outcomeTokens.length; i++) + outcomeTokens[i].issue(msg.sender, collateralTokenCount); + OutcomeTokenSetIssuance(msg.sender, collateralTokenCount); + } + + /// @dev Sells equal number of tokens of all outcomes, exchanging collateral tokens and sets of outcome tokens 1:1 + /// @param outcomeTokenCount Number of outcome tokens + function sellAllOutcomes(uint outcomeTokenCount) + public + { + // Revoke sender's outcome tokens of all outcomes + for (uint8 i = 0; i < outcomeTokens.length; i++) + outcomeTokens[i].revoke(msg.sender, outcomeTokenCount); + // Transfer collateral tokens to sender + require(collateralToken.transfer(msg.sender, outcomeTokenCount)); + OutcomeTokenSetRevocation(msg.sender, outcomeTokenCount); + } + + /// @dev Sets winning event outcome + function setOutcome() + public + { + // Winning outcome is not set yet in event contract but in oracle contract + require(!isOutcomeSet && oracle.isOutcomeSet()); + // Set winning outcome + outcome = oracle.getOutcome(); + isOutcomeSet = true; + OutcomeAssignment(outcome); + } + + /// @dev Returns outcome count + /// @return Outcome count + function getOutcomeCount() + public + constant + returns (uint8) + { + return uint8(outcomeTokens.length); + } + + /// @dev Returns outcome tokens array + /// @return Outcome tokens + function getOutcomeTokens() + public + constant + returns (OutcomeToken[]) + { + return outcomeTokens; + } + + /// @dev Returns the amount of outcome tokens held by owner + /// @return Outcome token distribution + function getOutcomeTokenDistribution(address owner) + public + constant + returns (uint[] outcomeTokenDistribution) + { + outcomeTokenDistribution = new uint[](outcomeTokens.length); + for (uint8 i = 0; i < outcomeTokenDistribution.length; i++) + outcomeTokenDistribution[i] = outcomeTokens[i].balanceOf(owner); + } + + /// @dev Calculates and returns event hash + /// @return Event hash + function getEventHash() public constant returns (bytes32); + + /// @dev Exchanges sender's winning outcome tokens for collateral tokens + /// @return Sender's winnings + function redeemWinnings() public returns (uint); +} diff --git a/test/compilationTests/gnosis/Events/EventFactory.sol b/test/compilationTests/gnosis/Events/EventFactory.sol new file mode 100644 index 00000000..dfb1a579 --- /dev/null +++ b/test/compilationTests/gnosis/Events/EventFactory.sol @@ -0,0 +1,79 @@ +pragma solidity ^0.4.11; +import "../Events/CategoricalEvent.sol"; +import "../Events/ScalarEvent.sol"; + + +/// @title Event factory contract - Allows creation of categorical and scalar events +/// @author Stefan George - <stefan@gnosis.pm> +contract EventFactory { + + /* + * Events + */ + event CategoricalEventCreation(address indexed creator, CategoricalEvent categoricalEvent, Token collateralToken, Oracle oracle, uint8 outcomeCount); + event ScalarEventCreation(address indexed creator, ScalarEvent scalarEvent, Token collateralToken, Oracle oracle, int lowerBound, int upperBound); + + /* + * Storage + */ + mapping (bytes32 => CategoricalEvent) public categoricalEvents; + mapping (bytes32 => ScalarEvent) public scalarEvents; + + /* + * Public functions + */ + /// @dev Creates a new categorical event and adds it to the event mapping + /// @param collateralToken Tokens used as collateral in exchange for outcome tokens + /// @param oracle Oracle contract used to resolve the event + /// @param outcomeCount Number of event outcomes + /// @return Event contract + function createCategoricalEvent( + Token collateralToken, + Oracle oracle, + uint8 outcomeCount + ) + public + returns (CategoricalEvent eventContract) + { + bytes32 eventHash = keccak256(collateralToken, oracle, outcomeCount); + // Event should not exist yet + require(address(categoricalEvents[eventHash]) == 0); + // Create event + eventContract = new CategoricalEvent( + collateralToken, + oracle, + outcomeCount + ); + categoricalEvents[eventHash] = eventContract; + CategoricalEventCreation(msg.sender, eventContract, collateralToken, oracle, outcomeCount); + } + + /// @dev Creates a new scalar event and adds it to the event mapping + /// @param collateralToken Tokens used as collateral in exchange for outcome tokens + /// @param oracle Oracle contract used to resolve the event + /// @param lowerBound Lower bound for event outcome + /// @param upperBound Lower bound for event outcome + /// @return Event contract + function createScalarEvent( + Token collateralToken, + Oracle oracle, + int lowerBound, + int upperBound + ) + public + returns (ScalarEvent eventContract) + { + bytes32 eventHash = keccak256(collateralToken, oracle, lowerBound, upperBound); + // Event should not exist yet + require(address(scalarEvents[eventHash]) == 0); + // Create event + eventContract = new ScalarEvent( + collateralToken, + oracle, + lowerBound, + upperBound + ); + scalarEvents[eventHash] = eventContract; + ScalarEventCreation(msg.sender, eventContract, collateralToken, oracle, lowerBound, upperBound); + } +} diff --git a/test/compilationTests/gnosis/Events/ScalarEvent.sol b/test/compilationTests/gnosis/Events/ScalarEvent.sol new file mode 100644 index 00000000..2e5718ef --- /dev/null +++ b/test/compilationTests/gnosis/Events/ScalarEvent.sol @@ -0,0 +1,87 @@ +pragma solidity ^0.4.11; +import "../Events/Event.sol"; + + +/// @title Scalar event contract - Scalar events resolve to a number within a range +/// @author Stefan George - <stefan@gnosis.pm> +contract ScalarEvent is Event { + using Math for *; + + /* + * Constants + */ + uint8 public constant SHORT = 0; + uint8 public constant LONG = 1; + uint24 public constant OUTCOME_RANGE = 1000000; + + /* + * Storage + */ + int public lowerBound; + int public upperBound; + + /* + * Public functions + */ + /// @dev Contract constructor validates and sets basic event properties + /// @param _collateralToken Tokens used as collateral in exchange for outcome tokens + /// @param _oracle Oracle contract used to resolve the event + /// @param _lowerBound Lower bound for event outcome + /// @param _upperBound Lower bound for event outcome + function ScalarEvent( + Token _collateralToken, + Oracle _oracle, + int _lowerBound, + int _upperBound + ) + public + Event(_collateralToken, _oracle, 2) + { + // Validate bounds + require(_upperBound > _lowerBound); + lowerBound = _lowerBound; + upperBound = _upperBound; + } + + /// @dev Exchanges sender's winning outcome tokens for collateral tokens + /// @return Sender's winnings + function redeemWinnings() + public + returns (uint winnings) + { + // Winning outcome has to be set + require(isOutcomeSet); + // Calculate winnings + uint24 convertedWinningOutcome; + // Outcome is lower than defined lower bound + if (outcome < lowerBound) + convertedWinningOutcome = 0; + // Outcome is higher than defined upper bound + else if (outcome > upperBound) + convertedWinningOutcome = OUTCOME_RANGE; + // Map outcome to outcome range + else + convertedWinningOutcome = uint24(OUTCOME_RANGE * (outcome - lowerBound) / (upperBound - lowerBound)); + uint factorShort = OUTCOME_RANGE - convertedWinningOutcome; + uint factorLong = OUTCOME_RANGE - factorShort; + uint shortOutcomeTokenCount = outcomeTokens[SHORT].balanceOf(msg.sender); + uint longOutcomeTokenCount = outcomeTokens[LONG].balanceOf(msg.sender); + winnings = shortOutcomeTokenCount.mul(factorShort).add(longOutcomeTokenCount.mul(factorLong)) / OUTCOME_RANGE; + // Revoke all outcome tokens + outcomeTokens[SHORT].revoke(msg.sender, shortOutcomeTokenCount); + outcomeTokens[LONG].revoke(msg.sender, longOutcomeTokenCount); + // Payout winnings to sender + require(collateralToken.transfer(msg.sender, winnings)); + WinningsRedemption(msg.sender, winnings); + } + + /// @dev Calculates and returns event hash + /// @return Event hash + function getEventHash() + public + constant + returns (bytes32) + { + return keccak256(collateralToken, oracle, lowerBound, upperBound); + } +} diff --git a/test/compilationTests/gnosis/LICENSE b/test/compilationTests/gnosis/LICENSE new file mode 100644 index 00000000..0f2001b5 --- /dev/null +++ b/test/compilationTests/gnosis/LICENSE @@ -0,0 +1,675 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + Decentralized prediction markets and decentralized oracle system + #Copyright (C) 2015 Forecast Foundation OU, full GPL notice in LICENSE + + This program 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. + + This program 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 this program. If not, see <http://www.gnu.org/licenses/>. + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Decentralized prediction markets and decentralized oracle system + Copyright (C) 2015 Forecast Foundation OU + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +<http://www.gnu.org/licenses/>. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +<http://www.gnu.org/philosophy/why-not-lgpl.html>.
\ No newline at end of file diff --git a/test/compilationTests/gnosis/MarketMakers/LMSRMarketMaker.sol b/test/compilationTests/gnosis/MarketMakers/LMSRMarketMaker.sol new file mode 100644 index 00000000..1529129d --- /dev/null +++ b/test/compilationTests/gnosis/MarketMakers/LMSRMarketMaker.sol @@ -0,0 +1,180 @@ +pragma solidity ^0.4.11; +import "../Utils/Math.sol"; +import "../MarketMakers/MarketMaker.sol"; + + +/// @title LMSR market maker contract - Calculates share prices based on share distribution and initial funding +/// @author Alan Lu - <alan.lu@gnosis.pm> +contract LMSRMarketMaker is MarketMaker { + using Math for *; + + /* + * Constants + */ + uint constant ONE = 0x10000000000000000; + int constant EXP_LIMIT = 2352680790717288641401; + + /* + * Public functions + */ + /// @dev Returns cost to buy given number of outcome tokens + /// @param market Market contract + /// @param outcomeTokenIndex Index of outcome to buy + /// @param outcomeTokenCount Number of outcome tokens to buy + /// @return Cost + function calcCost(Market market, uint8 outcomeTokenIndex, uint outcomeTokenCount) + public + constant + returns (uint cost) + { + require(market.eventContract().getOutcomeCount() > 1); + int[] memory netOutcomeTokensSold = getNetOutcomeTokensSold(market); + // Calculate cost level based on net outcome token balances + int logN = Math.ln(netOutcomeTokensSold.length * ONE); + uint funding = market.funding(); + int costLevelBefore = calcCostLevel(logN, netOutcomeTokensSold, funding); + // Add outcome token count to net outcome token balance + require(int(outcomeTokenCount) >= 0); + netOutcomeTokensSold[outcomeTokenIndex] = netOutcomeTokensSold[outcomeTokenIndex].add(int(outcomeTokenCount)); + // Calculate cost level after balance was updated + int costLevelAfter = calcCostLevel(logN, netOutcomeTokensSold, funding); + // Calculate cost as cost level difference + require(costLevelAfter >= costLevelBefore); + cost = uint(costLevelAfter - costLevelBefore); + // Take the ceiling to account for rounding + if (cost / ONE * ONE == cost) + cost /= ONE; + else + // Integer division by ONE ensures there is room to (+ 1) + cost = cost / ONE + 1; + // Make sure cost is not bigger than 1 per share + if (cost > outcomeTokenCount) + cost = outcomeTokenCount; + } + + /// @dev Returns profit for selling given number of outcome tokens + /// @param market Market contract + /// @param outcomeTokenIndex Index of outcome to sell + /// @param outcomeTokenCount Number of outcome tokens to sell + /// @return Profit + function calcProfit(Market market, uint8 outcomeTokenIndex, uint outcomeTokenCount) + public + constant + returns (uint profit) + { + require(market.eventContract().getOutcomeCount() > 1); + int[] memory netOutcomeTokensSold = getNetOutcomeTokensSold(market); + // Calculate cost level based on net outcome token balances + int logN = Math.ln(netOutcomeTokensSold.length * ONE); + uint funding = market.funding(); + int costLevelBefore = calcCostLevel(logN, netOutcomeTokensSold, funding); + // Subtract outcome token count from the net outcome token balance + require(int(outcomeTokenCount) >= 0); + netOutcomeTokensSold[outcomeTokenIndex] = netOutcomeTokensSold[outcomeTokenIndex].sub(int(outcomeTokenCount)); + // Calculate cost level after balance was updated + int costLevelAfter = calcCostLevel(logN, netOutcomeTokensSold, funding); + // Calculate profit as cost level difference + require(costLevelBefore >= costLevelAfter); + // Take the floor + profit = uint(costLevelBefore - costLevelAfter) / ONE; + } + + /// @dev Returns marginal price of an outcome + /// @param market Market contract + /// @param outcomeTokenIndex Index of outcome to determine marginal price of + /// @return Marginal price of an outcome as a fixed point number + function calcMarginalPrice(Market market, uint8 outcomeTokenIndex) + public + constant + returns (uint price) + { + require(market.eventContract().getOutcomeCount() > 1); + int[] memory netOutcomeTokensSold = getNetOutcomeTokensSold(market); + int logN = Math.ln(netOutcomeTokensSold.length * ONE); + uint funding = market.funding(); + // The price function is exp(quantities[i]/b) / sum(exp(q/b) for q in quantities) + // To avoid overflow, calculate with + // exp(quantities[i]/b - offset) / sum(exp(q/b - offset) for q in quantities) + var (sum, , outcomeExpTerm) = sumExpOffset(logN, netOutcomeTokensSold, funding, outcomeTokenIndex); + return outcomeExpTerm / (sum / ONE); + } + + /* + * Private functions + */ + /// @dev Calculates the result of the LMSR cost function which is used to + /// derive prices from the market state + /// @param logN Logarithm of the number of outcomes + /// @param netOutcomeTokensSold Net outcome tokens sold by market + /// @param funding Initial funding for market + /// @return Cost level + function calcCostLevel(int logN, int[] netOutcomeTokensSold, uint funding) + private + constant + returns(int costLevel) + { + // The cost function is C = b * log(sum(exp(q/b) for q in quantities)). + // To avoid overflow, we need to calc with an exponent offset: + // C = b * (offset + log(sum(exp(q/b - offset) for q in quantities))) + var (sum, offset, ) = sumExpOffset(logN, netOutcomeTokensSold, funding, 0); + costLevel = Math.ln(sum); + costLevel = costLevel.add(offset); + costLevel = (costLevel.mul(int(ONE)) / logN).mul(int(funding)); + } + + /// @dev Calculates sum(exp(q/b - offset) for q in quantities), where offset is set + /// so that the sum fits in 248-256 bits + /// @param logN Logarithm of the number of outcomes + /// @param netOutcomeTokensSold Net outcome tokens sold by market + /// @param funding Initial funding for market + /// @param outcomeIndex Index of exponential term to extract (for use by marginal price function) + /// @return A result structure composed of the sum, the offset used, and the summand associated with the supplied index + function sumExpOffset(int logN, int[] netOutcomeTokensSold, uint funding, uint8 outcomeIndex) + private + constant + returns (uint sum, int offset, uint outcomeExpTerm) + { + // Naive calculation of this causes an overflow + // since anything above a bit over 133*ONE supplied to exp will explode + // as exp(133) just about fits into 192 bits of whole number data. + + // The choice of this offset is subject to another limit: + // computing the inner sum successfully. + // Since the index is 8 bits, there has to be 8 bits of headroom for + // each summand, meaning q/b - offset <= exponential_limit, + // where that limit can be found with `mp.floor(mp.log((2**248 - 1) / ONE) * ONE)` + // That is what EXP_LIMIT is set to: it is about 127.5 + + // finally, if the distribution looks like [BIG, tiny, tiny...], using a + // BIG offset will cause the tiny quantities to go really negative + // causing the associated exponentials to vanish. + + int maxQuantity = Math.max(netOutcomeTokensSold); + require(logN >= 0 && int(funding) >= 0); + offset = maxQuantity.mul(logN) / int(funding); + offset = offset.sub(EXP_LIMIT); + uint term; + for (uint8 i = 0; i < netOutcomeTokensSold.length; i++) { + term = Math.exp((netOutcomeTokensSold[i].mul(logN) / int(funding)).sub(offset)); + if (i == outcomeIndex) + outcomeExpTerm = term; + sum = sum.add(term); + } + } + + /// @dev Gets net outcome tokens sold by market. Since all sets of outcome tokens are backed by + /// corresponding collateral tokens, the net quantity of a token sold by the market is the + /// number of collateral tokens (which is the same as the number of outcome tokens the + /// market created) subtracted by the quantity of that token held by the market. + /// @param market Market contract + /// @return Net outcome tokens sold by market + function getNetOutcomeTokensSold(Market market) + private + constant + returns (int[] quantities) + { + quantities = new int[](market.eventContract().getOutcomeCount()); + for (uint8 i = 0; i < quantities.length; i++) + quantities[i] = market.netOutcomeTokensSold(i); + } +} diff --git a/test/compilationTests/gnosis/MarketMakers/MarketMaker.sol b/test/compilationTests/gnosis/MarketMakers/MarketMaker.sol new file mode 100644 index 00000000..3162ce64 --- /dev/null +++ b/test/compilationTests/gnosis/MarketMakers/MarketMaker.sol @@ -0,0 +1,14 @@ +pragma solidity ^0.4.11; +import "../Markets/Market.sol"; + + +/// @title Abstract market maker contract - Functions to be implemented by market maker contracts +contract MarketMaker { + + /* + * Public functions + */ + function calcCost(Market market, uint8 outcomeTokenIndex, uint outcomeTokenCount) public constant returns (uint); + function calcProfit(Market market, uint8 outcomeTokenIndex, uint outcomeTokenCount) public constant returns (uint); + function calcMarginalPrice(Market market, uint8 outcomeTokenIndex) public constant returns (uint); +} diff --git a/test/compilationTests/gnosis/Markets/Campaign.sol b/test/compilationTests/gnosis/Markets/Campaign.sol new file mode 100644 index 00000000..9aee1033 --- /dev/null +++ b/test/compilationTests/gnosis/Markets/Campaign.sol @@ -0,0 +1,177 @@ +pragma solidity ^0.4.11; +import "../Events/Event.sol"; +import "../Markets/StandardMarketFactory.sol"; +import "../Utils/Math.sol"; + + +/// @title Campaign contract - Allows to crowdfund a market +/// @author Stefan George - <stefan@gnosis.pm> +contract Campaign { + using Math for *; + + /* + * Events + */ + event CampaignFunding(address indexed sender, uint funding); + event CampaignRefund(address indexed sender, uint refund); + event MarketCreation(Market indexed market); + event MarketClosing(); + event FeeWithdrawal(address indexed receiver, uint fees); + + /* + * Constants + */ + uint24 public constant FEE_RANGE = 1000000; // 100% + + /* + * Storage + */ + Event public eventContract; + MarketFactory public marketFactory; + MarketMaker public marketMaker; + Market public market; + uint24 public fee; + uint public funding; + uint public deadline; + uint public finalBalance; + mapping (address => uint) public contributions; + Stages public stage; + + enum Stages { + AuctionStarted, + AuctionSuccessful, + AuctionFailed, + MarketCreated, + MarketClosed + } + + /* + * Modifiers + */ + modifier atStage(Stages _stage) { + // Contract has to be in given stage + require(stage == _stage); + _; + } + + modifier timedTransitions() { + if (stage == Stages.AuctionStarted && deadline < now) + stage = Stages.AuctionFailed; + _; + } + + /* + * Public functions + */ + /// @dev Constructor validates and sets campaign properties + /// @param _eventContract Event contract + /// @param _marketFactory Market factory contract + /// @param _marketMaker Market maker contract + /// @param _fee Market fee + /// @param _funding Initial funding for market + /// @param _deadline Campaign deadline + function Campaign( + Event _eventContract, + MarketFactory _marketFactory, + MarketMaker _marketMaker, + uint24 _fee, + uint _funding, + uint _deadline + ) + public + { + // Validate input + require( address(_eventContract) != 0 + && address(_marketFactory) != 0 + && address(_marketMaker) != 0 + && _fee < FEE_RANGE + && _funding > 0 + && now < _deadline); + eventContract = _eventContract; + marketFactory = _marketFactory; + marketMaker = _marketMaker; + fee = _fee; + funding = _funding; + deadline = _deadline; + } + + /// @dev Allows to contribute to required market funding + /// @param amount Amount of collateral tokens + function fund(uint amount) + public + timedTransitions + atStage(Stages.AuctionStarted) + { + uint raisedAmount = eventContract.collateralToken().balanceOf(this); + uint maxAmount = funding.sub(raisedAmount); + if (maxAmount < amount) + amount = maxAmount; + // Collect collateral tokens + require(eventContract.collateralToken().transferFrom(msg.sender, this, amount)); + contributions[msg.sender] = contributions[msg.sender].add(amount); + if (amount == maxAmount) + stage = Stages.AuctionSuccessful; + CampaignFunding(msg.sender, amount); + } + + /// @dev Withdraws refund amount + /// @return Refund amount + function refund() + public + timedTransitions + atStage(Stages.AuctionFailed) + returns (uint refundAmount) + { + refundAmount = contributions[msg.sender]; + contributions[msg.sender] = 0; + // Refund collateral tokens + require(eventContract.collateralToken().transfer(msg.sender, refundAmount)); + CampaignRefund(msg.sender, refundAmount); + } + + /// @dev Allows to create market after successful funding + /// @return Market address + function createMarket() + public + timedTransitions + atStage(Stages.AuctionSuccessful) + returns (Market) + { + market = marketFactory.createMarket(eventContract, marketMaker, fee); + require(eventContract.collateralToken().approve(market, funding)); + market.fund(funding); + stage = Stages.MarketCreated; + MarketCreation(market); + return market; + } + + /// @dev Allows to withdraw fees from market contract to campaign contract + /// @return Fee amount + function closeMarket() + public + atStage(Stages.MarketCreated) + { + // Winning outcome should be set + require(eventContract.isOutcomeSet()); + market.close(); + market.withdrawFees(); + eventContract.redeemWinnings(); + finalBalance = eventContract.collateralToken().balanceOf(this); + stage = Stages.MarketClosed; + MarketClosing(); + } + + /// @dev Allows to withdraw fees from campaign contract to contributor + /// @return Fee amount + function withdrawFees() + public + atStage(Stages.MarketClosed) + returns (uint fees) + { + fees = finalBalance.mul(contributions[msg.sender]) / funding; + contributions[msg.sender] = 0; + // Send fee share to contributor + require(eventContract.collateralToken().transfer(msg.sender, fees)); + FeeWithdrawal(msg.sender, fees); + } +} diff --git a/test/compilationTests/gnosis/Markets/CampaignFactory.sol b/test/compilationTests/gnosis/Markets/CampaignFactory.sol new file mode 100644 index 00000000..930ec2e2 --- /dev/null +++ b/test/compilationTests/gnosis/Markets/CampaignFactory.sol @@ -0,0 +1,39 @@ +pragma solidity ^0.4.11; +import "../Markets/Campaign.sol"; + + +/// @title Campaign factory contract - Allows to create campaign contracts +/// @author Stefan George - <stefan@gnosis.pm> +contract CampaignFactory { + + /* + * Events + */ + event CampaignCreation(address indexed creator, Campaign campaign, Event eventContract, MarketFactory marketFactory, MarketMaker marketMaker, uint24 fee, uint funding, uint deadline); + + /* + * Public functions + */ + /// @dev Creates a new campaign contract + /// @param eventContract Event contract + /// @param marketFactory Market factory contract + /// @param marketMaker Market maker contract + /// @param fee Market fee + /// @param funding Initial funding for market + /// @param deadline Campaign deadline + /// @return Market contract + function createCampaigns( + Event eventContract, + MarketFactory marketFactory, + MarketMaker marketMaker, + uint24 fee, + uint funding, + uint deadline + ) + public + returns (Campaign campaign) + { + campaign = new Campaign(eventContract, marketFactory, marketMaker, fee, funding, deadline); + CampaignCreation(msg.sender, campaign, eventContract, marketFactory, marketMaker, fee, funding, deadline); + } +} diff --git a/test/compilationTests/gnosis/Markets/Market.sol b/test/compilationTests/gnosis/Markets/Market.sol new file mode 100644 index 00000000..635b14db --- /dev/null +++ b/test/compilationTests/gnosis/Markets/Market.sol @@ -0,0 +1,47 @@ +pragma solidity ^0.4.11; +import "../Events/Event.sol"; +import "../MarketMakers/MarketMaker.sol"; + + +/// @title Abstract market contract - Functions to be implemented by market contracts +contract Market { + + /* + * Events + */ + event MarketFunding(uint funding); + event MarketClosing(); + event FeeWithdrawal(uint fees); + event OutcomeTokenPurchase(address indexed buyer, uint8 outcomeTokenIndex, uint outcomeTokenCount, uint cost); + event OutcomeTokenSale(address indexed seller, uint8 outcomeTokenIndex, uint outcomeTokenCount, uint profit); + event OutcomeTokenShortSale(address indexed buyer, uint8 outcomeTokenIndex, uint outcomeTokenCount, uint cost); + + /* + * Storage + */ + address public creator; + uint public createdAtBlock; + Event public eventContract; + MarketMaker public marketMaker; + uint24 public fee; + uint public funding; + int[] public netOutcomeTokensSold; + Stages public stage; + + enum Stages { + MarketCreated, + MarketFunded, + MarketClosed + } + + /* + * Public functions + */ + function fund(uint _funding) public; + function close() public; + function withdrawFees() public returns (uint); + function buy(uint8 outcomeTokenIndex, uint outcomeTokenCount, uint maxCost) public returns (uint); + function sell(uint8 outcomeTokenIndex, uint outcomeTokenCount, uint minProfit) public returns (uint); + function shortSell(uint8 outcomeTokenIndex, uint outcomeTokenCount, uint minProfit) public returns (uint); + function calcMarketFee(uint outcomeTokenCost) public constant returns (uint); +} diff --git a/test/compilationTests/gnosis/Markets/MarketFactory.sol b/test/compilationTests/gnosis/Markets/MarketFactory.sol new file mode 100644 index 00000000..d368e8db --- /dev/null +++ b/test/compilationTests/gnosis/Markets/MarketFactory.sol @@ -0,0 +1,19 @@ +pragma solidity ^0.4.11; +import "../Events/Event.sol"; +import "../MarketMakers/MarketMaker.sol"; +import "../Markets/Market.sol"; + + +/// @title Abstract market factory contract - Functions to be implemented by market factories +contract MarketFactory { + + /* + * Events + */ + event MarketCreation(address indexed creator, Market market, Event eventContract, MarketMaker marketMaker, uint24 fee); + + /* + * Public functions + */ + function createMarket(Event eventContract, MarketMaker marketMaker, uint24 fee) public returns (Market); +} diff --git a/test/compilationTests/gnosis/Markets/StandardMarket.sol b/test/compilationTests/gnosis/Markets/StandardMarket.sol new file mode 100644 index 00000000..b973119a --- /dev/null +++ b/test/compilationTests/gnosis/Markets/StandardMarket.sol @@ -0,0 +1,194 @@ +pragma solidity ^0.4.11; +import "../Markets/Market.sol"; +import "../Tokens/Token.sol"; +import "../Events/Event.sol"; +import "../MarketMakers/MarketMaker.sol"; + + +/// @title Market factory contract - Allows to create market contracts +/// @author Stefan George - <stefan@gnosis.pm> +contract StandardMarket is Market { + using Math for *; + + /* + * Constants + */ + uint24 public constant FEE_RANGE = 1000000; // 100% + + /* + * Modifiers + */ + modifier isCreator () { + // Only creator is allowed to proceed + require(msg.sender == creator); + _; + } + + modifier atStage(Stages _stage) { + // Contract has to be in given stage + require(stage == _stage); + _; + } + + /* + * Public functions + */ + /// @dev Constructor validates and sets market properties + /// @param _creator Market creator + /// @param _eventContract Event contract + /// @param _marketMaker Market maker contract + /// @param _fee Market fee + function StandardMarket(address _creator, Event _eventContract, MarketMaker _marketMaker, uint24 _fee) + public + { + // Validate inputs + require(address(_eventContract) != 0 && address(_marketMaker) != 0 && _fee < FEE_RANGE); + creator = _creator; + createdAtBlock = block.number; + eventContract = _eventContract; + netOutcomeTokensSold = new int[](eventContract.getOutcomeCount()); + fee = _fee; + marketMaker = _marketMaker; + stage = Stages.MarketCreated; + } + + /// @dev Allows to fund the market with collateral tokens converting them into outcome tokens + /// @param _funding Funding amount + function fund(uint _funding) + public + isCreator + atStage(Stages.MarketCreated) + { + // Request collateral tokens and allow event contract to transfer them to buy all outcomes + require( eventContract.collateralToken().transferFrom(msg.sender, this, _funding) + && eventContract.collateralToken().approve(eventContract, _funding)); + eventContract.buyAllOutcomes(_funding); + funding = _funding; + stage = Stages.MarketFunded; + MarketFunding(funding); + } + + /// @dev Allows market creator to close the markets by transferring all remaining outcome tokens to the creator + function close() + public + isCreator + atStage(Stages.MarketFunded) + { + uint8 outcomeCount = eventContract.getOutcomeCount(); + for (uint8 i = 0; i < outcomeCount; i++) + require(eventContract.outcomeTokens(i).transfer(creator, eventContract.outcomeTokens(i).balanceOf(this))); + stage = Stages.MarketClosed; + MarketClosing(); + } + + /// @dev Allows market creator to withdraw fees generated by trades + /// @return Fee amount + function withdrawFees() + public + isCreator + returns (uint fees) + { + fees = eventContract.collateralToken().balanceOf(this); + // Transfer fees + require(eventContract.collateralToken().transfer(creator, fees)); + FeeWithdrawal(fees); + } + + /// @dev Allows to buy outcome tokens from market maker + /// @param outcomeTokenIndex Index of the outcome token to buy + /// @param outcomeTokenCount Amount of outcome tokens to buy + /// @param maxCost The maximum cost in collateral tokens to pay for outcome tokens + /// @return Cost in collateral tokens + function buy(uint8 outcomeTokenIndex, uint outcomeTokenCount, uint maxCost) + public + atStage(Stages.MarketFunded) + returns (uint cost) + { + // Calculate cost to buy outcome tokens + uint outcomeTokenCost = marketMaker.calcCost(this, outcomeTokenIndex, outcomeTokenCount); + // Calculate fees charged by market + uint fees = calcMarketFee(outcomeTokenCost); + cost = outcomeTokenCost.add(fees); + // Check cost doesn't exceed max cost + require(cost > 0 && cost <= maxCost); + // Transfer tokens to markets contract and buy all outcomes + require( eventContract.collateralToken().transferFrom(msg.sender, this, cost) + && eventContract.collateralToken().approve(eventContract, outcomeTokenCost)); + // Buy all outcomes + eventContract.buyAllOutcomes(outcomeTokenCost); + // Transfer outcome tokens to buyer + require(eventContract.outcomeTokens(outcomeTokenIndex).transfer(msg.sender, outcomeTokenCount)); + // Add outcome token count to market maker net balance + require(int(outcomeTokenCount) >= 0); + netOutcomeTokensSold[outcomeTokenIndex] = netOutcomeTokensSold[outcomeTokenIndex].add(int(outcomeTokenCount)); + OutcomeTokenPurchase(msg.sender, outcomeTokenIndex, outcomeTokenCount, cost); + } + + /// @dev Allows to sell outcome tokens to market maker + /// @param outcomeTokenIndex Index of the outcome token to sell + /// @param outcomeTokenCount Amount of outcome tokens to sell + /// @param minProfit The minimum profit in collateral tokens to earn for outcome tokens + /// @return Profit in collateral tokens + function sell(uint8 outcomeTokenIndex, uint outcomeTokenCount, uint minProfit) + public + atStage(Stages.MarketFunded) + returns (uint profit) + { + // Calculate profit for selling outcome tokens + uint outcomeTokenProfit = marketMaker.calcProfit(this, outcomeTokenIndex, outcomeTokenCount); + // Calculate fee charged by market + uint fees = calcMarketFee(outcomeTokenProfit); + profit = outcomeTokenProfit.sub(fees); + // Check profit is not too low + require(profit > 0 && profit >= minProfit); + // Transfer outcome tokens to markets contract to sell all outcomes + require(eventContract.outcomeTokens(outcomeTokenIndex).transferFrom(msg.sender, this, outcomeTokenCount)); + // Sell all outcomes + eventContract.sellAllOutcomes(outcomeTokenProfit); + // Transfer profit to seller + require(eventContract.collateralToken().transfer(msg.sender, profit)); + // Subtract outcome token count from market maker net balance + require(int(outcomeTokenCount) >= 0); + netOutcomeTokensSold[outcomeTokenIndex] = netOutcomeTokensSold[outcomeTokenIndex].sub(int(outcomeTokenCount)); + OutcomeTokenSale(msg.sender, outcomeTokenIndex, outcomeTokenCount, profit); + } + + /// @dev Buys all outcomes, then sells all shares of selected outcome which were bought, keeping + /// shares of all other outcome tokens. + /// @param outcomeTokenIndex Index of the outcome token to short sell + /// @param outcomeTokenCount Amount of outcome tokens to short sell + /// @param minProfit The minimum profit in collateral tokens to earn for short sold outcome tokens + /// @return Cost to short sell outcome in collateral tokens + function shortSell(uint8 outcomeTokenIndex, uint outcomeTokenCount, uint minProfit) + public + returns (uint cost) + { + // Buy all outcomes + require( eventContract.collateralToken().transferFrom(msg.sender, this, outcomeTokenCount) + && eventContract.collateralToken().approve(eventContract, outcomeTokenCount)); + eventContract.buyAllOutcomes(outcomeTokenCount); + // Short sell selected outcome + eventContract.outcomeTokens(outcomeTokenIndex).approve(this, outcomeTokenCount); + uint profit = this.sell(outcomeTokenIndex, outcomeTokenCount, minProfit); + cost = outcomeTokenCount - profit; + // Transfer outcome tokens to buyer + uint8 outcomeCount = eventContract.getOutcomeCount(); + for (uint8 i = 0; i < outcomeCount; i++) + if (i != outcomeTokenIndex) + require(eventContract.outcomeTokens(i).transfer(msg.sender, outcomeTokenCount)); + // Send change back to buyer + require(eventContract.collateralToken().transfer(msg.sender, profit)); + OutcomeTokenShortSale(msg.sender, outcomeTokenIndex, outcomeTokenCount, cost); + } + + /// @dev Calculates fee to be paid to market maker + /// @param outcomeTokenCost Cost for buying outcome tokens + /// @return Fee for trade + function calcMarketFee(uint outcomeTokenCost) + public + constant + returns (uint) + { + return outcomeTokenCost * fee / FEE_RANGE; + } +} diff --git a/test/compilationTests/gnosis/Markets/StandardMarketFactory.sol b/test/compilationTests/gnosis/Markets/StandardMarketFactory.sol new file mode 100644 index 00000000..101c37a2 --- /dev/null +++ b/test/compilationTests/gnosis/Markets/StandardMarketFactory.sol @@ -0,0 +1,25 @@ +pragma solidity ^0.4.11; +import "../Markets/MarketFactory.sol"; +import "../Markets/StandardMarket.sol"; + + +/// @title Market factory contract - Allows to create market contracts +/// @author Stefan George - <stefan@gnosis.pm> +contract StandardMarketFactory is MarketFactory { + + /* + * Public functions + */ + /// @dev Creates a new market contract + /// @param eventContract Event contract + /// @param marketMaker Market maker contract + /// @param fee Market fee + /// @return Market contract + function createMarket(Event eventContract, MarketMaker marketMaker, uint24 fee) + public + returns (Market market) + { + market = new StandardMarket(msg.sender, eventContract, marketMaker, fee); + MarketCreation(msg.sender, market, eventContract, marketMaker, fee); + } +} diff --git a/test/compilationTests/gnosis/Migrations.sol b/test/compilationTests/gnosis/Migrations.sol new file mode 100644 index 00000000..7e7fe8d4 --- /dev/null +++ b/test/compilationTests/gnosis/Migrations.sol @@ -0,0 +1,23 @@ +pragma solidity ^0.4.4; + +contract Migrations { + address public owner; + uint public last_completed_migration; + + modifier restricted() { + if (msg.sender == owner) _; + } + + function Migrations() { + owner = msg.sender; + } + + function setCompleted(uint completed) restricted { + last_completed_migration = completed; + } + + function upgrade(address new_address) restricted { + Migrations upgraded = Migrations(new_address); + upgraded.setCompleted(last_completed_migration); + } +} diff --git a/test/compilationTests/gnosis/Oracles/CentralizedOracle.sol b/test/compilationTests/gnosis/Oracles/CentralizedOracle.sol new file mode 100644 index 00000000..26acf526 --- /dev/null +++ b/test/compilationTests/gnosis/Oracles/CentralizedOracle.sol @@ -0,0 +1,90 @@ +pragma solidity ^0.4.11; +import "../Oracles/Oracle.sol"; + + +/// @title Centralized oracle contract - Allows the contract owner to set an outcome +/// @author Stefan George - <stefan@gnosis.pm> +contract CentralizedOracle is Oracle { + + /* + * Events + */ + event OwnerReplacement(address indexed newOwner); + event OutcomeAssignment(int outcome); + + /* + * Storage + */ + address public owner; + bytes public ipfsHash; + bool public isSet; + int public outcome; + + /* + * Modifiers + */ + modifier isOwner () { + // Only owner is allowed to proceed + require(msg.sender == owner); + _; + } + + /* + * Public functions + */ + /// @dev Constructor sets owner address and IPFS hash + /// @param _ipfsHash Hash identifying off chain event description + function CentralizedOracle(address _owner, bytes _ipfsHash) + public + { + // Description hash cannot be null + require(_ipfsHash.length == 46); + owner = _owner; + ipfsHash = _ipfsHash; + } + + /// @dev Replaces owner + /// @param newOwner New owner + function replaceOwner(address newOwner) + public + isOwner + { + // Result is not set yet + require(!isSet); + owner = newOwner; + OwnerReplacement(newOwner); + } + + /// @dev Sets event outcome + /// @param _outcome Event outcome + function setOutcome(int _outcome) + public + isOwner + { + // Result is not set yet + require(!isSet); + isSet = true; + outcome = _outcome; + OutcomeAssignment(_outcome); + } + + /// @dev Returns if winning outcome is set + /// @return Is outcome set? + function isOutcomeSet() + public + constant + returns (bool) + { + return isSet; + } + + /// @dev Returns outcome + /// @return Outcome + function getOutcome() + public + constant + returns (int) + { + return outcome; + } +} diff --git a/test/compilationTests/gnosis/Oracles/CentralizedOracleFactory.sol b/test/compilationTests/gnosis/Oracles/CentralizedOracleFactory.sol new file mode 100644 index 00000000..62a12cf4 --- /dev/null +++ b/test/compilationTests/gnosis/Oracles/CentralizedOracleFactory.sol @@ -0,0 +1,27 @@ +pragma solidity ^0.4.11; +import "../Oracles/CentralizedOracle.sol"; + + +/// @title Centralized oracle factory contract - Allows to create centralized oracle contracts +/// @author Stefan George - <stefan@gnosis.pm> +contract CentralizedOracleFactory { + + /* + * Events + */ + event CentralizedOracleCreation(address indexed creator, CentralizedOracle centralizedOracle, bytes ipfsHash); + + /* + * Public functions + */ + /// @dev Creates a new centralized oracle contract + /// @param ipfsHash Hash identifying off chain event description + /// @return Oracle contract + function createCentralizedOracle(bytes ipfsHash) + public + returns (CentralizedOracle centralizedOracle) + { + centralizedOracle = new CentralizedOracle(msg.sender, ipfsHash); + CentralizedOracleCreation(msg.sender, centralizedOracle, ipfsHash); + } +} diff --git a/test/compilationTests/gnosis/Oracles/DifficultyOracle.sol b/test/compilationTests/gnosis/Oracles/DifficultyOracle.sol new file mode 100644 index 00000000..87351dfa --- /dev/null +++ b/test/compilationTests/gnosis/Oracles/DifficultyOracle.sol @@ -0,0 +1,63 @@ +pragma solidity ^0.4.11; +import "../Oracles/Oracle.sol"; + + +/// @title Difficulty oracle contract - Oracle to resolve difficulty events at given block +/// @author Stefan George - <stefan@gnosis.pm> +contract DifficultyOracle is Oracle { + + /* + * Events + */ + event OutcomeAssignment(uint difficulty); + + /* + * Storage + */ + uint public blockNumber; + uint public difficulty; + + /* + * Public functions + */ + /// @dev Contract constructor validates and sets target block number + /// @param _blockNumber Target block number + function DifficultyOracle(uint _blockNumber) + public + { + // Block has to be in the future + require(_blockNumber > block.number); + blockNumber = _blockNumber; + } + + /// @dev Sets difficulty as winning outcome for specified block + function setOutcome() + public + { + // Block number was reached and outcome was not set yet + require(block.number >= blockNumber && difficulty == 0); + difficulty = block.difficulty; + OutcomeAssignment(difficulty); + } + + /// @dev Returns if difficulty is set + /// @return Is outcome set? + function isOutcomeSet() + public + constant + returns (bool) + { + // Difficulty is always bigger than 0 + return difficulty > 0; + } + + /// @dev Returns difficulty + /// @return Outcome + function getOutcome() + public + constant + returns (int) + { + return int(difficulty); + } +} diff --git a/test/compilationTests/gnosis/Oracles/DifficultyOracleFactory.sol b/test/compilationTests/gnosis/Oracles/DifficultyOracleFactory.sol new file mode 100644 index 00000000..2e97362c --- /dev/null +++ b/test/compilationTests/gnosis/Oracles/DifficultyOracleFactory.sol @@ -0,0 +1,27 @@ +pragma solidity ^0.4.11; +import "../Oracles/DifficultyOracle.sol"; + + +/// @title Difficulty oracle factory contract - Allows to create difficulty oracle contracts +/// @author Stefan George - <stefan@gnosis.pm> +contract DifficultyOracleFactory { + + /* + * Events + */ + event DifficultyOracleCreation(address indexed creator, DifficultyOracle difficultyOracle, uint blockNumber); + + /* + * Public functions + */ + /// @dev Creates a new difficulty oracle contract + /// @param blockNumber Target block number + /// @return Oracle contract + function createDifficultyOracle(uint blockNumber) + public + returns (DifficultyOracle difficultyOracle) + { + difficultyOracle = new DifficultyOracle(blockNumber); + DifficultyOracleCreation(msg.sender, difficultyOracle, blockNumber); + } +} diff --git a/test/compilationTests/gnosis/Oracles/FutarchyOracle.sol b/test/compilationTests/gnosis/Oracles/FutarchyOracle.sol new file mode 100644 index 00000000..524103d8 --- /dev/null +++ b/test/compilationTests/gnosis/Oracles/FutarchyOracle.sol @@ -0,0 +1,169 @@ +pragma solidity ^0.4.11; +import "../Oracles/Oracle.sol"; +import "../Events/EventFactory.sol"; +import "../Markets/MarketFactory.sol"; + + +/// @title Futarchy oracle contract - Allows to create an oracle based on market behaviour +/// @author Stefan George - <stefan@gnosis.pm> +contract FutarchyOracle is Oracle { + using Math for *; + + /* + * Events + */ + event FutarchyFunding(uint funding); + event FutarchyClosing(); + event OutcomeAssignment(uint winningMarketIndex); + + /* + * Constants + */ + uint8 public constant LONG = 1; + + /* + * Storage + */ + address creator; + Market[] public markets; + CategoricalEvent public categoricalEvent; + uint public deadline; + uint public winningMarketIndex; + bool public isSet; + + /* + * Modifiers + */ + modifier isCreator () { + // Only creator is allowed to proceed + require(msg.sender == creator); + _; + } + + /* + * Public functions + */ + /// @dev Constructor creates events and markets for futarchy oracle + /// @param _creator Oracle creator + /// @param eventFactory Event factory contract + /// @param collateralToken Tokens used as collateral in exchange for outcome tokens + /// @param oracle Oracle contract used to resolve the event + /// @param outcomeCount Number of event outcomes + /// @param lowerBound Lower bound for event outcome + /// @param upperBound Lower bound for event outcome + /// @param marketFactory Market factory contract + /// @param marketMaker Market maker contract + /// @param fee Market fee + /// @param _deadline Decision deadline + function FutarchyOracle( + address _creator, + EventFactory eventFactory, + Token collateralToken, + Oracle oracle, + uint8 outcomeCount, + int lowerBound, + int upperBound, + MarketFactory marketFactory, + MarketMaker marketMaker, + uint24 fee, + uint _deadline + ) + public + { + // Deadline is in the future + require(_deadline > now); + // Create decision event + categoricalEvent = eventFactory.createCategoricalEvent(collateralToken, this, outcomeCount); + // Create outcome events + for (uint8 i = 0; i < categoricalEvent.getOutcomeCount(); i++) { + ScalarEvent scalarEvent = eventFactory.createScalarEvent( + categoricalEvent.outcomeTokens(i), + oracle, + lowerBound, + upperBound + ); + markets.push(marketFactory.createMarket(scalarEvent, marketMaker, fee)); + } + creator = _creator; + deadline = _deadline; + } + + /// @dev Funds all markets with equal amount of funding + /// @param funding Amount of funding + function fund(uint funding) + public + isCreator + { + // Buy all outcomes + require( categoricalEvent.collateralToken().transferFrom(creator, this, funding) + && categoricalEvent.collateralToken().approve(categoricalEvent, funding)); + categoricalEvent.buyAllOutcomes(funding); + // Fund each market with outcome tokens from categorical event + for (uint8 i = 0; i < markets.length; i++) { + Market market = markets[i]; + // Approve funding for market + require(market.eventContract().collateralToken().approve(market, funding)); + market.fund(funding); + } + FutarchyFunding(funding); + } + + /// @dev Closes market for winning outcome and redeems winnings and sends all collateral tokens to creator + function close() + public + isCreator + { + // Winning outcome has to be set + Market market = markets[uint(getOutcome())]; + require(categoricalEvent.isOutcomeSet() && market.eventContract().isOutcomeSet()); + // Close market and transfer all outcome tokens from winning outcome to this contract + market.close(); + market.eventContract().redeemWinnings(); + market.withdrawFees(); + // Redeem collateral token for winning outcome tokens and transfer collateral tokens to creator + categoricalEvent.redeemWinnings(); + require(categoricalEvent.collateralToken().transfer(creator, categoricalEvent.collateralToken().balanceOf(this))); + FutarchyClosing(); + } + + /// @dev Allows to set the oracle outcome based on the market with largest long position + function setOutcome() + public + { + // Outcome is not set yet and deadline has passed + require(!isSet && deadline <= now); + // Find market with highest marginal price for long outcome tokens + uint highestMarginalPrice = markets[0].marketMaker().calcMarginalPrice(markets[0], LONG); + uint highestIndex = 0; + for (uint8 i = 1; i < markets.length; i++) { + uint marginalPrice = markets[i].marketMaker().calcMarginalPrice(markets[i], LONG); + if (marginalPrice > highestMarginalPrice) { + highestMarginalPrice = marginalPrice; + highestIndex = i; + } + } + winningMarketIndex = highestIndex; + isSet = true; + OutcomeAssignment(winningMarketIndex); + } + + /// @dev Returns if winning outcome is set + /// @return Is outcome set? + function isOutcomeSet() + public + constant + returns (bool) + { + return isSet; + } + + /// @dev Returns winning outcome + /// @return Outcome + function getOutcome() + public + constant + returns (int) + { + return int(winningMarketIndex); + } +} diff --git a/test/compilationTests/gnosis/Oracles/FutarchyOracleFactory.sol b/test/compilationTests/gnosis/Oracles/FutarchyOracleFactory.sol new file mode 100644 index 00000000..62eab4f0 --- /dev/null +++ b/test/compilationTests/gnosis/Oracles/FutarchyOracleFactory.sol @@ -0,0 +1,95 @@ +pragma solidity ^0.4.11; +import "../Oracles/FutarchyOracle.sol"; + + +/// @title Futarchy oracle factory contract - Allows to create Futarchy oracle contracts +/// @author Stefan George - <stefan@gnosis.pm> +contract FutarchyOracleFactory { + + /* + * Events + */ + event FutarchyOracleCreation( + address indexed creator, + FutarchyOracle futarchyOracle, + Token collateralToken, + Oracle oracle, + uint8 outcomeCount, + int lowerBound, + int upperBound, + MarketFactory marketFactory, + MarketMaker marketMaker, + uint24 fee, + uint deadline + ); + + /* + * Storage + */ + EventFactory eventFactory; + + /* + * Public functions + */ + /// @dev Constructor sets event factory contract + /// @param _eventFactory Event factory contract + function FutarchyOracleFactory(EventFactory _eventFactory) + public + { + require(address(_eventFactory) != 0); + eventFactory = _eventFactory; + } + + /// @dev Creates a new Futarchy oracle contract + /// @param collateralToken Tokens used as collateral in exchange for outcome tokens + /// @param oracle Oracle contract used to resolve the event + /// @param outcomeCount Number of event outcomes + /// @param lowerBound Lower bound for event outcome + /// @param upperBound Lower bound for event outcome + /// @param marketFactory Market factory contract + /// @param marketMaker Market maker contract + /// @param fee Market fee + /// @param deadline Decision deadline + /// @return Oracle contract + function createFutarchyOracle( + Token collateralToken, + Oracle oracle, + uint8 outcomeCount, + int lowerBound, + int upperBound, + MarketFactory marketFactory, + MarketMaker marketMaker, + uint24 fee, + uint deadline + ) + public + returns (FutarchyOracle futarchyOracle) + { + futarchyOracle = new FutarchyOracle( + msg.sender, + eventFactory, + collateralToken, + oracle, + outcomeCount, + lowerBound, + upperBound, + marketFactory, + marketMaker, + fee, + deadline + ); + FutarchyOracleCreation( + msg.sender, + futarchyOracle, + collateralToken, + oracle, + outcomeCount, + lowerBound, + upperBound, + marketFactory, + marketMaker, + fee, + deadline + ); + } +} diff --git a/test/compilationTests/gnosis/Oracles/MajorityOracle.sol b/test/compilationTests/gnosis/Oracles/MajorityOracle.sol new file mode 100644 index 00000000..1562ce48 --- /dev/null +++ b/test/compilationTests/gnosis/Oracles/MajorityOracle.sol @@ -0,0 +1,89 @@ +pragma solidity ^0.4.11; +import "../Oracles/Oracle.sol"; + + +/// @title Majority oracle contract - Allows to resolve an event based on multiple oracles with majority vote +/// @author Stefan George - <stefan@gnosis.pm> +contract MajorityOracle is Oracle { + + /* + * Storage + */ + Oracle[] public oracles; + + /* + * Public functions + */ + /// @dev Allows to create an oracle for a majority vote based on other oracles + /// @param _oracles List of oracles taking part in the majority vote + function MajorityOracle(Oracle[] _oracles) + public + { + // At least 2 oracles should be defined + require(_oracles.length > 2); + for (uint i = 0; i < _oracles.length; i++) + // Oracle address cannot be null + require(address(_oracles[i]) != 0); + oracles = _oracles; + } + + /// @dev Allows to registers oracles for a majority vote + /// @return Is outcome set? + /// @return Outcome + function getStatusAndOutcome() + public + returns (bool outcomeSet, int outcome) + { + uint i; + int[] memory outcomes = new int[](oracles.length); + uint[] memory validations = new uint[](oracles.length); + for (i = 0; i < oracles.length; i++) + if (oracles[i].isOutcomeSet()) { + int _outcome = oracles[i].getOutcome(); + for (uint j = 0; j <= i; j++) + if (_outcome == outcomes[j]) { + validations[j] += 1; + break; + } + else if (validations[j] == 0) { + outcomes[j] = _outcome; + validations[j] = 1; + break; + } + } + uint outcomeValidations = 0; + uint outcomeIndex = 0; + for (i = 0; i < oracles.length; i++) + if (validations[i] > outcomeValidations) { + outcomeValidations = validations[i]; + outcomeIndex = i; + } + // There is a majority vote + if (outcomeValidations * 2 > oracles.length) { + outcomeSet = true; + outcome = outcomes[outcomeIndex]; + } + } + + /// @dev Returns if winning outcome is set + /// @return Is outcome set? + function isOutcomeSet() + public + constant + returns (bool) + { + var (outcomeSet, ) = getStatusAndOutcome(); + return outcomeSet; + } + + /// @dev Returns winning outcome + /// @return Outcome + function getOutcome() + public + constant + returns (int) + { + var (, winningOutcome) = getStatusAndOutcome(); + return winningOutcome; + } +} diff --git a/test/compilationTests/gnosis/Oracles/MajorityOracleFactory.sol b/test/compilationTests/gnosis/Oracles/MajorityOracleFactory.sol new file mode 100644 index 00000000..0024516a --- /dev/null +++ b/test/compilationTests/gnosis/Oracles/MajorityOracleFactory.sol @@ -0,0 +1,27 @@ +pragma solidity ^0.4.11; +import "../Oracles/MajorityOracle.sol"; + + +/// @title Majority oracle factory contract - Allows to create majority oracle contracts +/// @author Stefan George - <stefan@gnosis.pm> +contract MajorityOracleFactory { + + /* + * Events + */ + event MajorityOracleCreation(address indexed creator, MajorityOracle majorityOracle, Oracle[] oracles); + + /* + * Public functions + */ + /// @dev Creates a new majority oracle contract + /// @param oracles List of oracles taking part in the majority vote + /// @return Oracle contract + function createMajorityOracle(Oracle[] oracles) + public + returns (MajorityOracle majorityOracle) + { + majorityOracle = new MajorityOracle(oracles); + MajorityOracleCreation(msg.sender, majorityOracle, oracles); + } +} diff --git a/test/compilationTests/gnosis/Oracles/Oracle.sol b/test/compilationTests/gnosis/Oracles/Oracle.sol new file mode 100644 index 00000000..cf96eb9f --- /dev/null +++ b/test/compilationTests/gnosis/Oracles/Oracle.sol @@ -0,0 +1,9 @@ +pragma solidity ^0.4.11; + + +/// @title Abstract oracle contract - Functions to be implemented by oracles +contract Oracle { + + function isOutcomeSet() public constant returns (bool); + function getOutcome() public constant returns (int); +} diff --git a/test/compilationTests/gnosis/Oracles/SignedMessageOracle.sol b/test/compilationTests/gnosis/Oracles/SignedMessageOracle.sol new file mode 100644 index 00000000..d541ab46 --- /dev/null +++ b/test/compilationTests/gnosis/Oracles/SignedMessageOracle.sol @@ -0,0 +1,102 @@ +pragma solidity ^0.4.11; +import "../Oracles/Oracle.sol"; + + +/// @title Signed message oracle contract - Allows to set an outcome with a signed message +/// @author Stefan George - <stefan@gnosis.pm> +contract SignedMessageOracle is Oracle { + + /* + * Events + */ + event SignerReplacement(address indexed newSigner); + event OutcomeAssignment(int outcome); + + /* + * Storage + */ + address public signer; + bytes32 public descriptionHash; + uint nonce; + bool public isSet; + int public outcome; + + /* + * Modifiers + */ + modifier isSigner () { + // Only signer is allowed to proceed + require(msg.sender == signer); + _; + } + + /* + * Public functions + */ + /// @dev Constructor sets signer address based on signature + /// @param _descriptionHash Hash identifying off chain event description + /// @param v Signature parameter + /// @param r Signature parameter + /// @param s Signature parameter + function SignedMessageOracle(bytes32 _descriptionHash, uint8 v, bytes32 r, bytes32 s) + public + { + signer = ecrecover(_descriptionHash, v, r, s); + descriptionHash = _descriptionHash; + } + + /// @dev Replaces signer + /// @param newSigner New signer + /// @param _nonce Unique nonce to prevent replay attacks + /// @param v Signature parameter + /// @param r Signature parameter + /// @param s Signature parameter + function replaceSigner(address newSigner, uint _nonce, uint8 v, bytes32 r, bytes32 s) + public + isSigner + { + // Result is not set yet and nonce and signer are valid + require( !isSet + && _nonce > nonce + && signer == ecrecover(keccak256(descriptionHash, newSigner, _nonce), v, r, s)); + nonce = _nonce; + signer = newSigner; + SignerReplacement(newSigner); + } + + /// @dev Sets outcome based on signed message + /// @param _outcome Signed event outcome + /// @param v Signature parameter + /// @param r Signature parameter + /// @param s Signature parameter + function setOutcome(int _outcome, uint8 v, bytes32 r, bytes32 s) + public + { + // Result is not set yet and signer is valid + require( !isSet + && signer == ecrecover(keccak256(descriptionHash, _outcome), v, r, s)); + isSet = true; + outcome = _outcome; + OutcomeAssignment(_outcome); + } + + /// @dev Returns if winning outcome + /// @return Is outcome set? + function isOutcomeSet() + public + constant + returns (bool) + { + return isSet; + } + + /// @dev Returns winning outcome + /// @return Outcome + function getOutcome() + public + constant + returns (int) + { + return outcome; + } +} diff --git a/test/compilationTests/gnosis/Oracles/SignedMessageOracleFactory.sol b/test/compilationTests/gnosis/Oracles/SignedMessageOracleFactory.sol new file mode 100644 index 00000000..0884d8ca --- /dev/null +++ b/test/compilationTests/gnosis/Oracles/SignedMessageOracleFactory.sol @@ -0,0 +1,31 @@ +pragma solidity ^0.4.11; +import "../Oracles/SignedMessageOracle.sol"; + + +/// @title Signed message oracle factory contract - Allows to create signed message oracle contracts +/// @author Stefan George - <stefan@gnosis.pm> +contract SignedMessageOracleFactory { + + /* + * Events + */ + event SignedMessageOracleCreation(address indexed creator, SignedMessageOracle signedMessageOracle, address oracle); + + /* + * Public functions + */ + /// @dev Creates a new signed message oracle contract + /// @param descriptionHash Hash identifying off chain event description + /// @param v Signature parameter + /// @param r Signature parameter + /// @param s Signature parameter + /// @return Oracle contract + function createSignedMessageOracle(bytes32 descriptionHash, uint8 v, bytes32 r, bytes32 s) + public + returns (SignedMessageOracle signedMessageOracle) + { + signedMessageOracle = new SignedMessageOracle(descriptionHash, v, r, s); + address oracle = ecrecover(descriptionHash, v, r, s); + SignedMessageOracleCreation(msg.sender, signedMessageOracle, oracle); + } +} diff --git a/test/compilationTests/gnosis/Oracles/UltimateOracle.sol b/test/compilationTests/gnosis/Oracles/UltimateOracle.sol new file mode 100644 index 00000000..fe8b4ec7 --- /dev/null +++ b/test/compilationTests/gnosis/Oracles/UltimateOracle.sol @@ -0,0 +1,192 @@ +pragma solidity ^0.4.11; +import "../Oracles/Oracle.sol"; +import "../Tokens/Token.sol"; +import "../Utils/Math.sol"; + + +/// @title Ultimate oracle contract - Allows to swap oracle result for ultimate oracle result +/// @author Stefan George - <stefan@gnosis.pm> +contract UltimateOracle is Oracle { + using Math for *; + + /* + * Events + */ + event ForwardedOracleOutcomeAssignment(int outcome); + event OutcomeChallenge(address indexed sender, int outcome); + event OutcomeVote(address indexed sender, int outcome, uint amount); + event Withdrawal(address indexed sender, uint amount); + + /* + * Storage + */ + Oracle public forwardedOracle; + Token public collateralToken; + uint8 public spreadMultiplier; + uint public challengePeriod; + uint public challengeAmount; + uint public frontRunnerPeriod; + + int public forwardedOutcome; + uint public forwardedOutcomeSetTimestamp; + int public frontRunner; + uint public frontRunnerSetTimestamp; + + uint public totalAmount; + mapping (int => uint) public totalOutcomeAmounts; + mapping (address => mapping (int => uint)) public outcomeAmounts; + + /* + * Public functions + */ + /// @dev Constructor sets ultimate oracle properties + /// @param _forwardedOracle Oracle address + /// @param _collateralToken Collateral token address + /// @param _spreadMultiplier Defines the spread as a multiple of the money bet on other outcomes + /// @param _challengePeriod Time to challenge oracle outcome + /// @param _challengeAmount Amount to challenge the outcome + /// @param _frontRunnerPeriod Time to overbid the front-runner + function UltimateOracle( + Oracle _forwardedOracle, + Token _collateralToken, + uint8 _spreadMultiplier, + uint _challengePeriod, + uint _challengeAmount, + uint _frontRunnerPeriod + ) + public + { + // Validate inputs + require( address(_forwardedOracle) != 0 + && address(_collateralToken) != 0 + && _spreadMultiplier >= 2 + && _challengePeriod > 0 + && _challengeAmount > 0 + && _frontRunnerPeriod > 0); + forwardedOracle = _forwardedOracle; + collateralToken = _collateralToken; + spreadMultiplier = _spreadMultiplier; + challengePeriod = _challengePeriod; + challengeAmount = _challengeAmount; + frontRunnerPeriod = _frontRunnerPeriod; + } + + /// @dev Allows to set oracle outcome + function setForwardedOutcome() + public + { + // There was no challenge and the outcome was not set yet in the ultimate oracle but in the forwarded oracle + require( !isChallenged() + && forwardedOutcomeSetTimestamp == 0 + && forwardedOracle.isOutcomeSet()); + forwardedOutcome = forwardedOracle.getOutcome(); + forwardedOutcomeSetTimestamp = now; + ForwardedOracleOutcomeAssignment(forwardedOutcome); + } + + /// @dev Allows to challenge the oracle outcome + /// @param _outcome Outcome to bid on + function challengeOutcome(int _outcome) + public + { + // There was no challenge yet or the challenge period expired + require( !isChallenged() + && !isChallengePeriodOver() + && collateralToken.transferFrom(msg.sender, this, challengeAmount)); + outcomeAmounts[msg.sender][_outcome] = challengeAmount; + totalOutcomeAmounts[_outcome] = challengeAmount; + totalAmount = challengeAmount; + frontRunner = _outcome; + frontRunnerSetTimestamp = now; + OutcomeChallenge(msg.sender, _outcome); + } + + /// @dev Allows to challenge the oracle outcome + /// @param _outcome Outcome to bid on + /// @param amount Amount to bid + function voteForOutcome(int _outcome, uint amount) + public + { + uint maxAmount = (totalAmount - totalOutcomeAmounts[_outcome]).mul(spreadMultiplier); + if (amount > maxAmount) + amount = maxAmount; + // Outcome is challenged and front runner period is not over yet and tokens can be transferred + require( isChallenged() + && !isFrontRunnerPeriodOver() + && collateralToken.transferFrom(msg.sender, this, amount)); + outcomeAmounts[msg.sender][_outcome] = outcomeAmounts[msg.sender][_outcome].add(amount); + totalOutcomeAmounts[_outcome] = totalOutcomeAmounts[_outcome].add(amount); + totalAmount = totalAmount.add(amount); + if (_outcome != frontRunner && totalOutcomeAmounts[_outcome] > totalOutcomeAmounts[frontRunner]) + { + frontRunner = _outcome; + frontRunnerSetTimestamp = now; + } + OutcomeVote(msg.sender, _outcome, amount); + } + + /// @dev Withdraws winnings for user + /// @return Winnings + function withdraw() + public + returns (uint amount) + { + // Outcome was challenged and ultimate outcome decided + require(isFrontRunnerPeriodOver()); + amount = totalAmount.mul(outcomeAmounts[msg.sender][frontRunner]) / totalOutcomeAmounts[frontRunner]; + outcomeAmounts[msg.sender][frontRunner] = 0; + // Transfer earnings to contributor + require(collateralToken.transfer(msg.sender, amount)); + Withdrawal(msg.sender, amount); + } + + /// @dev Checks if time to challenge the outcome is over + /// @return Is challenge period over? + function isChallengePeriodOver() + public + returns (bool) + { + return forwardedOutcomeSetTimestamp != 0 && now.sub(forwardedOutcomeSetTimestamp) > challengePeriod; + } + + /// @dev Checks if time to overbid the front runner is over + /// @return Is front runner period over? + function isFrontRunnerPeriodOver() + public + returns (bool) + { + return frontRunnerSetTimestamp != 0 && now.sub(frontRunnerSetTimestamp) > frontRunnerPeriod; + } + + /// @dev Checks if outcome was challenged + /// @return Is challenged? + function isChallenged() + public + returns (bool) + { + return frontRunnerSetTimestamp != 0; + } + + /// @dev Returns if winning outcome is set + /// @return Is outcome set? + function isOutcomeSet() + public + constant + returns (bool) + { + return isChallengePeriodOver() && !isChallenged() + || isFrontRunnerPeriodOver(); + } + + /// @dev Returns winning outcome + /// @return Outcome + function getOutcome() + public + constant + returns (int) + { + if (isFrontRunnerPeriodOver()) + return frontRunner; + return forwardedOutcome; + } +} diff --git a/test/compilationTests/gnosis/Oracles/UltimateOracleFactory.sol b/test/compilationTests/gnosis/Oracles/UltimateOracleFactory.sol new file mode 100644 index 00000000..67f8a96e --- /dev/null +++ b/test/compilationTests/gnosis/Oracles/UltimateOracleFactory.sol @@ -0,0 +1,64 @@ +pragma solidity ^0.4.11; +import "../Oracles/UltimateOracle.sol"; + + +/// @title Ultimate oracle factory contract - Allows to create ultimate oracle contracts +/// @author Stefan George - <stefan@gnosis.pm> +contract UltimateOracleFactory { + + /* + * Events + */ + event UltimateOracleCreation( + address indexed creator, + UltimateOracle ultimateOracle, + Oracle oracle, + Token collateralToken, + uint8 spreadMultiplier, + uint challengePeriod, + uint challengeAmount, + uint frontRunnerPeriod + ); + + /* + * Public functions + */ + /// @dev Creates a new ultimate Oracle contract + /// @param oracle Oracle address + /// @param collateralToken Collateral token address + /// @param spreadMultiplier Defines the spread as a multiple of the money bet on other outcomes + /// @param challengePeriod Time to challenge oracle outcome + /// @param challengeAmount Amount to challenge the outcome + /// @param frontRunnerPeriod Time to overbid the front-runner + /// @return Oracle contract + function createUltimateOracle( + Oracle oracle, + Token collateralToken, + uint8 spreadMultiplier, + uint challengePeriod, + uint challengeAmount, + uint frontRunnerPeriod + ) + public + returns (UltimateOracle ultimateOracle) + { + ultimateOracle = new UltimateOracle( + oracle, + collateralToken, + spreadMultiplier, + challengePeriod, + challengeAmount, + frontRunnerPeriod + ); + UltimateOracleCreation( + msg.sender, + ultimateOracle, + oracle, + collateralToken, + spreadMultiplier, + challengePeriod, + challengeAmount, + frontRunnerPeriod + ); + } +} diff --git a/test/compilationTests/gnosis/README.md b/test/compilationTests/gnosis/README.md new file mode 100644 index 00000000..e939cd26 --- /dev/null +++ b/test/compilationTests/gnosis/README.md @@ -0,0 +1,3 @@ +Gnosis contracts, originally from + +https://github.com/gnosis/gnosis-contracts diff --git a/test/compilationTests/gnosis/Tokens/EtherToken.sol b/test/compilationTests/gnosis/Tokens/EtherToken.sol new file mode 100644 index 00000000..f6e73e5a --- /dev/null +++ b/test/compilationTests/gnosis/Tokens/EtherToken.sol @@ -0,0 +1,47 @@ +pragma solidity ^0.4.11; +import "../Tokens/StandardToken.sol"; + + +/// @title Token contract - Token exchanging Ether 1:1 +/// @author Stefan George - <stefan@gnosis.pm> +contract EtherToken is StandardToken { + using Math for *; + + /* + * Events + */ + event Deposit(address indexed sender, uint value); + event Withdrawal(address indexed receiver, uint value); + + /* + * Constants + */ + string public constant name = "Ether Token"; + string public constant symbol = "ETH"; + uint8 public constant decimals = 18; + + /* + * Public functions + */ + /// @dev Buys tokens with Ether, exchanging them 1:1 + function deposit() + public + payable + { + balances[msg.sender] = balances[msg.sender].add(msg.value); + totalTokens = totalTokens.add(msg.value); + Deposit(msg.sender, msg.value); + } + + /// @dev Sells tokens in exchange for Ether, exchanging them 1:1 + /// @param value Number of tokens to sell + function withdraw(uint value) + public + { + // Balance covers value + balances[msg.sender] = balances[msg.sender].sub(value); + totalTokens = totalTokens.sub(value); + msg.sender.transfer(value); + Withdrawal(msg.sender, value); + } +} diff --git a/test/compilationTests/gnosis/Tokens/OutcomeToken.sol b/test/compilationTests/gnosis/Tokens/OutcomeToken.sol new file mode 100644 index 00000000..fd1fa590 --- /dev/null +++ b/test/compilationTests/gnosis/Tokens/OutcomeToken.sol @@ -0,0 +1,63 @@ +pragma solidity ^0.4.11; +import "../Tokens/StandardToken.sol"; + + +/// @title Outcome token contract - Issuing and revoking outcome tokens +/// @author Stefan George - <stefan@gnosis.pm> +contract OutcomeToken is StandardToken { + using Math for *; + + /* + * Events + */ + event Issuance(address indexed owner, uint amount); + event Revocation(address indexed owner, uint amount); + + /* + * Storage + */ + address public eventContract; + + /* + * Modifiers + */ + modifier isEventContract () { + // Only event contract is allowed to proceed + require(msg.sender == eventContract); + _; + } + + /* + * Public functions + */ + /// @dev Constructor sets events contract address + function OutcomeToken() + public + { + eventContract = msg.sender; + } + + /// @dev Events contract issues new tokens for address. Returns success + /// @param _for Address of receiver + /// @param outcomeTokenCount Number of tokens to issue + function issue(address _for, uint outcomeTokenCount) + public + isEventContract + { + balances[_for] = balances[_for].add(outcomeTokenCount); + totalTokens = totalTokens.add(outcomeTokenCount); + Issuance(_for, outcomeTokenCount); + } + + /// @dev Events contract revokes tokens for address. Returns success + /// @param _for Address of token holder + /// @param outcomeTokenCount Number of tokens to revoke + function revoke(address _for, uint outcomeTokenCount) + public + isEventContract + { + balances[_for] = balances[_for].sub(outcomeTokenCount); + totalTokens = totalTokens.sub(outcomeTokenCount); + Revocation(_for, outcomeTokenCount); + } +} diff --git a/test/compilationTests/gnosis/Tokens/StandardToken.sol b/test/compilationTests/gnosis/Tokens/StandardToken.sol new file mode 100644 index 00000000..fc899ca6 --- /dev/null +++ b/test/compilationTests/gnosis/Tokens/StandardToken.sol @@ -0,0 +1,102 @@ +pragma solidity ^0.4.11; +import "../Tokens/Token.sol"; +import "../Utils/Math.sol"; + + +/// @title Standard token contract with overflow protection +contract StandardToken is Token { + using Math for *; + + /* + * Storage + */ + mapping (address => uint) balances; + mapping (address => mapping (address => uint)) allowances; + uint totalTokens; + + /* + * Public functions + */ + /// @dev Transfers sender's tokens to a given address. Returns success + /// @param to Address of token receiver + /// @param value Number of tokens to transfer + /// @return Was transfer successful? + function transfer(address to, uint value) + public + returns (bool) + { + if ( !balances[msg.sender].safeToSub(value) + || !balances[to].safeToAdd(value)) + return false; + balances[msg.sender] -= value; + balances[to] += value; + Transfer(msg.sender, to, value); + return true; + } + + /// @dev Allows allowed third party to transfer tokens from one address to another. Returns success + /// @param from Address from where tokens are withdrawn + /// @param to Address to where tokens are sent + /// @param value Number of tokens to transfer + /// @return Was transfer successful? + function transferFrom(address from, address to, uint value) + public + returns (bool) + { + if ( !balances[from].safeToSub(value) + || !allowances[from][msg.sender].safeToSub(value) + || !balances[to].safeToAdd(value)) + return false; + balances[from] -= value; + allowances[from][msg.sender] -= value; + balances[to] += value; + Transfer(from, to, value); + return true; + } + + /// @dev Sets approved amount of tokens for spender. Returns success + /// @param spender Address of allowed account + /// @param value Number of approved tokens + /// @return Was approval successful? + function approve(address spender, uint value) + public + returns (bool) + { + allowances[msg.sender][spender] = value; + Approval(msg.sender, spender, value); + return true; + } + + /// @dev Returns number of allowed tokens for given address + /// @param owner Address of token owner + /// @param spender Address of token spender + /// @return Remaining allowance for spender + function allowance(address owner, address spender) + public + constant + returns (uint) + { + return allowances[owner][spender]; + } + + /// @dev Returns number of tokens owned by given address + /// @param owner Address of token owner + /// @return Balance of owner + function balanceOf(address owner) + public + constant + returns (uint) + { + return balances[owner]; + } + + /// @dev Returns total supply of tokens + /// @return Total supply + function totalSupply() + public + constant + returns (uint) + { + return totalTokens; + } +} diff --git a/test/compilationTests/gnosis/Tokens/Token.sol b/test/compilationTests/gnosis/Tokens/Token.sol new file mode 100644 index 00000000..19bb618b --- /dev/null +++ b/test/compilationTests/gnosis/Tokens/Token.sol @@ -0,0 +1,23 @@ +/// Implements ERC 20 Token standard: https://github.com/ethereum/EIPs/issues/20 +pragma solidity ^0.4.11; + + +/// @title Abstract token contract - Functions to be implemented by token contracts +contract Token { + + /* + * Events + */ + event Transfer(address indexed from, address indexed to, uint value); + event Approval(address indexed owner, address indexed spender, uint value); + + /* + * Public functions + */ + function transfer(address to, uint value) public returns (bool); + function transferFrom(address from, address to, uint value) public returns (bool); + function approve(address spender, uint value) public returns (bool); + function balanceOf(address owner) public constant returns (uint); + function allowance(address owner, address spender) public constant returns (uint); + function totalSupply() public constant returns (uint); +} diff --git a/test/compilationTests/gnosis/Utils/Math.sol b/test/compilationTests/gnosis/Utils/Math.sol new file mode 100644 index 00000000..95d95346 --- /dev/null +++ b/test/compilationTests/gnosis/Utils/Math.sol @@ -0,0 +1,340 @@ +pragma solidity ^0.4.11; + + +/// @title Math library - Allows calculation of logarithmic and exponential functions +/// @author Alan Lu - <alan.lu@gnosis.pm> +/// @author Stefan George - <stefan@gnosis.pm> +library Math { + + /* + * Constants + */ + // This is equal to 1 in our calculations + uint public constant ONE = 0x10000000000000000; + uint public constant LN2 = 0xb17217f7d1cf79ac; + uint public constant LOG2_E = 0x171547652b82fe177; + + /* + * Public functions + */ + /// @dev Returns natural exponential function value of given x + /// @param x x + /// @return e**x + function exp(int x) + public + constant + returns (uint) + { + // revert if x is > MAX_POWER, where + // MAX_POWER = int(mp.floor(mp.log(mpf(2**256 - 1) / ONE) * ONE)) + require(x <= 2454971259878909886679); + // return 0 if exp(x) is tiny, using + // MIN_POWER = int(mp.floor(mp.log(mpf(1) / ONE) * ONE)) + if (x < -818323753292969962227) + return 0; + // Transform so that e^x -> 2^x + x = x * int(ONE) / int(LN2); + // 2^x = 2^whole(x) * 2^frac(x) + // ^^^^^^^^^^ is a bit shift + // so Taylor expand on z = frac(x) + int shift; + uint z; + if (x >= 0) { + shift = x / int(ONE); + z = uint(x % int(ONE)); + } + else { + shift = x / int(ONE) - 1; + z = ONE - uint(-x % int(ONE)); + } + // 2^x = 1 + (ln 2) x + (ln 2)^2/2! x^2 + ... + // + // Can generate the z coefficients using mpmath and the following lines + // >>> from mpmath import mp + // >>> mp.dps = 100 + // >>> ONE = 0x10000000000000000 + // >>> print('\n'.join(hex(int(mp.log(2)**i / mp.factorial(i) * ONE)) for i in range(1, 7))) + // 0xb17217f7d1cf79ab + // 0x3d7f7bff058b1d50 + // 0xe35846b82505fc5 + // 0x276556df749cee5 + // 0x5761ff9e299cc4 + // 0xa184897c363c3 + uint zpow = z; + uint result = ONE; + result += 0xb17217f7d1cf79ab * zpow / ONE; + zpow = zpow * z / ONE; + result += 0x3d7f7bff058b1d50 * zpow / ONE; + zpow = zpow * z / ONE; + result += 0xe35846b82505fc5 * zpow / ONE; + zpow = zpow * z / ONE; + result += 0x276556df749cee5 * zpow / ONE; + zpow = zpow * z / ONE; + result += 0x5761ff9e299cc4 * zpow / ONE; + zpow = zpow * z / ONE; + result += 0xa184897c363c3 * zpow / ONE; + zpow = zpow * z / ONE; + result += 0xffe5fe2c4586 * zpow / ONE; + zpow = zpow * z / ONE; + result += 0x162c0223a5c8 * zpow / ONE; + zpow = zpow * z / ONE; + result += 0x1b5253d395e * zpow / ONE; + zpow = zpow * z / ONE; + result += 0x1e4cf5158b * zpow / ONE; + zpow = zpow * z / ONE; + result += 0x1e8cac735 * zpow / ONE; + zpow = zpow * z / ONE; + result += 0x1c3bd650 * zpow / ONE; + zpow = zpow * z / ONE; + result += 0x1816193 * zpow / ONE; + zpow = zpow * z / ONE; + result += 0x131496 * zpow / ONE; + zpow = zpow * z / ONE; + result += 0xe1b7 * zpow / ONE; + zpow = zpow * z / ONE; + result += 0x9c7 * zpow / ONE; + if (shift >= 0) { + if (result >> (256-shift) > 0) + return (2**256-1); + return result << shift; + } + else + return result >> (-shift); + } + + /// @dev Returns natural logarithm value of given x + /// @param x x + /// @return ln(x) + function ln(uint x) + public + constant + returns (int) + { + require(x > 0); + // binary search for floor(log2(x)) + int ilog2 = floorLog2(x); + int z; + if (ilog2 < 0) + z = int(x << uint(-ilog2)); + else + z = int(x >> uint(ilog2)); + // z = x * 2^-⌊log₂x⌋ + // so 1 <= z < 2 + // and ln z = ln x - ⌊log₂x⌋/log₂e + // so just compute ln z using artanh series + // and calculate ln x from that + int term = (z - int(ONE)) * int(ONE) / (z + int(ONE)); + int halflnz = term; + int termpow = term * term / int(ONE) * term / int(ONE); + halflnz += termpow / 3; + termpow = termpow * term / int(ONE) * term / int(ONE); + halflnz += termpow / 5; + termpow = termpow * term / int(ONE) * term / int(ONE); + halflnz += termpow / 7; + termpow = termpow * term / int(ONE) * term / int(ONE); + halflnz += termpow / 9; + termpow = termpow * term / int(ONE) * term / int(ONE); + halflnz += termpow / 11; + termpow = termpow * term / int(ONE) * term / int(ONE); + halflnz += termpow / 13; + termpow = termpow * term / int(ONE) * term / int(ONE); + halflnz += termpow / 15; + termpow = termpow * term / int(ONE) * term / int(ONE); + halflnz += termpow / 17; + termpow = termpow * term / int(ONE) * term / int(ONE); + halflnz += termpow / 19; + termpow = termpow * term / int(ONE) * term / int(ONE); + halflnz += termpow / 21; + termpow = termpow * term / int(ONE) * term / int(ONE); + halflnz += termpow / 23; + termpow = termpow * term / int(ONE) * term / int(ONE); + halflnz += termpow / 25; + return (ilog2 * int(ONE)) * int(ONE) / int(LOG2_E) + 2 * halflnz; + } + + /// @dev Returns base 2 logarithm value of given x + /// @param x x + /// @return logarithmic value + function floorLog2(uint x) + public + constant + returns (int lo) + { + lo = -64; + int hi = 193; + // I use a shift here instead of / 2 because it floors instead of rounding towards 0 + int mid = (hi + lo) >> 1; + while((lo + 1) < hi) { + if (mid < 0 && x << uint(-mid) < ONE || mid >= 0 && x >> uint(mid) < ONE) + hi = mid; + else + lo = mid; + mid = (hi + lo) >> 1; + } + } + + /// @dev Returns maximum of an array + /// @param nums Numbers to look through + /// @return Maximum number + function max(int[] nums) + public + constant + returns (int max) + { + require(nums.length > 0); + max = -2**255; + for (uint i = 0; i < nums.length; i++) + if (nums[i] > max) + max = nums[i]; + } + + /// @dev Returns whether an add operation causes an overflow + /// @param a First addend + /// @param b Second addend + /// @return Did no overflow occur? + function safeToAdd(uint a, uint b) + public + constant + returns (bool) + { + return a + b >= a; + } + + /// @dev Returns whether a subtraction operation causes an underflow + /// @param a Minuend + /// @param b Subtrahend + /// @return Did no underflow occur? + function safeToSub(uint a, uint b) + public + constant + returns (bool) + { + return a >= b; + } + + /// @dev Returns whether a multiply operation causes an overflow + /// @param a First factor + /// @param b Second factor + /// @return Did no overflow occur? + function safeToMul(uint a, uint b) + public + constant + returns (bool) + { + return b == 0 || a * b / b == a; + } + + /// @dev Returns sum if no overflow occurred + /// @param a First addend + /// @param b Second addend + /// @return Sum + function add(uint a, uint b) + public + constant + returns (uint) + { + require(safeToAdd(a, b)); + return a + b; + } + + /// @dev Returns difference if no overflow occurred + /// @param a Minuend + /// @param b Subtrahend + /// @return Difference + function sub(uint a, uint b) + public + constant + returns (uint) + { + require(safeToSub(a, b)); + return a - b; + } + + /// @dev Returns product if no overflow occurred + /// @param a First factor + /// @param b Second factor + /// @return Product + function mul(uint a, uint b) + public + constant + returns (uint) + { + require(safeToMul(a, b)); + return a * b; + } + + /// @dev Returns whether an add operation causes an overflow + /// @param a First addend + /// @param b Second addend + /// @return Did no overflow occur? + function safeToAdd(int a, int b) + public + constant + returns (bool) + { + return (b >= 0 && a + b >= a) || (b < 0 && a + b < a); + } + + /// @dev Returns whether a subtraction operation causes an underflow + /// @param a Minuend + /// @param b Subtrahend + /// @return Did no underflow occur? + function safeToSub(int a, int b) + public + constant + returns (bool) + { + return (b >= 0 && a - b <= a) || (b < 0 && a - b > a); + } + + /// @dev Returns whether a multiply operation causes an overflow + /// @param a First factor + /// @param b Second factor + /// @return Did no overflow occur? + function safeToMul(int a, int b) + public + constant + returns (bool) + { + return (b == 0) || (a * b / b == a); + } + + /// @dev Returns sum if no overflow occurred + /// @param a First addend + /// @param b Second addend + /// @return Sum + function add(int a, int b) + public + constant + returns (int) + { + require(safeToAdd(a, b)); + return a + b; + } + + /// @dev Returns difference if no overflow occurred + /// @param a Minuend + /// @param b Subtrahend + /// @return Difference + function sub(int a, int b) + public + constant + returns (int) + { + require(safeToSub(a, b)); + return a - b; + } + + /// @dev Returns product if no overflow occurred + /// @param a First factor + /// @param b Second factor + /// @return Product + function mul(int a, int b) + public + constant + returns (int) + { + require(safeToMul(a, b)); + return a * b; + } +} diff --git a/test/compilationTests/milestonetracker/LICENSE b/test/compilationTests/milestonetracker/LICENSE new file mode 100644 index 00000000..733c0723 --- /dev/null +++ b/test/compilationTests/milestonetracker/LICENSE @@ -0,0 +1,675 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + {one line to give the program's name and a brief idea of what it does.} + Copyright (C) {year} {name of author} + + This program 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. + + This program 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 this program. If not, see <http://www.gnu.org/licenses/>. + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + {project} Copyright (C) {year} {fullname} + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +<http://www.gnu.org/licenses/>. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +<http://www.gnu.org/philosophy/why-not-lgpl.html>. + diff --git a/test/compilationTests/milestonetracker/MilestoneTracker.sol b/test/compilationTests/milestonetracker/MilestoneTracker.sol new file mode 100644 index 00000000..318330df --- /dev/null +++ b/test/compilationTests/milestonetracker/MilestoneTracker.sol @@ -0,0 +1,367 @@ +pragma solidity ^0.4.6; + +/* + Copyright 2016, Jordi Baylina + + This program 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. + + This program 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 this program. If not, see <http://www.gnu.org/licenses/>. + */ + +/// @title MilestoneTracker Contract +/// @author Jordi Baylina +/// @dev This contract tracks the + + +/// is rules the relation betwen a donor and a recipient +/// in order to guaranty to the donor that the job will be done and to guaranty +/// to the recipient that he will be paid + + +/// @dev We use the RLP library to decode RLP so that the donor can approve one +/// set of milestone changes at a time. +/// https://github.com/androlo/standard-contracts/blob/master/contracts/src/codec/RLP.sol +import "RLP.sol"; + + + +/// @dev This contract allows for `recipient` to set and modify milestones +contract MilestoneTracker { + using RLP for RLP.RLPItem; + using RLP for RLP.Iterator; + using RLP for bytes; + + struct Milestone { + string description; // Description of this milestone + string url; // A link to more information (swarm gateway) + uint minCompletionDate; // Earliest UNIX time the milestone can be paid + uint maxCompletionDate; // Latest UNIX time the milestone can be paid + address milestoneLeadLink; + // Similar to `recipient`but for this milestone + address reviewer; // Can reject the completion of this milestone + uint reviewTime; // How many seconds the reviewer has to review + address paymentSource; // Where the milestone payment is sent from + bytes payData; // Data defining how much ether is sent where + + MilestoneStatus status; // Current status of the milestone + // (Completed, AuthorizedForPayment...) + uint doneTime; // UNIX time when the milestone was marked DONE + } + + // The list of all the milestones. + Milestone[] public milestones; + + address public recipient; // Calls functions in the name of the recipient + address public donor; // Calls functions in the name of the donor + address public arbitrator; // Calls functions in the name of the arbitrator + + enum MilestoneStatus { + AcceptedAndInProgress, + Completed, + AuthorizedForPayment, + Canceled + } + + // True if the campaign has been canceled + bool public campaignCanceled; + + // True if an approval on a change to `milestones` is a pending + bool public changingMilestones; + + // The pending change to `milestones` encoded in RLP + bytes public proposedMilestones; + + + /// @dev The following modifiers only allow specific roles to call functions + /// with these modifiers + modifier onlyRecipient { if (msg.sender != recipient) throw; _; } + modifier onlyArbitrator { if (msg.sender != arbitrator) throw; _; } + modifier onlyDonor { if (msg.sender != donor) throw; _; } + + /// @dev The following modifiers prevent functions from being called if the + /// campaign has been canceled or if new milestones are being proposed + modifier campaignNotCanceled { if (campaignCanceled) throw; _; } + modifier notChanging { if (changingMilestones) throw; _; } + + // @dev Events to make the payment movements easy to find on the blockchain + event NewMilestoneListProposed(); + event NewMilestoneListUnproposed(); + event NewMilestoneListAccepted(); + event ProposalStatusChanged(uint idProposal, MilestoneStatus newProposal); + event CampaignCanceled(); + + +/////////// +// Constructor +/////////// + + /// @notice The Constructor creates the Milestone contract on the blockchain + /// @param _arbitrator Address assigned to be the arbitrator + /// @param _donor Address assigned to be the donor + /// @param _recipient Address assigned to be the recipient + function MilestoneTracker ( + address _arbitrator, + address _donor, + address _recipient + ) { + arbitrator = _arbitrator; + donor = _donor; + recipient = _recipient; + } + + +///////// +// Helper functions +///////// + + /// @return The number of milestones ever created even if they were canceled + function numberOfMilestones() constant returns (uint) { + return milestones.length; + } + + +//////// +// Change players +//////// + + /// @notice `onlyArbitrator` Reassigns the arbitrator to a new address + /// @param _newArbitrator The new arbitrator + function changeArbitrator(address _newArbitrator) onlyArbitrator { + arbitrator = _newArbitrator; + } + + /// @notice `onlyDonor` Reassigns the `donor` to a new address + /// @param _newDonor The new donor + function changeDonor(address _newDonor) onlyDonor { + donor = _newDonor; + } + + /// @notice `onlyRecipient` Reassigns the `recipient` to a new address + /// @param _newRecipient The new recipient + function changeRecipient(address _newRecipient) onlyRecipient { + recipient = _newRecipient; + } + + +//////////// +// Creation and modification of Milestones +//////////// + + /// @notice `onlyRecipient` Proposes new milestones or changes old + /// milestones, this will require a user interface to be built up to + /// support this functionality as asks for RLP encoded bytecode to be + /// generated, until this interface is built you can use this script: + /// https://github.com/Giveth/milestonetracker/blob/master/js/milestonetracker_helper.js + /// the functions milestones2bytes and bytes2milestones will enable the + /// recipient to encode and decode a list of milestones, also see + /// https://github.com/Giveth/milestonetracker/blob/master/README.md + /// @param _newMilestones The RLP encoded list of milestones; each milestone + /// has these fields: + /// string description, + /// string url, + /// uint minCompletionDate, // seconds since 1/1/1970 (UNIX time) + /// uint maxCompletionDate, // seconds since 1/1/1970 (UNIX time) + /// address milestoneLeadLink, + /// address reviewer, + /// uint reviewTime + /// address paymentSource, + /// bytes payData, + function proposeMilestones(bytes _newMilestones + ) onlyRecipient campaignNotCanceled { + proposedMilestones = _newMilestones; + changingMilestones = true; + NewMilestoneListProposed(); + } + + +//////////// +// Normal actions that will change the state of the milestones +//////////// + + /// @notice `onlyRecipient` Cancels the proposed milestones and reactivates + /// the previous set of milestones + function unproposeMilestones() onlyRecipient campaignNotCanceled { + delete proposedMilestones; + changingMilestones = false; + NewMilestoneListUnproposed(); + } + + /// @notice `onlyDonor` Approves the proposed milestone list + /// @param _hashProposals The sha3() of the proposed milestone list's + /// bytecode; this confirms that the `donor` knows the set of milestones + /// they are approving + function acceptProposedMilestones(bytes32 _hashProposals + ) onlyDonor campaignNotCanceled { + + uint i; + + if (!changingMilestones) throw; + if (sha3(proposedMilestones) != _hashProposals) throw; + + // Cancel all the unfinished milestones + for (i=0; i<milestones.length; i++) { + if (milestones[i].status != MilestoneStatus.AuthorizedForPayment) { + milestones[i].status = MilestoneStatus.Canceled; + } + } + // Decode the RLP encoded milestones and add them to the milestones list + bytes memory mProposedMilestones = proposedMilestones; + + var itmProposals = mProposedMilestones.toRLPItem(true); + + if (!itmProposals.isList()) throw; + + var itrProposals = itmProposals.iterator(); + + while(itrProposals.hasNext()) { + + + var itmProposal = itrProposals.next(); + + Milestone milestone = milestones[milestones.length ++]; + + if (!itmProposal.isList()) throw; + + var itrProposal = itmProposal.iterator(); + + milestone.description = itrProposal.next().toAscii(); + milestone.url = itrProposal.next().toAscii(); + milestone.minCompletionDate = itrProposal.next().toUint(); + milestone.maxCompletionDate = itrProposal.next().toUint(); + milestone.milestoneLeadLink = itrProposal.next().toAddress(); + milestone.reviewer = itrProposal.next().toAddress(); + milestone.reviewTime = itrProposal.next().toUint(); + milestone.paymentSource = itrProposal.next().toAddress(); + milestone.payData = itrProposal.next().toData(); + + milestone.status = MilestoneStatus.AcceptedAndInProgress; + + } + + delete proposedMilestones; + changingMilestones = false; + NewMilestoneListAccepted(); + } + + /// @notice `onlyRecipientOrLeadLink`Marks a milestone as DONE and + /// ready for review + /// @param _idMilestone ID of the milestone that has been completed + function markMilestoneComplete(uint _idMilestone) + campaignNotCanceled notChanging + { + if (_idMilestone >= milestones.length) throw; + Milestone milestone = milestones[_idMilestone]; + if ( (msg.sender != milestone.milestoneLeadLink) + &&(msg.sender != recipient)) + throw; + if (milestone.status != MilestoneStatus.AcceptedAndInProgress) throw; + if (now < milestone.minCompletionDate) throw; + if (now > milestone.maxCompletionDate) throw; + milestone.status = MilestoneStatus.Completed; + milestone.doneTime = now; + ProposalStatusChanged(_idMilestone, milestone.status); + } + + /// @notice `onlyReviewer` Approves a specific milestone + /// @param _idMilestone ID of the milestone that is approved + function approveCompletedMilestone(uint _idMilestone) + campaignNotCanceled notChanging + { + if (_idMilestone >= milestones.length) throw; + Milestone milestone = milestones[_idMilestone]; + if ((msg.sender != milestone.reviewer) || + (milestone.status != MilestoneStatus.Completed)) throw; + + authorizePayment(_idMilestone); + } + + /// @notice `onlyReviewer` Rejects a specific milestone's completion and + /// reverts the `milestone.status` back to the `AcceptedAndInProgress` + /// state + /// @param _idMilestone ID of the milestone that is being rejected + function rejectMilestone(uint _idMilestone) + campaignNotCanceled notChanging + { + if (_idMilestone >= milestones.length) throw; + Milestone milestone = milestones[_idMilestone]; + if ((msg.sender != milestone.reviewer) || + (milestone.status != MilestoneStatus.Completed)) throw; + + milestone.status = MilestoneStatus.AcceptedAndInProgress; + ProposalStatusChanged(_idMilestone, milestone.status); + } + + /// @notice `onlyRecipientOrLeadLink` Sends the milestone payment as + /// specified in `payData`; the recipient can only call this after the + /// `reviewTime` has elapsed + /// @param _idMilestone ID of the milestone to be paid out + function requestMilestonePayment(uint _idMilestone + ) campaignNotCanceled notChanging { + if (_idMilestone >= milestones.length) throw; + Milestone milestone = milestones[_idMilestone]; + if ( (msg.sender != milestone.milestoneLeadLink) + &&(msg.sender != recipient)) + throw; + if ((milestone.status != MilestoneStatus.Completed) || + (now < milestone.doneTime + milestone.reviewTime)) + throw; + + authorizePayment(_idMilestone); + } + + /// @notice `onlyRecipient` Cancels a previously accepted milestone + /// @param _idMilestone ID of the milestone to be canceled + function cancelMilestone(uint _idMilestone) + onlyRecipient campaignNotCanceled notChanging + { + if (_idMilestone >= milestones.length) throw; + Milestone milestone = milestones[_idMilestone]; + if ((milestone.status != MilestoneStatus.AcceptedAndInProgress) && + (milestone.status != MilestoneStatus.Completed)) + throw; + + milestone.status = MilestoneStatus.Canceled; + ProposalStatusChanged(_idMilestone, milestone.status); + } + + /// @notice `onlyArbitrator` Forces a milestone to be paid out as long as it + /// has not been paid or canceled + /// @param _idMilestone ID of the milestone to be paid out + function arbitrateApproveMilestone(uint _idMilestone + ) onlyArbitrator campaignNotCanceled notChanging { + if (_idMilestone >= milestones.length) throw; + Milestone milestone = milestones[_idMilestone]; + if ((milestone.status != MilestoneStatus.AcceptedAndInProgress) && + (milestone.status != MilestoneStatus.Completed)) + throw; + authorizePayment(_idMilestone); + } + + /// @notice `onlyArbitrator` Cancels the entire campaign voiding all + /// milestones. + function arbitrateCancelCampaign() onlyArbitrator campaignNotCanceled { + campaignCanceled = true; + CampaignCanceled(); + } + + // @dev This internal function is executed when the milestone is paid out + function authorizePayment(uint _idMilestone) internal { + if (_idMilestone >= milestones.length) throw; + Milestone milestone = milestones[_idMilestone]; + // Recheck again to not pay twice + if (milestone.status == MilestoneStatus.AuthorizedForPayment) throw; + milestone.status = MilestoneStatus.AuthorizedForPayment; + if (!milestone.paymentSource.call.value(0)(milestone.payData)) + throw; + ProposalStatusChanged(_idMilestone, milestone.status); + } +} diff --git a/test/compilationTests/milestonetracker/README.md b/test/compilationTests/milestonetracker/README.md new file mode 100644 index 00000000..84fb980e --- /dev/null +++ b/test/compilationTests/milestonetracker/README.md @@ -0,0 +1,3 @@ +Giveth milestone tracker, originally from + +https://github.com/Giveth/milestonetracker/ diff --git a/test/compilationTests/milestonetracker/RLP.sol b/test/compilationTests/milestonetracker/RLP.sol new file mode 100644 index 00000000..5bb27bb2 --- /dev/null +++ b/test/compilationTests/milestonetracker/RLP.sol @@ -0,0 +1,416 @@ +pragma solidity ^0.4.6; + +/** +* @title RLPReader +* +* RLPReader is used to read and parse RLP encoded data in memory. +* +* @author Andreas Olofsson (androlo1980@gmail.com) +*/ +library RLP { + + uint constant DATA_SHORT_START = 0x80; + uint constant DATA_LONG_START = 0xB8; + uint constant LIST_SHORT_START = 0xC0; + uint constant LIST_LONG_START = 0xF8; + + uint constant DATA_LONG_OFFSET = 0xB7; + uint constant LIST_LONG_OFFSET = 0xF7; + + + struct RLPItem { + uint _unsafe_memPtr; // Pointer to the RLP-encoded bytes. + uint _unsafe_length; // Number of bytes. This is the full length of the string. + } + + struct Iterator { + RLPItem _unsafe_item; // Item that's being iterated over. + uint _unsafe_nextPtr; // Position of the next item in the list. + } + + /* Iterator */ + + function next(Iterator memory self) internal constant returns (RLPItem memory subItem) { + if(hasNext(self)) { + var ptr = self._unsafe_nextPtr; + var itemLength = _itemLength(ptr); + subItem._unsafe_memPtr = ptr; + subItem._unsafe_length = itemLength; + self._unsafe_nextPtr = ptr + itemLength; + } + else + throw; + } + + function next(Iterator memory self, bool strict) internal constant returns (RLPItem memory subItem) { + subItem = next(self); + if(strict && !_validate(subItem)) + throw; + return; + } + + function hasNext(Iterator memory self) internal constant returns (bool) { + var item = self._unsafe_item; + return self._unsafe_nextPtr < item._unsafe_memPtr + item._unsafe_length; + } + + /* RLPItem */ + + /// @dev Creates an RLPItem from an array of RLP encoded bytes. + /// @param self The RLP encoded bytes. + /// @return An RLPItem + function toRLPItem(bytes memory self) internal constant returns (RLPItem memory) { + uint len = self.length; + if (len == 0) { + return RLPItem(0, 0); + } + uint memPtr; + assembly { + memPtr := add(self, 0x20) + } + return RLPItem(memPtr, len); + } + + /// @dev Creates an RLPItem from an array of RLP encoded bytes. + /// @param self The RLP encoded bytes. + /// @param strict Will throw if the data is not RLP encoded. + /// @return An RLPItem + function toRLPItem(bytes memory self, bool strict) internal constant returns (RLPItem memory) { + var item = toRLPItem(self); + if(strict) { + uint len = self.length; + if(_payloadOffset(item) > len) + throw; + if(_itemLength(item._unsafe_memPtr) != len) + throw; + if(!_validate(item)) + throw; + } + return item; + } + + /// @dev Check if the RLP item is null. + /// @param self The RLP item. + /// @return 'true' if the item is null. + function isNull(RLPItem memory self) internal constant returns (bool ret) { + return self._unsafe_length == 0; + } + + /// @dev Check if the RLP item is a list. + /// @param self The RLP item. + /// @return 'true' if the item is a list. + function isList(RLPItem memory self) internal constant returns (bool ret) { + if (self._unsafe_length == 0) + return false; + uint memPtr = self._unsafe_memPtr; + assembly { + ret := iszero(lt(byte(0, mload(memPtr)), 0xC0)) + } + } + + /// @dev Check if the RLP item is data. + /// @param self The RLP item. + /// @return 'true' if the item is data. + function isData(RLPItem memory self) internal constant returns (bool ret) { + if (self._unsafe_length == 0) + return false; + uint memPtr = self._unsafe_memPtr; + assembly { + ret := lt(byte(0, mload(memPtr)), 0xC0) + } + } + + /// @dev Check if the RLP item is empty (string or list). + /// @param self The RLP item. + /// @return 'true' if the item is null. + function isEmpty(RLPItem memory self) internal constant returns (bool ret) { + if(isNull(self)) + return false; + uint b0; + uint memPtr = self._unsafe_memPtr; + assembly { + b0 := byte(0, mload(memPtr)) + } + return (b0 == DATA_SHORT_START || b0 == LIST_SHORT_START); + } + + /// @dev Get the number of items in an RLP encoded list. + /// @param self The RLP item. + /// @return The number of items. + function items(RLPItem memory self) internal constant returns (uint) { + if (!isList(self)) + return 0; + uint b0; + uint memPtr = self._unsafe_memPtr; + assembly { + b0 := byte(0, mload(memPtr)) + } + uint pos = memPtr + _payloadOffset(self); + uint last = memPtr + self._unsafe_length - 1; + uint itms; + while(pos <= last) { + pos += _itemLength(pos); + itms++; + } + return itms; + } + + /// @dev Create an iterator. + /// @param self The RLP item. + /// @return An 'Iterator' over the item. + function iterator(RLPItem memory self) internal constant returns (Iterator memory it) { + if (!isList(self)) + throw; + uint ptr = self._unsafe_memPtr + _payloadOffset(self); + it._unsafe_item = self; + it._unsafe_nextPtr = ptr; + } + + /// @dev Return the RLP encoded bytes. + /// @param self The RLPItem. + /// @return The bytes. + function toBytes(RLPItem memory self) internal constant returns (bytes memory bts) { + var len = self._unsafe_length; + if (len == 0) + return; + bts = new bytes(len); + _copyToBytes(self._unsafe_memPtr, bts, len); + } + + /// @dev Decode an RLPItem into bytes. This will not work if the + /// RLPItem is a list. + /// @param self The RLPItem. + /// @return The decoded string. + function toData(RLPItem memory self) internal constant returns (bytes memory bts) { + if(!isData(self)) + throw; + var (rStartPos, len) = _decode(self); + bts = new bytes(len); + _copyToBytes(rStartPos, bts, len); + } + + /// @dev Get the list of sub-items from an RLP encoded list. + /// Warning: This is inefficient, as it requires that the list is read twice. + /// @param self The RLP item. + /// @return Array of RLPItems. + function toList(RLPItem memory self) internal constant returns (RLPItem[] memory list) { + if(!isList(self)) + throw; + var numItems = items(self); + list = new RLPItem[](numItems); + var it = iterator(self); + uint idx; + while(hasNext(it)) { + list[idx] = next(it); + idx++; + } + } + + /// @dev Decode an RLPItem into an ascii string. This will not work if the + /// RLPItem is a list. + /// @param self The RLPItem. + /// @return The decoded string. + function toAscii(RLPItem memory self) internal constant returns (string memory str) { + if(!isData(self)) + throw; + var (rStartPos, len) = _decode(self); + bytes memory bts = new bytes(len); + _copyToBytes(rStartPos, bts, len); + str = string(bts); + } + + /// @dev Decode an RLPItem into a uint. This will not work if the + /// RLPItem is a list. + /// @param self The RLPItem. + /// @return The decoded string. + function toUint(RLPItem memory self) internal constant returns (uint data) { + if(!isData(self)) + throw; + var (rStartPos, len) = _decode(self); + if (len > 32 || len == 0) + throw; + assembly { + data := div(mload(rStartPos), exp(256, sub(32, len))) + } + } + + /// @dev Decode an RLPItem into a boolean. This will not work if the + /// RLPItem is a list. + /// @param self The RLPItem. + /// @return The decoded string. + function toBool(RLPItem memory self) internal constant returns (bool data) { + if(!isData(self)) + throw; + var (rStartPos, len) = _decode(self); + if (len != 1) + throw; + uint temp; + assembly { + temp := byte(0, mload(rStartPos)) + } + if (temp > 1) + throw; + return temp == 1 ? true : false; + } + + /// @dev Decode an RLPItem into a byte. This will not work if the + /// RLPItem is a list. + /// @param self The RLPItem. + /// @return The decoded string. + function toByte(RLPItem memory self) internal constant returns (byte data) { + if(!isData(self)) + throw; + var (rStartPos, len) = _decode(self); + if (len != 1) + throw; + uint temp; + assembly { + temp := byte(0, mload(rStartPos)) + } + return byte(temp); + } + + /// @dev Decode an RLPItem into an int. This will not work if the + /// RLPItem is a list. + /// @param self The RLPItem. + /// @return The decoded string. + function toInt(RLPItem memory self) internal constant returns (int data) { + return int(toUint(self)); + } + + /// @dev Decode an RLPItem into a bytes32. This will not work if the + /// RLPItem is a list. + /// @param self The RLPItem. + /// @return The decoded string. + function toBytes32(RLPItem memory self) internal constant returns (bytes32 data) { + return bytes32(toUint(self)); + } + + /// @dev Decode an RLPItem into an address. This will not work if the + /// RLPItem is a list. + /// @param self The RLPItem. + /// @return The decoded string. + function toAddress(RLPItem memory self) internal constant returns (address data) { + if(!isData(self)) + throw; + var (rStartPos, len) = _decode(self); + if (len != 20) + throw; + assembly { + data := div(mload(rStartPos), exp(256, 12)) + } + } + + // Get the payload offset. + function _payloadOffset(RLPItem memory self) private constant returns (uint) { + if(self._unsafe_length == 0) + return 0; + uint b0; + uint memPtr = self._unsafe_memPtr; + assembly { + b0 := byte(0, mload(memPtr)) + } + if(b0 < DATA_SHORT_START) + return 0; + if(b0 < DATA_LONG_START || (b0 >= LIST_SHORT_START && b0 < LIST_LONG_START)) + return 1; + if(b0 < LIST_SHORT_START) + return b0 - DATA_LONG_OFFSET + 1; + return b0 - LIST_LONG_OFFSET + 1; + } + + // Get the full length of an RLP item. + function _itemLength(uint memPtr) private constant returns (uint len) { + uint b0; + assembly { + b0 := byte(0, mload(memPtr)) + } + if (b0 < DATA_SHORT_START) + len = 1; + else if (b0 < DATA_LONG_START) + len = b0 - DATA_SHORT_START + 1; + else if (b0 < LIST_SHORT_START) { + assembly { + let bLen := sub(b0, 0xB7) // bytes length (DATA_LONG_OFFSET) + let dLen := div(mload(add(memPtr, 1)), exp(256, sub(32, bLen))) // data length + len := add(1, add(bLen, dLen)) // total length + } + } + else if (b0 < LIST_LONG_START) + len = b0 - LIST_SHORT_START + 1; + else { + assembly { + let bLen := sub(b0, 0xF7) // bytes length (LIST_LONG_OFFSET) + let dLen := div(mload(add(memPtr, 1)), exp(256, sub(32, bLen))) // data length + len := add(1, add(bLen, dLen)) // total length + } + } + } + + // Get start position and length of the data. + function _decode(RLPItem memory self) private constant returns (uint memPtr, uint len) { + if(!isData(self)) + throw; + uint b0; + uint start = self._unsafe_memPtr; + assembly { + b0 := byte(0, mload(start)) + } + if (b0 < DATA_SHORT_START) { + memPtr = start; + len = 1; + return; + } + if (b0 < DATA_LONG_START) { + len = self._unsafe_length - 1; + memPtr = start + 1; + } else { + uint bLen; + assembly { + bLen := sub(b0, 0xB7) // DATA_LONG_OFFSET + } + len = self._unsafe_length - 1 - bLen; + memPtr = start + bLen + 1; + } + return; + } + + // Assumes that enough memory has been allocated to store in target. + function _copyToBytes(uint btsPtr, bytes memory tgt, uint btsLen) private constant { + // Exploiting the fact that 'tgt' was the last thing to be allocated, + // we can write entire words, and just overwrite any excess. + assembly { + { + let i := 0 // Start at arr + 0x20 + let words := div(add(btsLen, 31), 32) + let rOffset := btsPtr + let wOffset := add(tgt, 0x20) + tag_loop: + jumpi(end, eq(i, words)) + { + let offset := mul(i, 0x20) + mstore(add(wOffset, offset), mload(add(rOffset, offset))) + i := add(i, 1) + } + jump(tag_loop) + end: + mstore(add(tgt, add(0x20, mload(tgt))), 0) + } + } + } + + // Check that an RLP item is valid. + function _validate(RLPItem memory self) private constant returns (bool ret) { + // Check that RLP is well-formed. + uint b0; + uint b1; + uint memPtr = self._unsafe_memPtr; + assembly { + b0 := byte(0, mload(memPtr)) + b1 := byte(1, mload(memPtr)) + } + if(b0 == DATA_SHORT_START + 1 && b1 < DATA_SHORT_START) + return false; + return true; + } +} diff --git a/test/compilationTests/stringutils/LICENSE b/test/compilationTests/stringutils/LICENSE new file mode 100644 index 00000000..769c2409 --- /dev/null +++ b/test/compilationTests/stringutils/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2016 Nick Johnson + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/test/compilationTests/stringutils/README.md b/test/compilationTests/stringutils/README.md new file mode 100644 index 00000000..48f71f31 --- /dev/null +++ b/test/compilationTests/stringutils/README.md @@ -0,0 +1,4 @@ +String utilities, originally from + +https://github.com/Arachnid/solidity-stringutils + diff --git a/test/compilationTests/stringutils/strings.sol b/test/compilationTests/stringutils/strings.sol new file mode 100644 index 00000000..0a2d68bd --- /dev/null +++ b/test/compilationTests/stringutils/strings.sol @@ -0,0 +1,709 @@ +/* + * @title String & slice utility library for Solidity contracts. + * @author Nick Johnson <arachnid@notdot.net> + * + * @dev Functionality in this library is largely implemented using an + * abstraction called a 'slice'. A slice represents a part of a string - + * anything from the entire string to a single character, or even no + * characters at all (a 0-length slice). Since a slice only has to specify + * an offset and a length, copying and manipulating slices is a lot less + * expensive than copying and manipulating the strings they reference. + * + * To further reduce gas costs, most functions on slice that need to return + * a slice modify the original one instead of allocating a new one; for + * instance, `s.split(".")` will return the text up to the first '.', + * modifying s to only contain the remainder of the string after the '.'. + * In situations where you do not want to modify the original slice, you + * can make a copy first with `.copy()`, for example: + * `s.copy().split(".")`. Try and avoid using this idiom in loops; since + * Solidity has no memory management, it will result in allocating many + * short-lived slices that are later discarded. + * + * Functions that return two slices come in two versions: a non-allocating + * version that takes the second slice as an argument, modifying it in + * place, and an allocating version that allocates and returns the second + * slice; see `nextRune` for example. + * + * Functions that have to copy string data will return strings rather than + * slices; these can be cast back to slices for further processing if + * required. + * + * For convenience, some functions are provided with non-modifying + * variants that create a new slice and return both; for instance, + * `s.splitNew('.')` leaves s unmodified, and returns two values + * corresponding to the left and right parts of the string. + */ +library strings { + struct slice { + uint _len; + uint _ptr; + } + + function memcpy(uint dest, uint src, uint len) private { + // Copy word-length chunks while possible + for(; len >= 32; len -= 32) { + assembly { + mstore(dest, mload(src)) + } + dest += 32; + src += 32; + } + + // Copy remaining bytes + uint mask = 256 ** (32 - len) - 1; + assembly { + let srcpart := and(mload(src), not(mask)) + let destpart := and(mload(dest), mask) + mstore(dest, or(destpart, srcpart)) + } + } + + /* + * @dev Returns a slice containing the entire string. + * @param self The string to make a slice from. + * @return A newly allocated slice containing the entire string. + */ + function toSlice(string self) internal returns (slice) { + uint ptr; + assembly { + ptr := add(self, 0x20) + } + return slice(bytes(self).length, ptr); + } + + /* + * @dev Returns the length of a null-terminated bytes32 string. + * @param self The value to find the length of. + * @return The length of the string, from 0 to 32. + */ + function len(bytes32 self) internal returns (uint) { + uint ret; + if (self == 0) + return 0; + if (self & 0xffffffffffffffffffffffffffffffff == 0) { + ret += 16; + self = bytes32(uint(self) / 0x100000000000000000000000000000000); + } + if (self & 0xffffffffffffffff == 0) { + ret += 8; + self = bytes32(uint(self) / 0x10000000000000000); + } + if (self & 0xffffffff == 0) { + ret += 4; + self = bytes32(uint(self) / 0x100000000); + } + if (self & 0xffff == 0) { + ret += 2; + self = bytes32(uint(self) / 0x10000); + } + if (self & 0xff == 0) { + ret += 1; + } + return 32 - ret; + } + + /* + * @dev Returns a slice containing the entire bytes32, interpreted as a + * null-termintaed utf-8 string. + * @param self The bytes32 value to convert to a slice. + * @return A new slice containing the value of the input argument up to the + * first null. + */ + function toSliceB32(bytes32 self) internal returns (slice ret) { + // Allocate space for `self` in memory, copy it there, and point ret at it + assembly { + let ptr := mload(0x40) + mstore(0x40, add(ptr, 0x20)) + mstore(ptr, self) + mstore(add(ret, 0x20), ptr) + } + ret._len = len(self); + } + + /* + * @dev Returns a new slice containing the same data as the current slice. + * @param self The slice to copy. + * @return A new slice containing the same data as `self`. + */ + function copy(slice self) internal returns (slice) { + return slice(self._len, self._ptr); + } + + /* + * @dev Copies a slice to a new string. + * @param self The slice to copy. + * @return A newly allocated string containing the slice's text. + */ + function toString(slice self) internal returns (string) { + var ret = new string(self._len); + uint retptr; + assembly { retptr := add(ret, 32) } + + memcpy(retptr, self._ptr, self._len); + return ret; + } + + /* + * @dev Returns the length in runes of the slice. Note that this operation + * takes time proportional to the length of the slice; avoid using it + * in loops, and call `slice.empty()` if you only need to know whether + * the slice is empty or not. + * @param self The slice to operate on. + * @return The length of the slice in runes. + */ + function len(slice self) internal returns (uint) { + // Starting at ptr-31 means the LSB will be the byte we care about + var ptr = self._ptr - 31; + var end = ptr + self._len; + for (uint len = 0; ptr < end; len++) { + uint8 b; + assembly { b := and(mload(ptr), 0xFF) } + if (b < 0x80) { + ptr += 1; + } else if(b < 0xE0) { + ptr += 2; + } else if(b < 0xF0) { + ptr += 3; + } else if(b < 0xF8) { + ptr += 4; + } else if(b < 0xFC) { + ptr += 5; + } else { + ptr += 6; + } + } + return len; + } + + /* + * @dev Returns true if the slice is empty (has a length of 0). + * @param self The slice to operate on. + * @return True if the slice is empty, False otherwise. + */ + function empty(slice self) internal returns (bool) { + return self._len == 0; + } + + /* + * @dev Returns a positive number if `other` comes lexicographically after + * `self`, a negative number if it comes before, or zero if the + * contents of the two slices are equal. Comparison is done per-rune, + * on unicode codepoints. + * @param self The first slice to compare. + * @param other The second slice to compare. + * @return The result of the comparison. + */ + function compare(slice self, slice other) internal returns (int) { + uint shortest = self._len; + if (other._len < self._len) + shortest = other._len; + + var selfptr = self._ptr; + var otherptr = other._ptr; + for (uint idx = 0; idx < shortest; idx += 32) { + uint a; + uint b; + assembly { + a := mload(selfptr) + b := mload(otherptr) + } + if (a != b) { + // Mask out irrelevant bytes and check again + uint mask = ~(2 ** (8 * (32 - shortest + idx)) - 1); + var diff = (a & mask) - (b & mask); + if (diff != 0) + return int(diff); + } + selfptr += 32; + otherptr += 32; + } + return int(self._len) - int(other._len); + } + + /* + * @dev Returns true if the two slices contain the same text. + * @param self The first slice to compare. + * @param self The second slice to compare. + * @return True if the slices are equal, false otherwise. + */ + function equals(slice self, slice other) internal returns (bool) { + return compare(self, other) == 0; + } + + /* + * @dev Extracts the first rune in the slice into `rune`, advancing the + * slice to point to the next rune and returning `self`. + * @param self The slice to operate on. + * @param rune The slice that will contain the first rune. + * @return `rune`. + */ + function nextRune(slice self, slice rune) internal returns (slice) { + rune._ptr = self._ptr; + + if (self._len == 0) { + rune._len = 0; + return rune; + } + + uint len; + uint b; + // Load the first byte of the rune into the LSBs of b + assembly { b := and(mload(sub(mload(add(self, 32)), 31)), 0xFF) } + if (b < 0x80) { + len = 1; + } else if(b < 0xE0) { + len = 2; + } else if(b < 0xF0) { + len = 3; + } else { + len = 4; + } + + // Check for truncated codepoints + if (len > self._len) { + rune._len = self._len; + self._ptr += self._len; + self._len = 0; + return rune; + } + + self._ptr += len; + self._len -= len; + rune._len = len; + return rune; + } + + /* + * @dev Returns the first rune in the slice, advancing the slice to point + * to the next rune. + * @param self The slice to operate on. + * @return A slice containing only the first rune from `self`. + */ + function nextRune(slice self) internal returns (slice ret) { + nextRune(self, ret); + } + + /* + * @dev Returns the number of the first codepoint in the slice. + * @param self The slice to operate on. + * @return The number of the first codepoint in the slice. + */ + function ord(slice self) internal returns (uint ret) { + if (self._len == 0) { + return 0; + } + + uint word; + uint len; + uint div = 2 ** 248; + + // Load the rune into the MSBs of b + assembly { word:= mload(mload(add(self, 32))) } + var b = word / div; + if (b < 0x80) { + ret = b; + len = 1; + } else if(b < 0xE0) { + ret = b & 0x1F; + len = 2; + } else if(b < 0xF0) { + ret = b & 0x0F; + len = 3; + } else { + ret = b & 0x07; + len = 4; + } + + // Check for truncated codepoints + if (len > self._len) { + return 0; + } + + for (uint i = 1; i < len; i++) { + div = div / 256; + b = (word / div) & 0xFF; + if (b & 0xC0 != 0x80) { + // Invalid UTF-8 sequence + return 0; + } + ret = (ret * 64) | (b & 0x3F); + } + + return ret; + } + + /* + * @dev Returns the keccak-256 hash of the slice. + * @param self The slice to hash. + * @return The hash of the slice. + */ + function keccak(slice self) internal returns (bytes32 ret) { + assembly { + ret := sha3(mload(add(self, 32)), mload(self)) + } + } + + /* + * @dev Returns true if `self` starts with `needle`. + * @param self The slice to operate on. + * @param needle The slice to search for. + * @return True if the slice starts with the provided text, false otherwise. + */ + function startsWith(slice self, slice needle) internal returns (bool) { + if (self._len < needle._len) { + return false; + } + + if (self._ptr == needle._ptr) { + return true; + } + + bool equal; + assembly { + let len := mload(needle) + let selfptr := mload(add(self, 0x20)) + let needleptr := mload(add(needle, 0x20)) + equal := eq(sha3(selfptr, len), sha3(needleptr, len)) + } + return equal; + } + + /* + * @dev If `self` starts with `needle`, `needle` is removed from the + * beginning of `self`. Otherwise, `self` is unmodified. + * @param self The slice to operate on. + * @param needle The slice to search for. + * @return `self` + */ + function beyond(slice self, slice needle) internal returns (slice) { + if (self._len < needle._len) { + return self; + } + + bool equal = true; + if (self._ptr != needle._ptr) { + assembly { + let len := mload(needle) + let selfptr := mload(add(self, 0x20)) + let needleptr := mload(add(needle, 0x20)) + equal := eq(sha3(selfptr, len), sha3(needleptr, len)) + } + } + + if (equal) { + self._len -= needle._len; + self._ptr += needle._len; + } + + return self; + } + + /* + * @dev Returns true if the slice ends with `needle`. + * @param self The slice to operate on. + * @param needle The slice to search for. + * @return True if the slice starts with the provided text, false otherwise. + */ + function endsWith(slice self, slice needle) internal returns (bool) { + if (self._len < needle._len) { + return false; + } + + var selfptr = self._ptr + self._len - needle._len; + + if (selfptr == needle._ptr) { + return true; + } + + bool equal; + assembly { + let len := mload(needle) + let needleptr := mload(add(needle, 0x20)) + equal := eq(sha3(selfptr, len), sha3(needleptr, len)) + } + + return equal; + } + + /* + * @dev If `self` ends with `needle`, `needle` is removed from the + * end of `self`. Otherwise, `self` is unmodified. + * @param self The slice to operate on. + * @param needle The slice to search for. + * @return `self` + */ + function until(slice self, slice needle) internal returns (slice) { + if (self._len < needle._len) { + return self; + } + + var selfptr = self._ptr + self._len - needle._len; + bool equal = true; + if (selfptr != needle._ptr) { + assembly { + let len := mload(needle) + let needleptr := mload(add(needle, 0x20)) + equal := eq(sha3(selfptr, len), sha3(needleptr, len)) + } + } + + if (equal) { + self._len -= needle._len; + } + + return self; + } + + // Returns the memory address of the first byte of the first occurrence of + // `needle` in `self`, or the first byte after `self` if not found. + function findPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private returns (uint) { + uint ptr; + uint idx; + + if (needlelen <= selflen) { + if (needlelen <= 32) { + // Optimized assembly for 68 gas per byte on short strings + assembly { + let mask := not(sub(exp(2, mul(8, sub(32, needlelen))), 1)) + let needledata := and(mload(needleptr), mask) + let end := add(selfptr, sub(selflen, needlelen)) + ptr := selfptr + loop: + jumpi(exit, eq(and(mload(ptr), mask), needledata)) + ptr := add(ptr, 1) + jumpi(loop, lt(sub(ptr, 1), end)) + ptr := add(selfptr, selflen) + exit: + } + return ptr; + } else { + // For long needles, use hashing + bytes32 hash; + assembly { hash := sha3(needleptr, needlelen) } + ptr = selfptr; + for (idx = 0; idx <= selflen - needlelen; idx++) { + bytes32 testHash; + assembly { testHash := sha3(ptr, needlelen) } + if (hash == testHash) + return ptr; + ptr += 1; + } + } + } + return selfptr + selflen; + } + + // Returns the memory address of the first byte after the last occurrence of + // `needle` in `self`, or the address of `self` if not found. + function rfindPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private returns (uint) { + uint ptr; + + if (needlelen <= selflen) { + if (needlelen <= 32) { + // Optimized assembly for 69 gas per byte on short strings + assembly { + let mask := not(sub(exp(2, mul(8, sub(32, needlelen))), 1)) + let needledata := and(mload(needleptr), mask) + ptr := add(selfptr, sub(selflen, needlelen)) + loop: + jumpi(ret, eq(and(mload(ptr), mask), needledata)) + ptr := sub(ptr, 1) + jumpi(loop, gt(add(ptr, 1), selfptr)) + ptr := selfptr + jump(exit) + ret: + ptr := add(ptr, needlelen) + exit: + } + return ptr; + } else { + // For long needles, use hashing + bytes32 hash; + assembly { hash := sha3(needleptr, needlelen) } + ptr = selfptr + (selflen - needlelen); + while (ptr >= selfptr) { + bytes32 testHash; + assembly { testHash := sha3(ptr, needlelen) } + if (hash == testHash) + return ptr + needlelen; + ptr -= 1; + } + } + } + return selfptr; + } + + /* + * @dev Modifies `self` to contain everything from the first occurrence of + * `needle` to the end of the slice. `self` is set to the empty slice + * if `needle` is not found. + * @param self The slice to search and modify. + * @param needle The text to search for. + * @return `self`. + */ + function find(slice self, slice needle) internal returns (slice) { + uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr); + self._len -= ptr - self._ptr; + self._ptr = ptr; + return self; + } + + /* + * @dev Modifies `self` to contain the part of the string from the start of + * `self` to the end of the first occurrence of `needle`. If `needle` + * is not found, `self` is set to the empty slice. + * @param self The slice to search and modify. + * @param needle The text to search for. + * @return `self`. + */ + function rfind(slice self, slice needle) internal returns (slice) { + uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr); + self._len = ptr - self._ptr; + return self; + } + + /* + * @dev Splits the slice, setting `self` to everything after the first + * occurrence of `needle`, and `token` to everything before it. If + * `needle` does not occur in `self`, `self` is set to the empty slice, + * and `token` is set to the entirety of `self`. + * @param self The slice to split. + * @param needle The text to search for in `self`. + * @param token An output parameter to which the first token is written. + * @return `token`. + */ + function split(slice self, slice needle, slice token) internal returns (slice) { + uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr); + token._ptr = self._ptr; + token._len = ptr - self._ptr; + if (ptr == self._ptr + self._len) { + // Not found + self._len = 0; + } else { + self._len -= token._len + needle._len; + self._ptr = ptr + needle._len; + } + return token; + } + + /* + * @dev Splits the slice, setting `self` to everything after the first + * occurrence of `needle`, and returning everything before it. If + * `needle` does not occur in `self`, `self` is set to the empty slice, + * and the entirety of `self` is returned. + * @param self The slice to split. + * @param needle The text to search for in `self`. + * @return The part of `self` up to the first occurrence of `delim`. + */ + function split(slice self, slice needle) internal returns (slice token) { + split(self, needle, token); + } + + /* + * @dev Splits the slice, setting `self` to everything before the last + * occurrence of `needle`, and `token` to everything after it. If + * `needle` does not occur in `self`, `self` is set to the empty slice, + * and `token` is set to the entirety of `self`. + * @param self The slice to split. + * @param needle The text to search for in `self`. + * @param token An output parameter to which the first token is written. + * @return `token`. + */ + function rsplit(slice self, slice needle, slice token) internal returns (slice) { + uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr); + token._ptr = ptr; + token._len = self._len - (ptr - self._ptr); + if (ptr == self._ptr) { + // Not found + self._len = 0; + } else { + self._len -= token._len + needle._len; + } + return token; + } + + /* + * @dev Splits the slice, setting `self` to everything before the last + * occurrence of `needle`, and returning everything after it. If + * `needle` does not occur in `self`, `self` is set to the empty slice, + * and the entirety of `self` is returned. + * @param self The slice to split. + * @param needle The text to search for in `self`. + * @return The part of `self` after the last occurrence of `delim`. + */ + function rsplit(slice self, slice needle) internal returns (slice token) { + rsplit(self, needle, token); + } + + /* + * @dev Counts the number of nonoverlapping occurrences of `needle` in `self`. + * @param self The slice to search. + * @param needle The text to search for in `self`. + * @return The number of occurrences of `needle` found in `self`. + */ + function count(slice self, slice needle) internal returns (uint count) { + uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr) + needle._len; + while (ptr <= self._ptr + self._len) { + count++; + ptr = findPtr(self._len - (ptr - self._ptr), ptr, needle._len, needle._ptr) + needle._len; + } + } + + /* + * @dev Returns True if `self` contains `needle`. + * @param self The slice to search. + * @param needle The text to search for in `self`. + * @return True if `needle` is found in `self`, false otherwise. + */ + function contains(slice self, slice needle) internal returns (bool) { + return rfindPtr(self._len, self._ptr, needle._len, needle._ptr) != self._ptr; + } + + /* + * @dev Returns a newly allocated string containing the concatenation of + * `self` and `other`. + * @param self The first slice to concatenate. + * @param other The second slice to concatenate. + * @return The concatenation of the two strings. + */ + function concat(slice self, slice other) internal returns (string) { + var ret = new string(self._len + other._len); + uint retptr; + assembly { retptr := add(ret, 32) } + memcpy(retptr, self._ptr, self._len); + memcpy(retptr + self._len, other._ptr, other._len); + return ret; + } + + /* + * @dev Joins an array of slices, using `self` as a delimiter, returning a + * newly allocated string. + * @param self The delimiter to use. + * @param parts A list of slices to join. + * @return A newly allocated string containing all the slices in `parts`, + * joined with `self`. + */ + function join(slice self, slice[] parts) internal returns (string) { + if (parts.length == 0) + return ""; + + uint len = self._len * (parts.length - 1); + for(uint i = 0; i < parts.length; i++) + len += parts[i]._len; + + var ret = new string(len); + uint retptr; + assembly { retptr := add(ret, 32) } + + for(i = 0; i < parts.length; i++) { + memcpy(retptr, parts[i]._ptr, parts[i]._len); + retptr += parts[i]._len; + if (i < parts.length - 1) { + memcpy(retptr, self._ptr, self._len); + retptr += self._len; + } + } + + return ret; + } +} diff --git a/test/compilationTests/zeppelin/Bounty.sol b/test/compilationTests/zeppelin/Bounty.sol new file mode 100644 index 00000000..4425b7a5 --- /dev/null +++ b/test/compilationTests/zeppelin/Bounty.sol @@ -0,0 +1,78 @@ +pragma solidity ^0.4.11; + + +import './payment/PullPayment.sol'; +import './lifecycle/Destructible.sol'; + + +/** + * @title Bounty + * @dev This bounty will pay out to a researcher if they break invariant logic of the contract. + */ +contract Bounty is PullPayment, Destructible { + bool public claimed; + mapping(address => address) public researchers; + + event TargetCreated(address createdAddress); + + /** + * @dev Fallback function allowing the contract to recieve funds, if they haven't already been claimed. + */ + function() payable { + if (claimed) { + throw; + } + } + + /** + * @dev Create and deploy the target contract (extension of Target contract), and sets the + * msg.sender as a researcher + * @return A target contract + */ + function createTarget() returns(Target) { + Target target = Target(deployContract()); + researchers[target] = msg.sender; + TargetCreated(target); + return target; + } + + /** + * @dev Internal function to deploy the target contract. + * @return A target contract address + */ + function deployContract() internal returns(address); + + /** + * @dev Sends the contract funds to the researcher that proved the contract is broken. + * @param target contract + */ + function claim(Target target) { + address researcher = researchers[target]; + if (researcher == 0) { + throw; + } + // Check Target contract invariants + if (target.checkInvariant()) { + throw; + } + asyncSend(researcher, this.balance); + claimed = true; + } + +} + + +/** + * @title Target + * @dev Your main contract should inherit from this class and implement the checkInvariant method. + */ +contract Target { + + /** + * @dev Checks all values a contract assumes to be true all the time. If this function returns + * false, the contract is broken in some way and is in an inconsistent state. + * In order to win the bounty, security researchers will try to cause this broken state. + * @return True if all invariant values are correct, false otherwise. + */ + function checkInvariant() returns(bool); +} diff --git a/test/compilationTests/zeppelin/DayLimit.sol b/test/compilationTests/zeppelin/DayLimit.sol new file mode 100644 index 00000000..3c8d5b0c --- /dev/null +++ b/test/compilationTests/zeppelin/DayLimit.sol @@ -0,0 +1,75 @@ +pragma solidity ^0.4.11; + +/** + * @title DayLimit + * @dev Base contract that enables methods to be protected by placing a linear limit (specifiable) + * on a particular resource per calendar day. Is multiowned to allow the limit to be altered. + */ +contract DayLimit { + + uint256 public dailyLimit; + uint256 public spentToday; + uint256 public lastDay; + + /** + * @dev Constructor that sets the passed value as a dailyLimit. + * @param _limit uint256 to represent the daily limit. + */ + function DayLimit(uint256 _limit) { + dailyLimit = _limit; + lastDay = today(); + } + + /** + * @dev sets the daily limit. Does not alter the amount already spent today. + * @param _newLimit uint256 to represent the new limit. + */ + function _setDailyLimit(uint256 _newLimit) internal { + dailyLimit = _newLimit; + } + + /** + * @dev Resets the amount already spent today. + */ + function _resetSpentToday() internal { + spentToday = 0; + } + + /** + * @dev Checks to see if there is enough resource to spend today. If true, the resource may be expended. + * @param _value uint256 representing the amount of resource to spend. + * @return A boolean that is True if the resource was spended and false otherwise. + */ + function underLimit(uint256 _value) internal returns (bool) { + // reset the spend limit if we're on a different day to last time. + if (today() > lastDay) { + spentToday = 0; + lastDay = today(); + } + // check to see if there's enough left - if so, subtract and return true. + // overflow protection // dailyLimit check + if (spentToday + _value >= spentToday && spentToday + _value <= dailyLimit) { + spentToday += _value; + return true; + } + return false; + } + + /** + * @dev Private function to determine today's index + * @return uint256 of today's index. + */ + function today() private constant returns (uint256) { + return now / 1 days; + } + + /** + * @dev Simple modifier for daily limit. + */ + modifier limitedDaily(uint256 _value) { + if (!underLimit(_value)) { + throw; + } + _; + } +} diff --git a/test/compilationTests/zeppelin/LICENSE b/test/compilationTests/zeppelin/LICENSE new file mode 100644 index 00000000..85f53321 --- /dev/null +++ b/test/compilationTests/zeppelin/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2016 Smart Contract Solutions, Inc. + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/test/compilationTests/zeppelin/LimitBalance.sol b/test/compilationTests/zeppelin/LimitBalance.sol new file mode 100644 index 00000000..57477c74 --- /dev/null +++ b/test/compilationTests/zeppelin/LimitBalance.sol @@ -0,0 +1,33 @@ +pragma solidity ^0.4.11; + + +/** + * @title LimitBalance + * @dev Simple contract to limit the balance of child contract. + * @dev Note this doesn't prevent other contracts to send funds by using selfdestruct(address); + * @dev See: https://github.com/ConsenSys/smart-contract-best-practices#remember-that-ether-can-be-forcibly-sent-to-an-account + */ +contract LimitBalance { + + uint256 public limit; + + /** + * @dev Constructor that sets the passed value as a limit. + * @param _limit uint256 to represent the limit. + */ + function LimitBalance(uint256 _limit) { + limit = _limit; + } + + /** + * @dev Checks if limit was reached. Case true, it throws. + */ + modifier limitedPayable() { + if (this.balance > limit) { + throw; + } + _; + + } + +} diff --git a/test/compilationTests/zeppelin/MultisigWallet.sol b/test/compilationTests/zeppelin/MultisigWallet.sol new file mode 100644 index 00000000..939e70f2 --- /dev/null +++ b/test/compilationTests/zeppelin/MultisigWallet.sol @@ -0,0 +1,127 @@ +pragma solidity ^0.4.11; + + +import "./ownership/Multisig.sol"; +import "./ownership/Shareable.sol"; +import "./DayLimit.sol"; + + +/** + * MultisigWallet + * Usage: + * bytes32 h = Wallet(w).from(oneOwner).execute(to, value, data); + * Wallet(w).from(anotherOwner).confirm(h); + */ +contract MultisigWallet is Multisig, Shareable, DayLimit { + + struct Transaction { + address to; + uint256 value; + bytes data; + } + + /** + * Constructor, sets the owners addresses, number of approvals required, and daily spending limit + * @param _owners A list of owners. + * @param _required The amount required for a transaction to be approved. + */ + function MultisigWallet(address[] _owners, uint256 _required, uint256 _daylimit) + Shareable(_owners, _required) + DayLimit(_daylimit) { } + + /** + * @dev destroys the contract sending everything to `_to`. + */ + function destroy(address _to) onlymanyowners(keccak256(msg.data)) external { + selfdestruct(_to); + } + + /** + * @dev Fallback function, receives value and emits a deposit event. + */ + function() payable { + // just being sent some cash? + if (msg.value > 0) + Deposit(msg.sender, msg.value); + } + + /** + * @dev Outside-visible transaction entry point. Executes transaction immediately if below daily + * spending limit. If not, goes into multisig process. We provide a hash on return to allow the + * sender to provide shortcuts for the other confirmations (allowing them to avoid replicating + * the _to, _value, and _data arguments). They still get the option of using them if they want, + * anyways. + * @param _to The receiver address + * @param _value The value to send + * @param _data The data part of the transaction + */ + function execute(address _to, uint256 _value, bytes _data) external onlyOwner returns (bytes32 _r) { + // first, take the opportunity to check that we're under the daily limit. + if (underLimit(_value)) { + SingleTransact(msg.sender, _value, _to, _data); + // yes - just execute the call. + if (!_to.call.value(_value)(_data)) { + throw; + } + return 0; + } + // determine our operation hash. + _r = keccak256(msg.data, block.number); + if (!confirm(_r) && txs[_r].to == 0) { + txs[_r].to = _to; + txs[_r].value = _value; + txs[_r].data = _data; + ConfirmationNeeded(_r, msg.sender, _value, _to, _data); + } + } + + /** + * @dev Confirm a transaction by providing just the hash. We use the previous transactions map, + * txs, in order to determine the body of the transaction from the hash provided. + * @param _h The transaction hash to approve. + */ + function confirm(bytes32 _h) onlymanyowners(_h) returns (bool) { + if (txs[_h].to != 0) { + if (!txs[_h].to.call.value(txs[_h].value)(txs[_h].data)) { + throw; + } + MultiTransact(msg.sender, _h, txs[_h].value, txs[_h].to, txs[_h].data); + delete txs[_h]; + return true; + } + } + + /** + * @dev Updates the daily limit value. + * @param _newLimit uint256 to represent the new limit. + */ + function setDailyLimit(uint256 _newLimit) onlymanyowners(keccak256(msg.data)) external { + _setDailyLimit(_newLimit); + } + + /** + * @dev Resets the value spent to enable more spending + */ + function resetSpentToday() onlymanyowners(keccak256(msg.data)) external { + _resetSpentToday(); + } + + + // INTERNAL METHODS + /** + * @dev Clears the list of transactions pending approval. + */ + function clearPending() internal { + uint256 length = pendingsIndex.length; + for (uint256 i = 0; i < length; ++i) { + delete txs[pendingsIndex[i]]; + } + super.clearPending(); + } + + + // FIELDS + + // pending transactions we have at present. + mapping (bytes32 => Transaction) txs; +} diff --git a/test/compilationTests/zeppelin/README.md b/test/compilationTests/zeppelin/README.md new file mode 100644 index 00000000..dee2f5ca --- /dev/null +++ b/test/compilationTests/zeppelin/README.md @@ -0,0 +1,3 @@ +Zeppelin contracts, originally from + +https://github.com/OpenZeppelin/zeppelin-solidity diff --git a/test/compilationTests/zeppelin/ReentrancyGuard.sol b/test/compilationTests/zeppelin/ReentrancyGuard.sol new file mode 100644 index 00000000..ca8b643b --- /dev/null +++ b/test/compilationTests/zeppelin/ReentrancyGuard.sol @@ -0,0 +1,34 @@ +pragma solidity ^0.4.11; + +/** + * @title Helps contracts guard agains rentrancy attacks. + * @author Remco Bloemen <remco@2π.com> + * @notice If you mark a function `nonReentrant`, you should also + * mark it `external`. + */ +contract ReentrancyGuard { + + /** + * @dev We use a single lock for the whole contract. + */ + bool private rentrancy_lock = false; + + /** + * @dev Prevents a contract from calling itself, directly or indirectly. + * @notice If you mark a function `nonReentrant`, you should also + * mark it `external`. Calling one nonReentrant function from + * another is not supported. Instead, you can implement a + * `private` function doing the actual work, and a `external` + * wrapper marked as `nonReentrant`. + */ + modifier nonReentrant() { + if(rentrancy_lock == false) { + rentrancy_lock = true; + _; + rentrancy_lock = false; + } else { + throw; + } + } + +} diff --git a/test/compilationTests/zeppelin/crowdsale/CappedCrowdsale.sol b/test/compilationTests/zeppelin/crowdsale/CappedCrowdsale.sol new file mode 100644 index 00000000..f04649f3 --- /dev/null +++ b/test/compilationTests/zeppelin/crowdsale/CappedCrowdsale.sol @@ -0,0 +1,33 @@ +pragma solidity ^0.4.11; + +import '../math/SafeMath.sol'; +import './Crowdsale.sol'; + +/** + * @title CappedCrowdsale + * @dev Extension of Crowsdale with a max amount of funds raised + */ +contract CappedCrowdsale is Crowdsale { + using SafeMath for uint256; + + uint256 public cap; + + function CappedCrowdsale(uint256 _cap) { + cap = _cap; + } + + // overriding Crowdsale#validPurchase to add extra cap logic + // @return true if investors can buy at the moment + function validPurchase() internal constant returns (bool) { + bool withinCap = weiRaised.add(msg.value) <= cap; + return super.validPurchase() && withinCap; + } + + // overriding Crowdsale#hasEnded to add cap logic + // @return true if crowdsale event has ended + function hasEnded() public constant returns (bool) { + bool capReached = weiRaised >= cap; + return super.hasEnded() || capReached; + } + +} diff --git a/test/compilationTests/zeppelin/crowdsale/Crowdsale.sol b/test/compilationTests/zeppelin/crowdsale/Crowdsale.sol new file mode 100644 index 00000000..bee1efd2 --- /dev/null +++ b/test/compilationTests/zeppelin/crowdsale/Crowdsale.sol @@ -0,0 +1,108 @@ +pragma solidity ^0.4.11; + +import '../token/MintableToken.sol'; +import '../math/SafeMath.sol'; + +/** + * @title Crowdsale + * @dev Crowdsale is a base contract for managing a token crowdsale. + * Crowdsales have a start and end block, where investors can make + * token purchases and the crowdsale will assign them tokens based + * on a token per ETH rate. Funds collected are forwarded to a wallet + * as they arrive. + */ +contract Crowdsale { + using SafeMath for uint256; + + // The token being sold + MintableToken public token; + + // start and end block where investments are allowed (both inclusive) + uint256 public startBlock; + uint256 public endBlock; + + // address where funds are collected + address public wallet; + + // how many token units a buyer gets per wei + uint256 public rate; + + // amount of raised money in wei + uint256 public weiRaised; + + /** + * event for token purchase logging + * @param purchaser who paid for the tokens + * @param beneficiary who got the tokens + * @param value weis paid for purchase + * @param amount amount of tokens purchased + */ + event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); + + + function Crowdsale(uint256 _startBlock, uint256 _endBlock, uint256 _rate, address _wallet) { + require(_startBlock >= block.number); + require(_endBlock >= _startBlock); + require(_rate > 0); + require(_wallet != 0x0); + + token = createTokenContract(); + startBlock = _startBlock; + endBlock = _endBlock; + rate = _rate; + wallet = _wallet; + } + + // creates the token to be sold. + // override this method to have crowdsale of a specific mintable token. + function createTokenContract() internal returns (MintableToken) { + return new MintableToken(); + } + + + // fallback function can be used to buy tokens + function () payable { + buyTokens(msg.sender); + } + + // low level token purchase function + function buyTokens(address beneficiary) payable { + require(beneficiary != 0x0); + require(validPurchase()); + + uint256 weiAmount = msg.value; + uint256 updatedWeiRaised = weiRaised.add(weiAmount); + + // calculate token amount to be created + uint256 tokens = weiAmount.mul(rate); + + // update state + weiRaised = updatedWeiRaised; + + token.mint(beneficiary, tokens); + TokenPurchase(msg.sender, beneficiary, weiAmount, tokens); + + forwardFunds(); + } + + // send ether to the fund collection wallet + // override to create custom fund forwarding mechanisms + function forwardFunds() internal { + wallet.transfer(msg.value); + } + + // @return true if the transaction can buy tokens + function validPurchase() internal constant returns (bool) { + uint256 current = block.number; + bool withinPeriod = current >= startBlock && current <= endBlock; + bool nonZeroPurchase = msg.value != 0; + return withinPeriod && nonZeroPurchase; + } + + // @return true if crowdsale event has ended + function hasEnded() public constant returns (bool) { + return block.number > endBlock; + } + + +} diff --git a/test/compilationTests/zeppelin/crowdsale/FinalizableCrowdsale.sol b/test/compilationTests/zeppelin/crowdsale/FinalizableCrowdsale.sol new file mode 100644 index 00000000..1a736083 --- /dev/null +++ b/test/compilationTests/zeppelin/crowdsale/FinalizableCrowdsale.sol @@ -0,0 +1,39 @@ +pragma solidity ^0.4.11; + +import '../math/SafeMath.sol'; +import '../ownership/Ownable.sol'; +import './Crowdsale.sol'; + +/** + * @title FinalizableCrowdsale + * @dev Extension of Crowsdale where an owner can do extra work + * after finishing. By default, it will end token minting. + */ +contract FinalizableCrowdsale is Crowdsale, Ownable { + using SafeMath for uint256; + + bool public isFinalized = false; + + event Finalized(); + + // should be called after crowdsale ends, to do + // some extra finalization work + function finalize() onlyOwner { + require(!isFinalized); + require(hasEnded()); + + finalization(); + Finalized(); + + isFinalized = true; + } + + // end token minting on finalization + // override this with custom logic if needed + function finalization() internal { + token.finishMinting(); + } + + + +} diff --git a/test/compilationTests/zeppelin/crowdsale/RefundVault.sol b/test/compilationTests/zeppelin/crowdsale/RefundVault.sol new file mode 100644 index 00000000..cc92ff9f --- /dev/null +++ b/test/compilationTests/zeppelin/crowdsale/RefundVault.sol @@ -0,0 +1,56 @@ +pragma solidity ^0.4.11; + +import '../math/SafeMath.sol'; +import '../ownership/Ownable.sol'; + +/** + * @title RefundVault + * @dev This contract is used for storing funds while a crowdsale + * is in progress. Supports refunding the money if crowdsale fails, + * and forwarding it if crowdsale is successful. + */ +contract RefundVault is Ownable { + using SafeMath for uint256; + + enum State { Active, Refunding, Closed } + + mapping (address => uint256) public deposited; + address public wallet; + State public state; + + event Closed(); + event RefundsEnabled(); + event Refunded(address indexed beneficiary, uint256 weiAmount); + + function RefundVault(address _wallet) { + require(_wallet != 0x0); + wallet = _wallet; + state = State.Active; + } + + function deposit(address investor) onlyOwner payable { + require(state == State.Active); + deposited[investor] = deposited[investor].add(msg.value); + } + + function close() onlyOwner { + require(state == State.Active); + state = State.Closed; + Closed(); + wallet.transfer(this.balance); + } + + function enableRefunds() onlyOwner { + require(state == State.Active); + state = State.Refunding; + RefundsEnabled(); + } + + function refund(address investor) { + require(state == State.Refunding); + uint256 depositedValue = deposited[investor]; + deposited[investor] = 0; + investor.transfer(depositedValue); + Refunded(investor, depositedValue); + } +} diff --git a/test/compilationTests/zeppelin/crowdsale/RefundableCrowdsale.sol b/test/compilationTests/zeppelin/crowdsale/RefundableCrowdsale.sol new file mode 100644 index 00000000..f45df1d3 --- /dev/null +++ b/test/compilationTests/zeppelin/crowdsale/RefundableCrowdsale.sol @@ -0,0 +1,59 @@ +pragma solidity ^0.4.11; + + +import '../math/SafeMath.sol'; +import './FinalizableCrowdsale.sol'; +import './RefundVault.sol'; + + +/** + * @title RefundableCrowdsale + * @dev Extension of Crowdsale contract that adds a funding goal, and + * the possibility of users getting a refund if goal is not met. + * Uses a RefundVault as the crowdsale's vault. + */ +contract RefundableCrowdsale is FinalizableCrowdsale { + using SafeMath for uint256; + + // minimum amount of funds to be raised in weis + uint256 public goal; + + // refund vault used to hold funds while crowdsale is running + RefundVault public vault; + + function RefundableCrowdsale(uint256 _goal) { + vault = new RefundVault(wallet); + goal = _goal; + } + + // We're overriding the fund forwarding from Crowdsale. + // In addition to sending the funds, we want to call + // the RefundVault deposit function + function forwardFunds() internal { + vault.deposit.value(msg.value)(msg.sender); + } + + // if crowdsale is unsuccessful, investors can claim refunds here + function claimRefund() { + require(isFinalized); + require(!goalReached()); + + vault.refund(msg.sender); + } + + // vault finalization task, called when owner calls finalize() + function finalization() internal { + if (goalReached()) { + vault.close(); + } else { + vault.enableRefunds(); + } + + super.finalization(); + } + + function goalReached() public constant returns (bool) { + return weiRaised >= goal; + } + +} diff --git a/test/compilationTests/zeppelin/lifecycle/Destructible.sol b/test/compilationTests/zeppelin/lifecycle/Destructible.sol new file mode 100644 index 00000000..3561e3b7 --- /dev/null +++ b/test/compilationTests/zeppelin/lifecycle/Destructible.sol @@ -0,0 +1,25 @@ +pragma solidity ^0.4.11; + + +import "../ownership/Ownable.sol"; + + +/** + * @title Destructible + * @dev Base contract that can be destroyed by owner. All funds in contract will be sent to the owner. + */ +contract Destructible is Ownable { + + function Destructible() payable { } + + /** + * @dev Transfers the current balance to the owner and terminates the contract. + */ + function destroy() onlyOwner { + selfdestruct(owner); + } + + function destroyAndSend(address _recipient) onlyOwner { + selfdestruct(_recipient); + } +} diff --git a/test/compilationTests/zeppelin/lifecycle/Migrations.sol b/test/compilationTests/zeppelin/lifecycle/Migrations.sol new file mode 100644 index 00000000..d5b05308 --- /dev/null +++ b/test/compilationTests/zeppelin/lifecycle/Migrations.sol @@ -0,0 +1,21 @@ +pragma solidity ^0.4.11; + + +import '../ownership/Ownable.sol'; + +/** + * @title Migrations + * @dev This is a truffle contract, needed for truffle integration, not meant for use by Zeppelin users. + */ +contract Migrations is Ownable { + uint256 public lastCompletedMigration; + + function setCompleted(uint256 completed) onlyOwner { + lastCompletedMigration = completed; + } + + function upgrade(address newAddress) onlyOwner { + Migrations upgraded = Migrations(newAddress); + upgraded.setCompleted(lastCompletedMigration); + } +} diff --git a/test/compilationTests/zeppelin/lifecycle/Pausable.sol b/test/compilationTests/zeppelin/lifecycle/Pausable.sol new file mode 100644 index 00000000..b14f8767 --- /dev/null +++ b/test/compilationTests/zeppelin/lifecycle/Pausable.sol @@ -0,0 +1,51 @@ +pragma solidity ^0.4.11; + + +import "../ownership/Ownable.sol"; + + +/** + * @title Pausable + * @dev Base contract which allows children to implement an emergency stop mechanism. + */ +contract Pausable is Ownable { + event Pause(); + event Unpause(); + + bool public paused = false; + + + /** + * @dev modifier to allow actions only when the contract IS paused + */ + modifier whenNotPaused() { + if (paused) throw; + _; + } + + /** + * @dev modifier to allow actions only when the contract IS NOT paused + */ + modifier whenPaused { + if (!paused) throw; + _; + } + + /** + * @dev called by the owner to pause, triggers stopped state + */ + function pause() onlyOwner whenNotPaused returns (bool) { + paused = true; + Pause(); + return true; + } + + /** + * @dev called by the owner to unpause, returns to normal state + */ + function unpause() onlyOwner whenPaused returns (bool) { + paused = false; + Unpause(); + return true; + } +} diff --git a/test/compilationTests/zeppelin/lifecycle/TokenDestructible.sol b/test/compilationTests/zeppelin/lifecycle/TokenDestructible.sol new file mode 100644 index 00000000..fe0b46b6 --- /dev/null +++ b/test/compilationTests/zeppelin/lifecycle/TokenDestructible.sol @@ -0,0 +1,36 @@ +pragma solidity ^0.4.11; + + +import "../ownership/Ownable.sol"; +import "../token/ERC20Basic.sol"; + +/** + * @title TokenDestructible: + * @author Remco Bloemen <remco@2π.com> + * @dev Base contract that can be destroyed by owner. All funds in contract including + * listed tokens will be sent to the owner. + */ +contract TokenDestructible is Ownable { + + function TokenDestructible() payable { } + + /** + * @notice Terminate contract and refund to owner + * @param tokens List of addresses of ERC20 or ERC20Basic token contracts to + refund. + * @notice The called token contracts could try to re-enter this contract. Only + supply token contracts you trust. + */ + function destroy(address[] tokens) onlyOwner { + + // Transfer tokens to owner + for(uint256 i = 0; i < tokens.length; i++) { + ERC20Basic token = ERC20Basic(tokens[i]); + uint256 balance = token.balanceOf(this); + token.transfer(owner, balance); + } + + // Transfer Eth to owner and terminate contract + selfdestruct(owner); + } +} diff --git a/test/compilationTests/zeppelin/math/Math.sol b/test/compilationTests/zeppelin/math/Math.sol new file mode 100644 index 00000000..3d016c0a --- /dev/null +++ b/test/compilationTests/zeppelin/math/Math.sol @@ -0,0 +1,24 @@ +pragma solidity ^0.4.11; + +/** + * @title Math + * @dev Assorted math operations + */ + +library Math { + function max64(uint64 a, uint64 b) internal constant returns (uint64) { + return a >= b ? a : b; + } + + function min64(uint64 a, uint64 b) internal constant returns (uint64) { + return a < b ? a : b; + } + + function max256(uint256 a, uint256 b) internal constant returns (uint256) { + return a >= b ? a : b; + } + + function min256(uint256 a, uint256 b) internal constant returns (uint256) { + return a < b ? a : b; + } +} diff --git a/test/compilationTests/zeppelin/math/SafeMath.sol b/test/compilationTests/zeppelin/math/SafeMath.sol new file mode 100644 index 00000000..dc05ba28 --- /dev/null +++ b/test/compilationTests/zeppelin/math/SafeMath.sol @@ -0,0 +1,32 @@ +pragma solidity ^0.4.11; + + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + function mul(uint256 a, uint256 b) internal returns (uint256) { + uint256 c = a * b; + assert(a == 0 || c / a == b); + return c; + } + + function div(uint256 a, uint256 b) internal returns (uint256) { + // assert(b > 0); // Solidity automatically throws when dividing by 0 + uint256 c = a / b; + // assert(a == b * c + a % b); // There is no case in which this doesn't hold + return c; + } + + function sub(uint256 a, uint256 b) internal returns (uint256) { + assert(b <= a); + return a - b; + } + + function add(uint256 a, uint256 b) internal returns (uint256) { + uint256 c = a + b; + assert(c >= a); + return c; + } +} diff --git a/test/compilationTests/zeppelin/ownership/Claimable.sol b/test/compilationTests/zeppelin/ownership/Claimable.sol new file mode 100644 index 00000000..d063502d --- /dev/null +++ b/test/compilationTests/zeppelin/ownership/Claimable.sol @@ -0,0 +1,40 @@ +pragma solidity ^0.4.11; + + +import './Ownable.sol'; + + +/** + * @title Claimable + * @dev Extension for the Ownable contract, where the ownership needs to be claimed. + * This allows the new owner to accept the transfer. + */ +contract Claimable is Ownable { + address public pendingOwner; + + /** + * @dev Modifier throws if called by any account other than the pendingOwner. + */ + modifier onlyPendingOwner() { + if (msg.sender != pendingOwner) { + throw; + } + _; + } + + /** + * @dev Allows the current owner to set the pendingOwner address. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) onlyOwner { + pendingOwner = newOwner; + } + + /** + * @dev Allows the pendingOwner address to finalize the transfer. + */ + function claimOwnership() onlyPendingOwner { + owner = pendingOwner; + pendingOwner = 0x0; + } +} diff --git a/test/compilationTests/zeppelin/ownership/Contactable.sol b/test/compilationTests/zeppelin/ownership/Contactable.sol new file mode 100644 index 00000000..0db3ee07 --- /dev/null +++ b/test/compilationTests/zeppelin/ownership/Contactable.sol @@ -0,0 +1,21 @@ +pragma solidity ^0.4.11; + +import './Ownable.sol'; + +/** + * @title Contactable token + * @dev Basic version of a contactable contract, allowing the owner to provide a string with their + * contact information. + */ +contract Contactable is Ownable{ + + string public contactInformation; + + /** + * @dev Allows the owner to set a string with their contact information. + * @param info The contact information to attach to the contract. + */ + function setContactInformation(string info) onlyOwner{ + contactInformation = info; + } +} diff --git a/test/compilationTests/zeppelin/ownership/DelayedClaimable.sol b/test/compilationTests/zeppelin/ownership/DelayedClaimable.sol new file mode 100644 index 00000000..f5fee614 --- /dev/null +++ b/test/compilationTests/zeppelin/ownership/DelayedClaimable.sol @@ -0,0 +1,43 @@ +pragma solidity ^0.4.11; + + +import './Claimable.sol'; + + +/** + * @title DelayedClaimable + * @dev Extension for the Claimable contract, where the ownership needs to be claimed before/after + * a certain block number. + */ +contract DelayedClaimable is Claimable { + + uint256 public end; + uint256 public start; + + /** + * @dev Used to specify the time period during which a pending + * owner can claim ownership. + * @param _start The earliest time ownership can be claimed. + * @param _end The latest time ownership can be claimed. + */ + function setLimits(uint256 _start, uint256 _end) onlyOwner { + if (_start > _end) + throw; + end = _end; + start = _start; + } + + + /** + * @dev Allows the pendingOwner address to finalize the transfer, as long as it is called within + * the specified start and end time. + */ + function claimOwnership() onlyPendingOwner { + if ((block.number > end) || (block.number < start)) + throw; + owner = pendingOwner; + pendingOwner = 0x0; + end = 0; + } + +} diff --git a/test/compilationTests/zeppelin/ownership/HasNoContracts.sol b/test/compilationTests/zeppelin/ownership/HasNoContracts.sol new file mode 100644 index 00000000..b5bd649d --- /dev/null +++ b/test/compilationTests/zeppelin/ownership/HasNoContracts.sol @@ -0,0 +1,21 @@ +pragma solidity ^0.4.11; + +import "./Ownable.sol"; + +/** + * @title Contracts that should not own Contracts + * @author Remco Bloemen <remco@2π.com> + * @dev Should contracts (anything Ownable) end up being owned by this contract, it allows the owner + * of this contract to reclaim ownership of the contracts. + */ +contract HasNoContracts is Ownable { + + /** + * @dev Reclaim ownership of Ownable contracts + * @param contractAddr The address of the Ownable to be reclaimed. + */ + function reclaimContract(address contractAddr) external onlyOwner { + Ownable contractInst = Ownable(contractAddr); + contractInst.transferOwnership(owner); + } +} diff --git a/test/compilationTests/zeppelin/ownership/HasNoEther.sol b/test/compilationTests/zeppelin/ownership/HasNoEther.sol new file mode 100644 index 00000000..2bcaf1b8 --- /dev/null +++ b/test/compilationTests/zeppelin/ownership/HasNoEther.sol @@ -0,0 +1,44 @@ +pragma solidity ^0.4.11; + +import "./Ownable.sol"; + +/** + * @title Contracts that should not own Ether + * @author Remco Bloemen <remco@2π.com> + * @dev This tries to block incoming ether to prevent accidental loss of Ether. Should Ether end up + * in the contract, it will allow the owner to reclaim this ether. + * @notice Ether can still be send to this contract by: + * calling functions labeled `payable` + * `selfdestruct(contract_address)` + * mining directly to the contract address +*/ +contract HasNoEther is Ownable { + + /** + * @dev Constructor that rejects incoming Ether + * @dev The `payable` flag is added so we can access `msg.value` without compiler warning. If we + * leave out payable, then Solidity will allow inheriting contracts to implement a payable + * constructor. By doing it this way we prevent a payable constructor from working. Alternatively + * we could use assembly to access msg.value. + */ + function HasNoEther() payable { + if(msg.value > 0) { + throw; + } + } + + /** + * @dev Disallows direct send by settings a default function without the `payable` flag. + */ + function() external { + } + + /** + * @dev Transfer all Ether held by the contract to the owner. + */ + function reclaimEther() external onlyOwner { + if(!owner.send(this.balance)) { + throw; + } + } +} diff --git a/test/compilationTests/zeppelin/ownership/HasNoTokens.sol b/test/compilationTests/zeppelin/ownership/HasNoTokens.sol new file mode 100644 index 00000000..d1dc4b3e --- /dev/null +++ b/test/compilationTests/zeppelin/ownership/HasNoTokens.sol @@ -0,0 +1,34 @@ +pragma solidity ^0.4.11; + +import "./Ownable.sol"; +import "../token/ERC20Basic.sol"; + +/** + * @title Contracts that should not own Tokens + * @author Remco Bloemen <remco@2π.com> + * @dev This blocks incoming ERC23 tokens to prevent accidental loss of tokens. + * Should tokens (any ERC20Basic compatible) end up in the contract, it allows the + * owner to reclaim the tokens. + */ +contract HasNoTokens is Ownable { + + /** + * @dev Reject all ERC23 compatible tokens + * @param from_ address The address that is transferring the tokens + * @param value_ uint256 the amount of the specified token + * @param data_ Bytes The data passed from the caller. + */ + function tokenFallback(address from_, uint256 value_, bytes data_) external { + throw; + } + + /** + * @dev Reclaim all ERC20Basic compatible tokens + * @param tokenAddr address The address of the token contract + */ + function reclaimToken(address tokenAddr) external onlyOwner { + ERC20Basic tokenInst = ERC20Basic(tokenAddr); + uint256 balance = tokenInst.balanceOf(this); + tokenInst.transfer(owner, balance); + } +} diff --git a/test/compilationTests/zeppelin/ownership/Multisig.sol b/test/compilationTests/zeppelin/ownership/Multisig.sol new file mode 100644 index 00000000..76c78411 --- /dev/null +++ b/test/compilationTests/zeppelin/ownership/Multisig.sol @@ -0,0 +1,28 @@ +pragma solidity ^0.4.11; + + +/** + * @title Multisig + * @dev Interface contract for multisig proxy contracts; see below for docs. + */ +contract Multisig { + // EVENTS + + // logged events: + // Funds has arrived into the wallet (record how much). + event Deposit(address _from, uint256 value); + // Single transaction going out of the wallet (record who signed for it, how much, and to whom it's going). + event SingleTransact(address owner, uint256 value, address to, bytes data); + // Multi-sig transaction going out of the wallet (record who signed for it last, the operation hash, how much, and to whom it's going). + event MultiTransact(address owner, bytes32 operation, uint256 value, address to, bytes data); + // Confirmation still needed for a transaction. + event ConfirmationNeeded(bytes32 operation, address initiator, uint256 value, address to, bytes data); + + + // FUNCTIONS + + // TODO: document + function changeOwner(address _from, address _to) external; + function execute(address _to, uint256 _value, bytes _data) external returns (bytes32); + function confirm(bytes32 _h) returns (bool); +} diff --git a/test/compilationTests/zeppelin/ownership/NoOwner.sol b/test/compilationTests/zeppelin/ownership/NoOwner.sol new file mode 100644 index 00000000..7215abf3 --- /dev/null +++ b/test/compilationTests/zeppelin/ownership/NoOwner.sol @@ -0,0 +1,14 @@ +pragma solidity ^0.4.11; + +import "./HasNoEther.sol"; +import "./HasNoTokens.sol"; +import "./HasNoContracts.sol"; + +/** + * @title Base contract for contracts that should not own things. + * @author Remco Bloemen <remco@2π.com> + * @dev Solves a class of errors where a contract accidentally becomes owner of Ether, Tokens or + * Owned contracts. See respective base contracts for details. + */ +contract NoOwner is HasNoEther, HasNoTokens, HasNoContracts { +} diff --git a/test/compilationTests/zeppelin/ownership/Ownable.sol b/test/compilationTests/zeppelin/ownership/Ownable.sol new file mode 100644 index 00000000..f1628454 --- /dev/null +++ b/test/compilationTests/zeppelin/ownership/Ownable.sol @@ -0,0 +1,43 @@ +pragma solidity ^0.4.11; + + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + function Ownable() { + owner = msg.sender; + } + + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + if (msg.sender != owner) { + throw; + } + _; + } + + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) onlyOwner { + if (newOwner != address(0)) { + owner = newOwner; + } + } + +} diff --git a/test/compilationTests/zeppelin/ownership/Shareable.sol b/test/compilationTests/zeppelin/ownership/Shareable.sol new file mode 100644 index 00000000..9fdaccfd --- /dev/null +++ b/test/compilationTests/zeppelin/ownership/Shareable.sol @@ -0,0 +1,189 @@ +pragma solidity ^0.4.11; + + +/** + * @title Shareable + * @dev inheritable "property" contract that enables methods to be protected by requiring the + * acquiescence of either a single, or, crucially, each of a number of, designated owners. + * @dev Usage: use modifiers onlyowner (just own owned) or onlymanyowners(hash), whereby the same hash must be provided by some number (specified in constructor) of the set of owners (specified in the constructor) before the interior is executed. + */ +contract Shareable { + + // struct for the status of a pending operation. + struct PendingState { + uint256 yetNeeded; + uint256 ownersDone; + uint256 index; + } + + // the number of owners that must confirm the same operation before it is run. + uint256 public required; + + // list of owners + address[256] owners; + // index on the list of owners to allow reverse lookup + mapping(address => uint256) ownerIndex; + // the ongoing operations. + mapping(bytes32 => PendingState) pendings; + bytes32[] pendingsIndex; + + + // this contract only has six types of events: it can accept a confirmation, in which case + // we record owner and operation (hash) alongside it. + event Confirmation(address owner, bytes32 operation); + event Revoke(address owner, bytes32 operation); + + + // simple single-sig function modifier. + modifier onlyOwner { + if (!isOwner(msg.sender)) { + throw; + } + _; + } + + /** + * @dev Modifier for multisig functions. + * @param _operation The operation must have an intrinsic hash in order that later attempts can be + * realised as the same underlying operation and thus count as confirmations. + */ + modifier onlymanyowners(bytes32 _operation) { + if (confirmAndCheck(_operation)) { + _; + } + } + + /** + * @dev Constructor is given the number of sigs required to do protected "onlymanyowners" + * transactions as well as the selection of addresses capable of confirming them. + * @param _owners A list of owners. + * @param _required The amount required for a transaction to be approved. + */ + function Shareable(address[] _owners, uint256 _required) { + owners[1] = msg.sender; + ownerIndex[msg.sender] = 1; + for (uint256 i = 0; i < _owners.length; ++i) { + owners[2 + i] = _owners[i]; + ownerIndex[_owners[i]] = 2 + i; + } + required = _required; + if (required > owners.length) { + throw; + } + } + + /** + * @dev Revokes a prior confirmation of the given operation. + * @param _operation A string identifying the operation. + */ + function revoke(bytes32 _operation) external { + uint256 index = ownerIndex[msg.sender]; + // make sure they're an owner + if (index == 0) { + return; + } + uint256 ownerIndexBit = 2**index; + var pending = pendings[_operation]; + if (pending.ownersDone & ownerIndexBit > 0) { + pending.yetNeeded++; + pending.ownersDone -= ownerIndexBit; + Revoke(msg.sender, _operation); + } + } + + /** + * @dev Gets an owner by 0-indexed position (using numOwners as the count) + * @param ownerIndex uint256 The index of the owner + * @return The address of the owner + */ + function getOwner(uint256 ownerIndex) external constant returns (address) { + return address(owners[ownerIndex + 1]); + } + + /** + * @dev Checks if given address is an owner. + * @param _addr address The address which you want to check. + * @return True if the address is an owner and fase otherwise. + */ + function isOwner(address _addr) constant returns (bool) { + return ownerIndex[_addr] > 0; + } + + /** + * @dev Function to check is specific owner has already confirme the operation. + * @param _operation The operation identifier. + * @param _owner The owner address. + * @return True if the owner has confirmed and false otherwise. + */ + function hasConfirmed(bytes32 _operation, address _owner) constant returns (bool) { + var pending = pendings[_operation]; + uint256 index = ownerIndex[_owner]; + + // make sure they're an owner + if (index == 0) { + return false; + } + + // determine the bit to set for this owner. + uint256 ownerIndexBit = 2**index; + return !(pending.ownersDone & ownerIndexBit == 0); + } + + /** + * @dev Confirm and operation and checks if it's already executable. + * @param _operation The operation identifier. + * @return Returns true when operation can be executed. + */ + function confirmAndCheck(bytes32 _operation) internal returns (bool) { + // determine what index the present sender is: + uint256 index = ownerIndex[msg.sender]; + // make sure they're an owner + if (index == 0) { + throw; + } + + var pending = pendings[_operation]; + // if we're not yet working on this operation, switch over and reset the confirmation status. + if (pending.yetNeeded == 0) { + // reset count of confirmations needed. + pending.yetNeeded = required; + // reset which owners have confirmed (none) - set our bitmap to 0. + pending.ownersDone = 0; + pending.index = pendingsIndex.length++; + pendingsIndex[pending.index] = _operation; + } + // determine the bit to set for this owner. + uint256 ownerIndexBit = 2**index; + // make sure we (the message sender) haven't confirmed this operation previously. + if (pending.ownersDone & ownerIndexBit == 0) { + Confirmation(msg.sender, _operation); + // ok - check if count is enough to go ahead. + if (pending.yetNeeded <= 1) { + // enough confirmations: reset and run interior. + delete pendingsIndex[pendings[_operation].index]; + delete pendings[_operation]; + return true; + } else { + // not enough: record that this owner in particular confirmed. + pending.yetNeeded--; + pending.ownersDone |= ownerIndexBit; + } + } + return false; + } + + + /** + * @dev Clear the pending list. + */ + function clearPending() internal { + uint256 length = pendingsIndex.length; + for (uint256 i = 0; i < length; ++i) { + if (pendingsIndex[i] != 0) { + delete pendings[pendingsIndex[i]]; + } + } + delete pendingsIndex; + } + +} diff --git a/test/compilationTests/zeppelin/payment/PullPayment.sol b/test/compilationTests/zeppelin/payment/PullPayment.sol new file mode 100644 index 00000000..ba710b53 --- /dev/null +++ b/test/compilationTests/zeppelin/payment/PullPayment.sol @@ -0,0 +1,50 @@ +pragma solidity ^0.4.11; + + +import '../math/SafeMath.sol'; + + +/** + * @title PullPayment + * @dev Base contract supporting async send for pull payments. Inherit from this + * contract and use asyncSend instead of send. + */ +contract PullPayment { + using SafeMath for uint256; + + mapping(address => uint256) public payments; + uint256 public totalPayments; + + /** + * @dev Called by the payer to store the sent amount as credit to be pulled. + * @param dest The destination address of the funds. + * @param amount The amount to transfer. + */ + function asyncSend(address dest, uint256 amount) internal { + payments[dest] = payments[dest].add(amount); + totalPayments = totalPayments.add(amount); + } + + /** + * @dev withdraw accumulated balance, called by payee. + */ + function withdrawPayments() { + address payee = msg.sender; + uint256 payment = payments[payee]; + + if (payment == 0) { + throw; + } + + if (this.balance < payment) { + throw; + } + + totalPayments = totalPayments.sub(payment); + payments[payee] = 0; + + if (!payee.send(payment)) { + throw; + } + } +} diff --git a/test/compilationTests/zeppelin/token/BasicToken.sol b/test/compilationTests/zeppelin/token/BasicToken.sol new file mode 100644 index 00000000..5618227a --- /dev/null +++ b/test/compilationTests/zeppelin/token/BasicToken.sol @@ -0,0 +1,37 @@ +pragma solidity ^0.4.11; + + +import './ERC20Basic.sol'; +import '../math/SafeMath.sol'; + + +/** + * @title Basic token + * @dev Basic version of StandardToken, with no allowances. + */ +contract BasicToken is ERC20Basic { + using SafeMath for uint256; + + mapping(address => uint256) balances; + + /** + * @dev transfer token for a specified address + * @param _to The address to transfer to. + * @param _value The amount to be transferred. + */ + function transfer(address _to, uint256 _value) { + balances[msg.sender] = balances[msg.sender].sub(_value); + balances[_to] = balances[_to].add(_value); + Transfer(msg.sender, _to, _value); + } + + /** + * @dev Gets the balance of the specified address. + * @param _owner The address to query the the balance of. + * @return An uint256 representing the amount owned by the passed address. + */ + function balanceOf(address _owner) constant returns (uint256 balance) { + return balances[_owner]; + } + +} diff --git a/test/compilationTests/zeppelin/token/ERC20.sol b/test/compilationTests/zeppelin/token/ERC20.sol new file mode 100644 index 00000000..1045ac35 --- /dev/null +++ b/test/compilationTests/zeppelin/token/ERC20.sol @@ -0,0 +1,16 @@ +pragma solidity ^0.4.11; + + +import './ERC20Basic.sol'; + + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) constant returns (uint256); + function transferFrom(address from, address to, uint256 value); + function approve(address spender, uint256 value); + event Approval(address indexed owner, address indexed spender, uint256 value); +} diff --git a/test/compilationTests/zeppelin/token/ERC20Basic.sol b/test/compilationTests/zeppelin/token/ERC20Basic.sol new file mode 100644 index 00000000..0e98779e --- /dev/null +++ b/test/compilationTests/zeppelin/token/ERC20Basic.sol @@ -0,0 +1,14 @@ +pragma solidity ^0.4.11; + + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20Basic { + uint256 public totalSupply; + function balanceOf(address who) constant returns (uint256); + function transfer(address to, uint256 value); + event Transfer(address indexed from, address indexed to, uint256 value); +} diff --git a/test/compilationTests/zeppelin/token/LimitedTransferToken.sol b/test/compilationTests/zeppelin/token/LimitedTransferToken.sol new file mode 100644 index 00000000..ee5032c9 --- /dev/null +++ b/test/compilationTests/zeppelin/token/LimitedTransferToken.sol @@ -0,0 +1,57 @@ +pragma solidity ^0.4.11; + +import "./ERC20.sol"; + +/** + * @title LimitedTransferToken + * @dev LimitedTransferToken defines the generic interface and the implementation to limit token + * transferability for different events. It is intended to be used as a base class for other token + * contracts. + * LimitedTransferToken has been designed to allow for different limiting factors, + * this can be achieved by recursively calling super.transferableTokens() until the base class is + * hit. For example: + * function transferableTokens(address holder, uint64 time) constant public returns (uint256) { + * return min256(unlockedTokens, super.transferableTokens(holder, time)); + * } + * A working example is VestedToken.sol: + * https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/token/VestedToken.sol + */ + +contract LimitedTransferToken is ERC20 { + + /** + * @dev Checks whether it can transfer or otherwise throws. + */ + modifier canTransfer(address _sender, uint256 _value) { + if (_value > transferableTokens(_sender, uint64(now))) throw; + _; + } + + /** + * @dev Checks modifier and allows transfer if tokens are not locked. + * @param _to The address that will recieve the tokens. + * @param _value The amount of tokens to be transferred. + */ + function transfer(address _to, uint256 _value) canTransfer(msg.sender, _value) { + super.transfer(_to, _value); + } + + /** + * @dev Checks modifier and allows transfer if tokens are not locked. + * @param _from The address that will send the tokens. + * @param _to The address that will recieve the tokens. + * @param _value The amount of tokens to be transferred. + */ + function transferFrom(address _from, address _to, uint256 _value) canTransfer(_from, _value) { + super.transferFrom(_from, _to, _value); + } + + /** + * @dev Default transferable tokens function returns all tokens for a holder (no limit). + * @dev Overwriting transferableTokens(address holder, uint64 time) is the way to provide the + * specific logic for limiting token transferability for a holder over time. + */ + function transferableTokens(address holder, uint64 time) constant public returns (uint256) { + return balanceOf(holder); + } +} diff --git a/test/compilationTests/zeppelin/token/MintableToken.sol b/test/compilationTests/zeppelin/token/MintableToken.sol new file mode 100644 index 00000000..505d13c3 --- /dev/null +++ b/test/compilationTests/zeppelin/token/MintableToken.sol @@ -0,0 +1,50 @@ +pragma solidity ^0.4.11; + + +import './StandardToken.sol'; +import '../ownership/Ownable.sol'; + + + +/** + * @title Mintable token + * @dev Simple ERC20 Token example, with mintable token creation + * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 + * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol + */ + +contract MintableToken is StandardToken, Ownable { + event Mint(address indexed to, uint256 amount); + event MintFinished(); + + bool public mintingFinished = false; + + + modifier canMint() { + if(mintingFinished) throw; + _; + } + + /** + * @dev Function to mint tokens + * @param _to The address that will recieve the minted tokens. + * @param _amount The amount of tokens to mint. + * @return A boolean that indicates if the operation was successful. + */ + function mint(address _to, uint256 _amount) onlyOwner canMint returns (bool) { + totalSupply = totalSupply.add(_amount); + balances[_to] = balances[_to].add(_amount); + Mint(_to, _amount); + return true; + } + + /** + * @dev Function to stop minting new tokens. + * @return True if the operation was successful. + */ + function finishMinting() onlyOwner returns (bool) { + mintingFinished = true; + MintFinished(); + return true; + } +} diff --git a/test/compilationTests/zeppelin/token/PausableToken.sol b/test/compilationTests/zeppelin/token/PausableToken.sol new file mode 100644 index 00000000..8ee114e1 --- /dev/null +++ b/test/compilationTests/zeppelin/token/PausableToken.sol @@ -0,0 +1,21 @@ +pragma solidity ^0.4.11; + +import './StandardToken.sol'; +import '../lifecycle/Pausable.sol'; + +/** + * Pausable token + * + * Simple ERC20 Token example, with pausable token creation + **/ + +contract PausableToken is StandardToken, Pausable { + + function transfer(address _to, uint _value) whenNotPaused { + super.transfer(_to, _value); + } + + function transferFrom(address _from, address _to, uint _value) whenNotPaused { + super.transferFrom(_from, _to, _value); + } +} diff --git a/test/compilationTests/zeppelin/token/SimpleToken.sol b/test/compilationTests/zeppelin/token/SimpleToken.sol new file mode 100644 index 00000000..898cb21d --- /dev/null +++ b/test/compilationTests/zeppelin/token/SimpleToken.sol @@ -0,0 +1,28 @@ +pragma solidity ^0.4.11; + + +import "./StandardToken.sol"; + + +/** + * @title SimpleToken + * @dev Very simple ERC20 Token example, where all tokens are pre-assigned to the creator. + * Note they can later distribute these tokens as they wish using `transfer` and other + * `StandardToken` functions. + */ +contract SimpleToken is StandardToken { + + string public name = "SimpleToken"; + string public symbol = "SIM"; + uint256 public decimals = 18; + uint256 public INITIAL_SUPPLY = 10000; + + /** + * @dev Contructor that gives msg.sender all of existing tokens. + */ + function SimpleToken() { + totalSupply = INITIAL_SUPPLY; + balances[msg.sender] = INITIAL_SUPPLY; + } + +} diff --git a/test/compilationTests/zeppelin/token/StandardToken.sol b/test/compilationTests/zeppelin/token/StandardToken.sol new file mode 100644 index 00000000..b1b49fe3 --- /dev/null +++ b/test/compilationTests/zeppelin/token/StandardToken.sol @@ -0,0 +1,65 @@ +pragma solidity ^0.4.11; + + +import './BasicToken.sol'; +import './ERC20.sol'; + + +/** + * @title Standard ERC20 token + * + * @dev Implementation of the basic standard token. + * @dev https://github.com/ethereum/EIPs/issues/20 + * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol + */ +contract StandardToken is ERC20, BasicToken { + + mapping (address => mapping (address => uint256)) allowed; + + + /** + * @dev Transfer tokens from one address to another + * @param _from address The address which you want to send tokens from + * @param _to address The address which you want to transfer to + * @param _value uint256 the amout of tokens to be transfered + */ + function transferFrom(address _from, address _to, uint256 _value) { + var _allowance = allowed[_from][msg.sender]; + + // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met + // if (_value > _allowance) throw; + + balances[_to] = balances[_to].add(_value); + balances[_from] = balances[_from].sub(_value); + allowed[_from][msg.sender] = _allowance.sub(_value); + Transfer(_from, _to, _value); + } + + /** + * @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender. + * @param _spender The address which will spend the funds. + * @param _value The amount of tokens to be spent. + */ + function approve(address _spender, uint256 _value) { + + // To change the approve amount you first have to reduce the addresses` + // allowance to zero by calling `approve(_spender, 0)` if it is not + // already 0 to mitigate the race condition described here: + // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 + if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) throw; + + allowed[msg.sender][_spender] = _value; + Approval(msg.sender, _spender, _value); + } + + /** + * @dev Function to check the amount of tokens that an owner allowed to a spender. + * @param _owner address The address which owns the funds. + * @param _spender address The address which will spend the funds. + * @return A uint256 specifing the amount of tokens still avaible for the spender. + */ + function allowance(address _owner, address _spender) constant returns (uint256 remaining) { + return allowed[_owner][_spender]; + } + +} diff --git a/test/compilationTests/zeppelin/token/TokenTimelock.sol b/test/compilationTests/zeppelin/token/TokenTimelock.sol new file mode 100644 index 00000000..595bf8d0 --- /dev/null +++ b/test/compilationTests/zeppelin/token/TokenTimelock.sol @@ -0,0 +1,41 @@ +pragma solidity ^0.4.11; + + +import './ERC20Basic.sol'; + +/** + * @title TokenTimelock + * @dev TokenTimelock is a token holder contract that will allow a + * beneficiary to extract the tokens after a given release time + */ +contract TokenTimelock { + + // ERC20 basic token contract being held + ERC20Basic token; + + // beneficiary of tokens after they are released + address beneficiary; + + // timestamp when token release is enabled + uint releaseTime; + + function TokenTimelock(ERC20Basic _token, address _beneficiary, uint _releaseTime) { + require(_releaseTime > now); + token = _token; + beneficiary = _beneficiary; + releaseTime = _releaseTime; + } + + /** + * @dev beneficiary claims tokens held by time lock + */ + function claim() { + require(msg.sender == beneficiary); + require(now >= releaseTime); + + uint amount = token.balanceOf(this); + require(amount > 0); + + token.transfer(beneficiary, amount); + } +} diff --git a/test/compilationTests/zeppelin/token/VestedToken.sol b/test/compilationTests/zeppelin/token/VestedToken.sol new file mode 100644 index 00000000..b7748b09 --- /dev/null +++ b/test/compilationTests/zeppelin/token/VestedToken.sol @@ -0,0 +1,248 @@ +pragma solidity ^0.4.11; + +import "../math/Math.sol"; +import "./StandardToken.sol"; +import "./LimitedTransferToken.sol"; + +/** + * @title Vested token + * @dev Tokens that can be vested for a group of addresses. + */ +contract VestedToken is StandardToken, LimitedTransferToken { + + uint256 MAX_GRANTS_PER_ADDRESS = 20; + + struct TokenGrant { + address granter; // 20 bytes + uint256 value; // 32 bytes + uint64 cliff; + uint64 vesting; + uint64 start; // 3 * 8 = 24 bytes + bool revokable; + bool burnsOnRevoke; // 2 * 1 = 2 bits? or 2 bytes? + } // total 78 bytes = 3 sstore per operation (32 per sstore) + + mapping (address => TokenGrant[]) public grants; + + event NewTokenGrant(address indexed from, address indexed to, uint256 value, uint256 grantId); + + /** + * @dev Grant tokens to a specified address + * @param _to address The address which the tokens will be granted to. + * @param _value uint256 The amount of tokens to be granted. + * @param _start uint64 Time of the beginning of the grant. + * @param _cliff uint64 Time of the cliff period. + * @param _vesting uint64 The vesting period. + */ + function grantVestedTokens( + address _to, + uint256 _value, + uint64 _start, + uint64 _cliff, + uint64 _vesting, + bool _revokable, + bool _burnsOnRevoke + ) public { + + // Check for date inconsistencies that may cause unexpected behavior + if (_cliff < _start || _vesting < _cliff) { + throw; + } + + if (tokenGrantsCount(_to) > MAX_GRANTS_PER_ADDRESS) throw; // To prevent a user being spammed and have his balance locked (out of gas attack when calculating vesting). + + uint256 count = grants[_to].push( + TokenGrant( + _revokable ? msg.sender : 0, // avoid storing an extra 20 bytes when it is non-revokable + _value, + _cliff, + _vesting, + _start, + _revokable, + _burnsOnRevoke + ) + ); + + transfer(_to, _value); + + NewTokenGrant(msg.sender, _to, _value, count - 1); + } + + /** + * @dev Revoke the grant of tokens of a specifed address. + * @param _holder The address which will have its tokens revoked. + * @param _grantId The id of the token grant. + */ + function revokeTokenGrant(address _holder, uint256 _grantId) public { + TokenGrant grant = grants[_holder][_grantId]; + + if (!grant.revokable) { // Check if grant was revokable + throw; + } + + if (grant.granter != msg.sender) { // Only granter can revoke it + throw; + } + + address receiver = grant.burnsOnRevoke ? 0xdead : msg.sender; + + uint256 nonVested = nonVestedTokens(grant, uint64(now)); + + // remove grant from array + delete grants[_holder][_grantId]; + grants[_holder][_grantId] = grants[_holder][grants[_holder].length.sub(1)]; + grants[_holder].length -= 1; + + balances[receiver] = balances[receiver].add(nonVested); + balances[_holder] = balances[_holder].sub(nonVested); + + Transfer(_holder, receiver, nonVested); + } + + + /** + * @dev Calculate the total amount of transferable tokens of a holder at a given time + * @param holder address The address of the holder + * @param time uint64 The specific time. + * @return An uint256 representing a holder's total amount of transferable tokens. + */ + function transferableTokens(address holder, uint64 time) constant public returns (uint256) { + uint256 grantIndex = tokenGrantsCount(holder); + + if (grantIndex == 0) return balanceOf(holder); // shortcut for holder without grants + + // Iterate through all the grants the holder has, and add all non-vested tokens + uint256 nonVested = 0; + for (uint256 i = 0; i < grantIndex; i++) { + nonVested = SafeMath.add(nonVested, nonVestedTokens(grants[holder][i], time)); + } + + // Balance - totalNonVested is the amount of tokens a holder can transfer at any given time + uint256 vestedTransferable = SafeMath.sub(balanceOf(holder), nonVested); + + // Return the minimum of how many vested can transfer and other value + // in case there are other limiting transferability factors (default is balanceOf) + return Math.min256(vestedTransferable, super.transferableTokens(holder, time)); + } + + /** + * @dev Check the amount of grants that an address has. + * @param _holder The holder of the grants. + * @return A uint256 representing the total amount of grants. + */ + function tokenGrantsCount(address _holder) constant returns (uint256 index) { + return grants[_holder].length; + } + + /** + * @dev Calculate amount of vested tokens at a specifc time. + * @param tokens uint256 The amount of tokens grantted. + * @param time uint64 The time to be checked + * @param start uint64 A time representing the begining of the grant + * @param cliff uint64 The cliff period. + * @param vesting uint64 The vesting period. + * @return An uint256 representing the amount of vested tokensof a specif grant. + * transferableTokens + * | _/-------- vestedTokens rect + * | _/ + * | _/ + * | _/ + * | _/ + * | / + * | .| + * | . | + * | . | + * | . | + * | . | + * | . | + * +===+===========+---------+----------> time + * Start Clift Vesting + */ + function calculateVestedTokens( + uint256 tokens, + uint256 time, + uint256 start, + uint256 cliff, + uint256 vesting) constant returns (uint256) + { + // Shortcuts for before cliff and after vesting cases. + if (time < cliff) return 0; + if (time >= vesting) return tokens; + + // Interpolate all vested tokens. + // As before cliff the shortcut returns 0, we can use just calculate a value + // in the vesting rect (as shown in above's figure) + + // vestedTokens = tokens * (time - start) / (vesting - start) + uint256 vestedTokens = SafeMath.div( + SafeMath.mul( + tokens, + SafeMath.sub(time, start) + ), + SafeMath.sub(vesting, start) + ); + + return vestedTokens; + } + + /** + * @dev Get all information about a specifc grant. + * @param _holder The address which will have its tokens revoked. + * @param _grantId The id of the token grant. + * @return Returns all the values that represent a TokenGrant(address, value, start, cliff, + * revokability, burnsOnRevoke, and vesting) plus the vested value at the current time. + */ + function tokenGrant(address _holder, uint256 _grantId) constant returns (address granter, uint256 value, uint256 vested, uint64 start, uint64 cliff, uint64 vesting, bool revokable, bool burnsOnRevoke) { + TokenGrant grant = grants[_holder][_grantId]; + + granter = grant.granter; + value = grant.value; + start = grant.start; + cliff = grant.cliff; + vesting = grant.vesting; + revokable = grant.revokable; + burnsOnRevoke = grant.burnsOnRevoke; + + vested = vestedTokens(grant, uint64(now)); + } + + /** + * @dev Get the amount of vested tokens at a specific time. + * @param grant TokenGrant The grant to be checked. + * @param time The time to be checked + * @return An uint256 representing the amount of vested tokens of a specific grant at a specific time. + */ + function vestedTokens(TokenGrant grant, uint64 time) private constant returns (uint256) { + return calculateVestedTokens( + grant.value, + uint256(time), + uint256(grant.start), + uint256(grant.cliff), + uint256(grant.vesting) + ); + } + + /** + * @dev Calculate the amount of non vested tokens at a specific time. + * @param grant TokenGrant The grant to be checked. + * @param time uint64 The time to be checked + * @return An uint256 representing the amount of non vested tokens of a specifc grant on the + * passed time frame. + */ + function nonVestedTokens(TokenGrant grant, uint64 time) private constant returns (uint256) { + return grant.value.sub(vestedTokens(grant, time)); + } + + /** + * @dev Calculate the date when the holder can trasfer all its tokens + * @param holder address The address of the holder + * @return An uint256 representing the date of the last transferable tokens. + */ + function lastTokenIsTransferableDate(address holder) constant public returns (uint64 date) { + date = uint64(now); + uint256 grantIndex = grants[holder].length; + for (uint256 i = 0; i < grantIndex; i++) { + date = Math.max64(grants[holder][i].vesting, date); + } + } +} diff --git a/test/contracts/AuctionRegistrar.cpp b/test/contracts/AuctionRegistrar.cpp index fb8c1c68..773b14b9 100644 --- a/test/contracts/AuctionRegistrar.cpp +++ b/test/contracts/AuctionRegistrar.cpp @@ -223,7 +223,8 @@ protected: { m_compiler.reset(false); m_compiler.addSource("", registrarCode); - ETH_TEST_REQUIRE_NO_THROW(m_compiler.compile(m_optimize, m_optimizeRuns), "Compiling contract failed"); + m_compiler.setOptimiserSettings(m_optimize, m_optimizeRuns); + ETH_TEST_REQUIRE_NO_THROW(m_compiler.compile(), "Compiling contract failed"); s_compiledRegistrar.reset(new bytes(m_compiler.object("GlobalRegistrar").bytecode)); } sendMessage(*s_compiledRegistrar, true); diff --git a/test/contracts/FixedFeeRegistrar.cpp b/test/contracts/FixedFeeRegistrar.cpp index d2904b5f..967d60b6 100644 --- a/test/contracts/FixedFeeRegistrar.cpp +++ b/test/contracts/FixedFeeRegistrar.cpp @@ -135,7 +135,8 @@ protected: { m_compiler.reset(false); m_compiler.addSource("", registrarCode); - ETH_TEST_REQUIRE_NO_THROW(m_compiler.compile(m_optimize, m_optimizeRuns), "Compiling contract failed"); + m_compiler.setOptimiserSettings(m_optimize, m_optimizeRuns); + ETH_TEST_REQUIRE_NO_THROW(m_compiler.compile(), "Compiling contract failed"); s_compiledRegistrar.reset(new bytes(m_compiler.object("FixedFeeRegistrar").bytecode)); } sendMessage(*s_compiledRegistrar, true); diff --git a/test/contracts/LLL_ENS.cpp b/test/contracts/LLL_ENS.cpp new file mode 100644 index 00000000..c5fe8a82 --- /dev/null +++ b/test/contracts/LLL_ENS.cpp @@ -0,0 +1,506 @@ +/* + This file is part of solidity. + + solidity 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. + + solidity 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 solidity. If not, see <http://www.gnu.org/licenses/>. +*/ +/** + * @author Ben Edgington <ben@benjaminion.xyz> + * @date 2017 + * Tests for the deployed ENS Registry implementation written in LLL + */ + +#include <string> +#include <boost/test/unit_test.hpp> +#include <test/liblll/ExecutionFramework.h> +#include <liblll/Compiler.h> + +#define ACCOUNT(n) h256(account(n), h256::AlignRight) + +using namespace std; +using namespace dev::eth; + +namespace dev +{ +namespace lll +{ +namespace test +{ + +namespace +{ + +static char const* ensCode = R"DELIMITER( +;;; --------------------------------------------------------------------------- +;;; @title The Ethereum Name Service registry. +;;; @author Daniel Ellison <daniel@syrinx.net> + +(seq + + ;; -------------------------------------------------------------------------- + ;; Constant definitions. + + ;; Memory layout. + (def 'node-bytes 0x00) + (def 'label-bytes 0x20) + (def 'call-result 0x40) + + ;; Struct: Record + (def 'resolver 0x00) ; address + (def 'owner 0x20) ; address + (def 'ttl 0x40) ; uint64 + + ;; Precomputed function IDs. + (def 'get-node-owner 0x02571be3) ; owner(bytes32) + (def 'get-node-resolver 0x0178b8bf) ; resolver(bytes32) + (def 'get-node-ttl 0x16a25cbd) ; ttl(bytes32) + (def 'set-node-owner 0x5b0fc9c3) ; setOwner(bytes32,address) + (def 'set-subnode-owner 0x06ab5923) ; setSubnodeOwner(bytes32,bytes32,address) + (def 'set-node-resolver 0x1896f70a) ; setResolver(bytes32,address) + (def 'set-node-ttl 0x14ab9038) ; setTTL(bytes32,uint64) + + ;; Jumping here causes an EVM error. + (def 'invalid-location 0x02) + + ;; -------------------------------------------------------------------------- + ;; @notice Shifts the leftmost 4 bytes of a 32-byte number right by 28 bytes. + ;; @param input A 32-byte number. + + (def 'shift-right (input) + (div input (exp 2 224))) + + ;; -------------------------------------------------------------------------- + ;; @notice Determines whether the supplied function ID matches a known + ;; function hash and executes <code-body> if so. + ;; @dev The function ID is in the leftmost four bytes of the call data. + ;; @param function-hash The four-byte hash of a known function signature. + ;; @param code-body The code to run in the case of a match. + + (def 'function (function-hash code-body) + (when (= (shift-right (calldataload 0x00)) function-hash) + code-body)) + + ;; -------------------------------------------------------------------------- + ;; @notice Calculates record location for the node and label passed in. + ;; @param node The parent node. + ;; @param label The hash of the subnode label. + + (def 'get-record (node label) + (seq + (mstore node-bytes node) + (mstore label-bytes label) + (sha3 node-bytes 64))) + + ;; -------------------------------------------------------------------------- + ;; @notice Retrieves owner from node record. + ;; @param node Get owner of this node. + + (def 'get-owner (node) + (sload (+ node owner))) + + ;; -------------------------------------------------------------------------- + ;; @notice Stores new owner in node record. + ;; @param node Set owner of this node. + ;; @param new-owner New owner of this node. + + (def 'set-owner (node new-owner) + (sstore (+ node owner) new-owner)) + + ;; -------------------------------------------------------------------------- + ;; @notice Stores new subnode owner in node record. + ;; @param node Set owner of this node. + ;; @param label The hash of the label specifying the subnode. + ;; @param new-owner New owner of the subnode. + + (def 'set-subowner (node label new-owner) + (sstore (+ (get-record node label) owner) new-owner)) + + ;; -------------------------------------------------------------------------- + ;; @notice Retrieves resolver from node record. + ;; @param node Get resolver of this node. + + (def 'get-resolver (node) + (sload node)) + + ;; -------------------------------------------------------------------------- + ;; @notice Stores new resolver in node record. + ;; @param node Set resolver of this node. + ;; @param new-resolver New resolver for this node. + + (def 'set-resolver (node new-resolver) + (sstore node new-resolver)) + + ;; -------------------------------------------------------------------------- + ;; @notice Retrieves TTL From node record. + ;; @param node Get TTL of this node. + + (def 'get-ttl (node) + (sload (+ node ttl))) + + ;; -------------------------------------------------------------------------- + ;; @notice Stores new TTL in node record. + ;; @param node Set TTL of this node. + ;; @param new-resolver New TTL for this node. + + (def 'set-ttl (node new-ttl) + (sstore (+ node ttl) new-ttl)) + + ;; -------------------------------------------------------------------------- + ;; @notice Checks that the caller is the node owner. + ;; @param node Check owner of this node. + + (def 'only-node-owner (node) + (when (!= (caller) (get-owner node)) + (jump invalid-location))) + + ;; -------------------------------------------------------------------------- + ;; INIT + + ;; Set the owner of the root node (0x00) to the deploying account. + (set-owner 0x00 (caller)) + + ;; -------------------------------------------------------------------------- + ;; CODE + + (returnlll + (seq + + ;; ---------------------------------------------------------------------- + ;; @notice Returns the address of the resolver for the specified node. + ;; @dev Signature: resolver(bytes32) + ;; @param node Return this node's resolver. + ;; @return The associated resolver. + + (def 'node (calldataload 0x04)) + + (function get-node-resolver + (seq + + ;; Get the node's resolver and save it. + (mstore call-result (get-resolver node)) + + ;; Return result. + (return call-result 32))) + + ;; ---------------------------------------------------------------------- + ;; @notice Returns the address that owns the specified node. + ;; @dev Signature: owner(bytes32) + ;; @param node Return this node's owner. + ;; @return The associated address. + + (def 'node (calldataload 0x04)) + + (function get-node-owner + (seq + + ;; Get the node's owner and save it. + (mstore call-result (get-owner node)) + + ;; Return result. + (return call-result 32))) + + ;; ---------------------------------------------------------------------- + ;; @notice Returns the TTL of a node and any records associated with it. + ;; @dev Signature: ttl(bytes32) + ;; @param node Return this node's TTL. + ;; @return The node's TTL. + + (def 'node (calldataload 0x04)) + + (function get-node-ttl + (seq + + ;; Get the node's TTL and save it. + (mstore call-result (get-ttl node)) + + ;; Return result. + (return call-result 32))) + + ;; ---------------------------------------------------------------------- + ;; @notice Transfers ownership of a node to a new address. May only be + ;; called by the current owner of the node. + ;; @dev Signature: setOwner(bytes32,address) + ;; @param node The node to transfer ownership of. + ;; @param new-owner The address of the new owner. + + (def 'node (calldataload 0x04)) + (def 'new-owner (calldataload 0x24)) + + (function set-node-owner + (seq (only-node-owner node) + + ;; Transfer ownership by storing passed-in address. + (set-owner node new-owner) + + ;; Emit an event about the transfer. + ;; Transfer(bytes32 indexed node, address owner); + (mstore call-result new-owner) + (log2 call-result 32 + (sha3 0x00 (lit 0x00 "Transfer(bytes32,address)")) node) + + ;; Nothing to return. + (stop))) + + ;; ---------------------------------------------------------------------- + ;; @notice Transfers ownership of a subnode to a new address. May only be + ;; called by the owner of the parent node. + ;; @dev Signature: setSubnodeOwner(bytes32,bytes32,address) + ;; @param node The parent node. + ;; @param label The hash of the label specifying the subnode. + ;; @param new-owner The address of the new owner. + + (def 'node (calldataload 0x04)) + (def 'label (calldataload 0x24)) + (def 'new-owner (calldataload 0x44)) + + (function set-subnode-owner + (seq (only-node-owner node) + + ;; Transfer ownership by storing passed-in address. + (set-subowner node label new-owner) + + ;; Emit an event about the transfer. + ;; NewOwner(bytes32 indexed node, bytes32 indexed label, address owner); + (mstore call-result new-owner) + (log3 call-result 32 + (sha3 0x00 (lit 0x00 "NewOwner(bytes32,bytes32,address)")) + node label) + + ;; Nothing to return. + (stop))) + + ;; ---------------------------------------------------------------------- + ;; @notice Sets the resolver address for the specified node. + ;; @dev Signature: setResolver(bytes32,address) + ;; @param node The node to update. + ;; @param new-resolver The address of the resolver. + + (def 'node (calldataload 0x04)) + (def 'new-resolver (calldataload 0x24)) + + (function set-node-resolver + (seq (only-node-owner node) + + ;; Transfer ownership by storing passed-in address. + (set-resolver node new-resolver) + + ;; Emit an event about the change of resolver. + ;; NewResolver(bytes32 indexed node, address resolver); + (mstore call-result new-resolver) + (log2 call-result 32 + (sha3 0x00 (lit 0x00 "NewResolver(bytes32,address)")) node) + + ;; Nothing to return. + (stop))) + + ;; ---------------------------------------------------------------------- + ;; @notice Sets the TTL for the specified node. + ;; @dev Signature: setTTL(bytes32,uint64) + ;; @param node The node to update. + ;; @param ttl The TTL in seconds. + + (def 'node (calldataload 0x04)) + (def 'new-ttl (calldataload 0x24)) + + (function set-node-ttl + (seq (only-node-owner node) + + ;; Set new TTL by storing passed-in time. + (set-ttl node new-ttl) + + ;; Emit an event about the change of TTL. + ;; NewTTL(bytes32 indexed node, uint64 ttl); + (mstore call-result new-ttl) + (log2 call-result 32 + (sha3 0x00 (lit 0x00 "NewTTL(bytes32,uint64)")) node) + + ;; Nothing to return. + (stop))) + + ;; ---------------------------------------------------------------------- + ;; @notice Fallback: No functions matched the function ID provided. + + (jump invalid-location))) + +) +)DELIMITER"; + +static unique_ptr<bytes> s_compiledEns; + +class LLLENSTestFramework: public LLLExecutionFramework +{ +protected: + void deployEns() + { + if (!s_compiledEns) + { + vector<string> errors; + s_compiledEns.reset(new bytes(compileLLL(ensCode, dev::test::Options::get().optimize, &errors))); + BOOST_REQUIRE(errors.empty()); + } + sendMessage(*s_compiledEns, true); + BOOST_REQUIRE(!m_output.empty()); + } + +}; + +} + +// Test suite for the deployed ENS Registry implementation written in LLL +BOOST_FIXTURE_TEST_SUITE(LLLENS, LLLENSTestFramework) + +BOOST_AUTO_TEST_CASE(creation) +{ + deployEns(); + + // Root node 0x00 should initially be owned by the deploying account, account(0). + BOOST_CHECK(callContractFunction("owner(bytes32)", 0x00) == encodeArgs(ACCOUNT(0))); +} + +BOOST_AUTO_TEST_CASE(transfer_ownership) +{ + deployEns(); + + // Transfer ownership of root node from account(0) to account(1). + BOOST_REQUIRE(callContractFunction("setOwner(bytes32,address)", 0x00, ACCOUNT(1)) == encodeArgs()); + + // Check that an event was raised and contents are correct. + BOOST_REQUIRE(m_logs.size() == 1); + BOOST_CHECK(m_logs[0].data == encodeArgs(ACCOUNT(1))); + BOOST_REQUIRE(m_logs[0].topics.size() == 2); + BOOST_CHECK(m_logs[0].topics[0] == keccak256(string("Transfer(bytes32,address)"))); + BOOST_CHECK(m_logs[0].topics[1] == u256(0x00)); + + // Verify that owner of 0x00 is now account(1). + BOOST_CHECK(callContractFunction("owner(bytes32)", 0x00) == encodeArgs(ACCOUNT(1))); +} + +BOOST_AUTO_TEST_CASE(transfer_ownership_fail) +{ + deployEns(); + + // Try to steal ownership of node 0x01 + BOOST_REQUIRE(callContractFunction("setOwner(bytes32,address)", 0x01, ACCOUNT(0)) == encodeArgs()); + + // Verify that owner of 0x01 remains the default zero address + BOOST_CHECK(callContractFunction("owner(bytes32)", 0x01) == encodeArgs(0)); +} + +BOOST_AUTO_TEST_CASE(set_resolver) +{ + deployEns(); + + // Set resolver of root node to account(1). + BOOST_REQUIRE(callContractFunction("setResolver(bytes32,address)", 0x00, ACCOUNT(1)) == encodeArgs()); + + // Check that an event was raised and contents are correct. + BOOST_REQUIRE(m_logs.size() == 1); + BOOST_CHECK(m_logs[0].data == encodeArgs(ACCOUNT(1))); + BOOST_REQUIRE(m_logs[0].topics.size() == 2); + BOOST_CHECK(m_logs[0].topics[0] == keccak256(string("NewResolver(bytes32,address)"))); + BOOST_CHECK(m_logs[0].topics[1] == u256(0x00)); + + // Verify that the resolver is changed to account(1). + BOOST_CHECK(callContractFunction("resolver(bytes32)", 0x00) == encodeArgs(ACCOUNT(1))); +} + +BOOST_AUTO_TEST_CASE(set_resolver_fail) +{ + deployEns(); + + // Try to set resolver of node 0x01, which is not owned by account(0). + BOOST_REQUIRE(callContractFunction("setResolver(bytes32,address)", 0x01, ACCOUNT(0)) == encodeArgs()); + + // Verify that the resolver of 0x01 remains default zero address. + BOOST_CHECK(callContractFunction("resolver(bytes32)", 0x01) == encodeArgs(0)); +} + +BOOST_AUTO_TEST_CASE(set_ttl) +{ + deployEns(); + + // Set ttl of root node to 3600. + BOOST_REQUIRE(callContractFunction("setTTL(bytes32,uint64)", 0x00, 3600) == encodeArgs()); + + // Check that an event was raised and contents are correct. + BOOST_REQUIRE(m_logs.size() == 1); + BOOST_CHECK(m_logs[0].data == encodeArgs(3600)); + BOOST_REQUIRE(m_logs[0].topics.size() == 2); + BOOST_CHECK(m_logs[0].topics[0] == keccak256(string("NewTTL(bytes32,uint64)"))); + BOOST_CHECK(m_logs[0].topics[1] == u256(0x00)); + + // Verify that the TTL has been set. + BOOST_CHECK(callContractFunction("ttl(bytes32)", 0x00) == encodeArgs(3600)); +} + +BOOST_AUTO_TEST_CASE(set_ttl_fail) +{ + deployEns(); + + // Try to set TTL of node 0x01, which is not owned by account(0). + BOOST_REQUIRE(callContractFunction("setTTL(bytes32,uint64)", 0x01, 3600) == encodeArgs()); + + // Verify that the TTL of node 0x01 has not changed from the default. + BOOST_CHECK(callContractFunction("ttl(bytes32)", 0x01) == encodeArgs(0)); +} + +BOOST_AUTO_TEST_CASE(create_subnode) +{ + deployEns(); + + // Set ownership of "eth" sub-node to account(1) + BOOST_REQUIRE(callContractFunction("setSubnodeOwner(bytes32,bytes32,address)", 0x00, keccak256(string("eth")), ACCOUNT(1)) == encodeArgs()); + + // Check that an event was raised and contents are correct. + BOOST_REQUIRE(m_logs.size() == 1); + BOOST_CHECK(m_logs[0].data == encodeArgs(ACCOUNT(1))); + BOOST_REQUIRE(m_logs[0].topics.size() == 3); + BOOST_CHECK(m_logs[0].topics[0] == keccak256(string("NewOwner(bytes32,bytes32,address)"))); + BOOST_CHECK(m_logs[0].topics[1] == u256(0x00)); + BOOST_CHECK(m_logs[0].topics[2] == keccak256(string("eth"))); + + // Verify that the sub-node owner is now account(1). + u256 namehash = keccak256(h256(0x00).asBytes() + keccak256("eth").asBytes()); + BOOST_CHECK(callContractFunction("owner(bytes32)", namehash) == encodeArgs(ACCOUNT(1))); +} + +BOOST_AUTO_TEST_CASE(create_subnode_fail) +{ + deployEns(); + + // Send account(1) some ether for gas. + sendEther(account(1), 1000 * ether); + BOOST_REQUIRE(balanceAt(account(1)) >= 1000 * ether); + + // account(1) tries to set ownership of the "eth" sub-node. + m_sender = account(1); + BOOST_REQUIRE(callContractFunction("setSubnodeOwner(bytes32,bytes32,address)", 0x00, keccak256(string("eth")), ACCOUNT(1)) == encodeArgs()); + + // Verify that the sub-node owner remains at default zero address. + u256 namehash = keccak256(h256(0x00).asBytes() + keccak256("eth").asBytes()); + BOOST_CHECK(callContractFunction("owner(bytes32)", namehash) == encodeArgs(0)); +} + +BOOST_AUTO_TEST_CASE(fallback) +{ + deployEns(); + + // Call fallback - should just abort via jump to invalid location. + BOOST_CHECK(callFallback() == encodeArgs()); +} + +BOOST_AUTO_TEST_SUITE_END() + +} +} +} // end namespaces diff --git a/test/contracts/LLL_ERC20.cpp b/test/contracts/LLL_ERC20.cpp new file mode 100644 index 00000000..25665d64 --- /dev/null +++ b/test/contracts/LLL_ERC20.cpp @@ -0,0 +1,651 @@ +/* + This file is part of solidity. + + solidity 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. + + solidity 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 solidity. If not, see <http://www.gnu.org/licenses/>. +*/ +/** + * @author Ben Edgington <ben@benjaminion.xyz> + * @date 2017 + * Tests for an ERC20 token implementation written in LLL + */ + +#include <string> +#include <boost/test/unit_test.hpp> +#include <test/liblll/ExecutionFramework.h> +#include <liblll/Compiler.h> + +#define TOKENSUPPLY 100000 +#define TOKENDECIMALS 2 +#define TOKENSYMBOL "BEN" +#define TOKENNAME "Ben Token" +#define ACCOUNT(n) h256(account(n), h256::AlignRight) +#define SUCCESS encodeArgs(1) + +using namespace std; +using namespace dev::eth; + +namespace dev +{ +namespace lll +{ +namespace test +{ + +namespace +{ + +static char const* erc20Code = R"DELIMITER( +(seq + + ;; -------------------------------------------------------------------------- + ;; CONSTANTS + + ;; Token parameters. + ;; 0x40 is a "magic number" - the text of the string is placed here + ;; when returning the string to the caller. See return-string below. + (def 'token-name-string (lit 0x40 "Ben Token")) + (def 'token-symbol-string (lit 0x40 "BEN")) + (def 'token-decimals 2) + (def 'token-supply 100000) ; 1000.00 total tokens + + ;; Booleans + (def 'false 0) + (def 'true 1) + + ;; Memory layout. + (def 'mem-ret 0x00) ; Fixed due to compiler macro for return. + (def 'mem-func 0x00) ; No conflict with mem-ret, so re-use. + (def 'mem-keccak 0x00) ; No conflict with mem-func or mem-ret, so re-use. + (def 'scratch0 0x20) + (def 'scratch1 0x40) + + ;; Precomputed function IDs. + (def 'get-name 0x06fdde03) ; name() + (def 'get-symbol 0x95d89b41) ; symbol() + (def 'get-decimals 0x313ce567) ; decimals() + (def 'get-total-supply 0x18160ddd) ; totalSupply() + (def 'get-balance-of 0x70a08231) ; balanceOf(address) + (def 'transfer 0xa9059cbb) ; transfer(address,uint256) + (def 'transfer-from 0x23b872dd) ; transferFrom(address,address,uint256) + (def 'approve 0x095ea7b3) ; approve(address,uint256) + (def 'get-allowance 0xdd62ed3e) ; allowance(address,address) + + ;; Event IDs + (def 'transfer-event-id ; Transfer(address,address,uint256) + 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef) + + (def 'approval-event-id ; Approval(address,address,uint256) + 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925) + + ;; -------------------------------------------------------------------------- + ;; UTILITIES + + ;; -------------------------------------------------------------------------- + ;; The following define the key data-structures: + ;; - balance(addr) => value + ;; - allowance(addr,addr) => value + + ;; Balances are stored at s[owner_addr]. + (def 'balance (address) address) + + ;; Allowances are stored at s[owner_addr + keccak256(spender_addr)] + ;; We use a crypto function here to avoid any situation where + ;; approve(me, spender) can be abused to do approve(target, me). + (def 'allowance (owner spender) + (seq + (mstore mem-keccak spender) + (keccak256 mem-keccak 0x20))) + + ;; -------------------------------------------------------------------------- + ;; For convenience we have macros to refer to function arguments + + (def 'arg1 (calldataload 0x04)) + (def 'arg2 (calldataload 0x24)) + (def 'arg3 (calldataload 0x44)) + + ;; -------------------------------------------------------------------------- + ;; Revert is a soft return that does not consume the remaining gas. + ;; We use it when rejecting invalid user input. + ;; + ;; Note: The REVERT opcode will be implemented in Metropolis (EIP 140). + ;; Meanwhile it just causes an invalid instruction exception (similar + ;; to a "throw" in Solidity). When fully implemented, Revert could be + ;; use to return error codes, or even messages. + + (def 'revert () (revert 0 0)) + + ;; -------------------------------------------------------------------------- + ;; Macro for returning string names. + ;; Compliant with the ABI format for strings. + + (def 'return-string (string-literal) + (seq + (mstore 0x00 0x20) ; Points to our string's memory location + (mstore 0x20 string-literal) ; Length. String itself is copied to 0x40. + (return 0x00 (& (+ (mload 0x20) 0x5f) (~ 0x1f))))) + ; Round return up to 32 byte boundary + + ;; -------------------------------------------------------------------------- + ;; Convenience macro for raising Events + + (def 'event3 (id addr1 addr2 value) + (seq + (mstore scratch0 value) + (log3 scratch0 0x20 id addr1 addr2))) + + ;; -------------------------------------------------------------------------- + ;; Determines whether the stored function ID matches a known + ;; function hash and executes <code-body> if so. + ;; @param function-hash The four-byte hash of a known function signature. + ;; @param code-body The code to run in the case of a match. + + (def 'function (function-hash code-body) + (when (= (mload mem-func) function-hash) + code-body)) + + ;; -------------------------------------------------------------------------- + ;; Gets the function ID and stores it in memory for reference. + ;; The function ID is in the leftmost four bytes of the call data. + + (def 'uses-functions + (mstore + mem-func + (shr (calldataload 0x00) 224))) + + ;; -------------------------------------------------------------------------- + ;; GUARDS + + ;; -------------------------------------------------------------------------- + ;; Checks that ensure that each function is called with the right + ;; number of arguments. For one thing this addresses the "ERC20 + ;; short address attack". For another, it stops me making + ;; mistakes while testing. We use these only on the non-constant functions. + + (def 'has-one-arg (unless (= 0x24 (calldatasize)) (revert))) + (def 'has-two-args (unless (= 0x44 (calldatasize)) (revert))) + (def 'has-three-args (unless (= 0x64 (calldatasize)) (revert))) + + ;; -------------------------------------------------------------------------- + ;; Check that addresses have only 160 bits and revert if not. + ;; We use these input type-checks on the non-constant functions. + + (def 'is-address (addr) + (when + (shr addr 160) + (revert))) + + ;; -------------------------------------------------------------------------- + ;; Check that transfer values are smaller than total supply and + ;; revert if not. This should effectively exclude negative values. + + (def 'is-value (value) + (when (> value token-supply) (revert))) + + ;; -------------------------------------------------------------------------- + ;; Will revert if sent any Ether. We use the macro immediately so as + ;; to abort if sent any Ether during contract deployment. + + (def 'not-payable + (when (callvalue) (revert))) + + not-payable + + ;; -------------------------------------------------------------------------- + ;; INITIALISATION + ;; + ;; Assign all tokens initially to the owner of the contract. + + (sstore (balance (caller)) token-supply) + + ;; -------------------------------------------------------------------------- + ;; CONTRACT CODE + + (returnlll + (seq not-payable uses-functions + + ;; ---------------------------------------------------------------------- + ;; Getter for the name of the token. + ;; @abi name() constant returns (string) + ;; @return The token name as a string. + + (function get-name + (return-string token-name-string)) + + ;; ---------------------------------------------------------------------- + ;; Getter for the symbol of the token. + ;; @abi symbol() constant returns (string) + ;; @return The token symbol as a string. + + (function get-symbol + (return-string token-symbol-string)) + + ;; ---------------------------------------------------------------------- + ;; Getter for the number of decimals assigned to the token. + ;; @abi decimals() constant returns (uint256) + ;; @return The token decimals. + + (function get-decimals + (return token-decimals)) + + ;; ---------------------------------------------------------------------- + ;; Getter for the total token supply. + ;; @abi totalSupply() constant returns (uint256) + ;; @return The token supply. + + (function get-total-supply + (return token-supply)) + + ;; ---------------------------------------------------------------------- + ;; Returns the account balance of another account. + ;; @abi balanceOf(address) constant returns (uint256) + ;; @param owner The address of the account's owner. + ;; @return The account balance. + + (function get-balance-of + (seq + + (def 'owner arg1) + + (return (sload (balance owner))))) + + ;; ---------------------------------------------------------------------- + ;; Transfers _value amount of tokens to address _to. The command + ;; should throw if the _from account balance has not enough + ;; tokens to spend. + ;; @abi transfer(address, uint256) returns (bool) + ;; @param to The account to receive the tokens. + ;; @param value The quantity of tokens to transfer. + ;; @return Success (true). Other outcomes result in a Revert. + + (function transfer + (seq has-two-args (is-address arg1) (is-value arg2) + + (def 'to arg1) + (def 'value arg2) + + (when value ; value == 0 is a no-op + (seq + + ;; The caller's balance. Save in memory for efficiency. + (mstore scratch0 (sload (balance (caller)))) + + ;; Revert if the caller's balance is not sufficient. + (when (> value (mload scratch0)) + (revert)) + + ;; Make the transfer + ;; It would be good to check invariants (sum of balances). + (sstore (balance (caller)) (- (mload scratch0) value)) + (sstore (balance to) (+ (sload (balance to)) value)) + + ;; Event - Transfer(address,address,uint256) + (event3 transfer-event-id (caller) to value))) + + (return true))) + + ;; ---------------------------------------------------------------------- + ;; Send _value amount of tokens from address _from to address _to + ;; @abi transferFrom(address,address,uint256) returns (bool) + ;; @param from The account to send the tokens from. + ;; @param to The account to receive the tokens. + ;; @param value The quantity of tokens to transfer. + ;; @return Success (true). Other outcomes result in a Revert. + + (function transfer-from + (seq has-three-args (is-address arg1) (is-address arg2) (is-value arg3) + + (def 'from arg1) + (def 'to arg2) + (def 'value arg3) + + (when value ; value == 0 is a no-op + + (seq + + ;; Save data to memory for efficiency. + (mstore scratch0 (sload (balance from))) + (mstore scratch1 (sload (allowance from (caller)))) + + ;; Revert if not enough funds, or not enough approved. + (when + (|| + (> value (mload scratch0)) + (> value (mload scratch1))) + (revert)) + + ;; Make the transfer and update allowance. + (sstore (balance from) (- (mload scratch0) value)) + (sstore (balance to) (+ (sload (balance to)) value)) + (sstore (allowance from (caller)) (- (mload scratch1) value)) + + ;; Event - Transfer(address,address,uint256) + (event3 transfer-event-id from to value))) + + (return true))) + + ;; ---------------------------------------------------------------------- + ;; Allows _spender to withdraw from your account multiple times, + ;; up to the _value amount. If this function is called again it + ;; overwrites the current allowance with _value. + ;; @abi approve(address,uint256) returns (bool) + ;; @param spender The withdrawing account having its limit set. + ;; @param value The maximum allowed amount. + ;; @return Success (true). Other outcomes result in a Revert. + + (function approve + (seq has-two-args (is-address arg1) (is-value arg2) + + (def 'spender arg1) + (def 'value arg2) + + ;; Force users set the allowance to 0 before setting it to + ;; another value for the same spender. Prevents this attack: + ;; https://docs.google.com/document/d/1YLPtQxZu1UAvO9cZ1O2RPXBbT0mooh4DYKjA_jp-RLM + (when + (&& value (sload (allowance (caller) spender))) + (revert)) + + (sstore (allowance (caller) spender) value) + + ;; Event - Approval(address,address,uint256) + (event3 approval-event-id (caller) spender value) + + (return true))) + + ;; ---------------------------------------------------------------------- + ;; Returns the amount which _spender is still allowed to withdraw + ;; from _owner. + ;; @abi allowance(address,address) constant returns (uint256) + ;; @param owner The owning account. + ;; @param spender The withdrawing account. + ;; @return The allowed amount remaining. + + (function get-allowance + (seq + + (def 'owner arg1) + (def 'spender arg2) + + (return (sload (allowance owner spender))))) + + ;; ---------------------------------------------------------------------- + ;; Fallback: No functions matched the function ID provided. + + (revert))) + ) +)DELIMITER"; + +static unique_ptr<bytes> s_compiledErc20; + +class LLLERC20TestFramework: public LLLExecutionFramework +{ +protected: + void deployErc20() + { + if (!s_compiledErc20) + { + vector<string> errors; + s_compiledErc20.reset(new bytes(compileLLL(erc20Code, dev::test::Options::get().optimize, &errors))); + BOOST_REQUIRE(errors.empty()); + } + sendMessage(*s_compiledErc20, true); + BOOST_REQUIRE(!m_output.empty()); + } + +}; + +} + +// Test suite for an ERC20 contract written in LLL. +BOOST_FIXTURE_TEST_SUITE(LLLERC20, LLLERC20TestFramework) + +BOOST_AUTO_TEST_CASE(creation) +{ + deployErc20(); + + // All tokens are initially assigned to the contract creator. + BOOST_CHECK(callContractFunction("balanceOf(address)", ACCOUNT(0)) == encodeArgs(TOKENSUPPLY)); +} + +BOOST_AUTO_TEST_CASE(constants) +{ + deployErc20(); + + BOOST_CHECK(callContractFunction("totalSupply()") == encodeArgs(TOKENSUPPLY)); + BOOST_CHECK(callContractFunction("decimals()") == encodeArgs(TOKENDECIMALS)); + BOOST_CHECK(callContractFunction("symbol()") == encodeDyn(string(TOKENSYMBOL))); + BOOST_CHECK(callContractFunction("name()") == encodeDyn(string(TOKENNAME))); +} + +BOOST_AUTO_TEST_CASE(send_value) +{ + deployErc20(); + + // Send value to the contract. Should always fail. + m_sender = account(0); + auto contractBalance = balanceAt(m_contractAddress); + + // Fallback: check value is not transferred. + BOOST_CHECK(callFallbackWithValue(42) != SUCCESS); + BOOST_CHECK(balanceAt(m_contractAddress) == contractBalance); + + // Transfer: check nothing happened. + BOOST_CHECK(callContractFunctionWithValue("transfer(address,uint256)", ACCOUNT(1), 100, 42) != SUCCESS); + BOOST_CHECK(balanceAt(m_contractAddress) == contractBalance); + BOOST_CHECK(callContractFunction("balanceOf(address)", ACCOUNT(1)) == encodeArgs(0)); + BOOST_CHECK(callContractFunction("balanceOf(address)", ACCOUNT(0)) == encodeArgs(TOKENSUPPLY)); +} + +BOOST_AUTO_TEST_CASE(transfer) +{ + deployErc20(); + + // Transfer 100 tokens from account(0) to account(1). + int transfer = 100; + m_sender = account(0); + BOOST_CHECK(callContractFunction("transfer(address,uint256)", ACCOUNT(1), u256(transfer)) == SUCCESS); + BOOST_CHECK(callContractFunction("balanceOf(address)", ACCOUNT(0)) == encodeArgs(TOKENSUPPLY - transfer)); + BOOST_CHECK(callContractFunction("balanceOf(address)", ACCOUNT(1)) == encodeArgs(transfer)); +} + +BOOST_AUTO_TEST_CASE(transfer_from) +{ + deployErc20(); + + // Approve account(1) to transfer up to 1000 tokens from account(0). + int allow = 1000; + m_sender = account(0); + BOOST_REQUIRE(callContractFunction("approve(address,uint256)", ACCOUNT(1), u256(allow)) == SUCCESS); + BOOST_REQUIRE(callContractFunction("allowance(address,address)", ACCOUNT(0), ACCOUNT(1)) == encodeArgs(allow)); + + // Send account(1) some ether for gas. + sendEther(account(1), 1000 * ether); + BOOST_REQUIRE(balanceAt(account(1)) >= 1000 * ether); + + // Transfer 300 tokens from account(0) to account(2); check that the allowance decreases. + int transfer = 300; + m_sender = account(1); + BOOST_REQUIRE(callContractFunction("transferFrom(address,address,uint256)", ACCOUNT(0), ACCOUNT(2), u256(transfer)) == SUCCESS); + BOOST_CHECK(callContractFunction("balanceOf(address)", ACCOUNT(2)) == encodeArgs(transfer)); + BOOST_CHECK(callContractFunction("balanceOf(address)", ACCOUNT(0)) == encodeArgs(TOKENSUPPLY - transfer)); + BOOST_CHECK(callContractFunction("allowance(address,address)", ACCOUNT(0), ACCOUNT(1)) == encodeArgs(allow - transfer)); +} + +BOOST_AUTO_TEST_CASE(transfer_event) +{ + deployErc20(); + + // Transfer 1000 tokens from account(0) to account(1). + int transfer = 1000; + m_sender = account(0); + BOOST_REQUIRE(callContractFunction("transfer(address,uint256)", ACCOUNT(1), u256(transfer)) == SUCCESS); + + // Check that a Transfer event was recorded and contents are correct. + BOOST_REQUIRE(m_logs.size() == 1); + BOOST_CHECK(m_logs[0].data == encodeArgs(transfer)); + BOOST_REQUIRE(m_logs[0].topics.size() == 3); + BOOST_CHECK(m_logs[0].topics[0] == keccak256(string("Transfer(address,address,uint256)"))); + BOOST_CHECK(m_logs[0].topics[1] == ACCOUNT(0)); + BOOST_CHECK(m_logs[0].topics[2] == ACCOUNT(1)); +} + +BOOST_AUTO_TEST_CASE(transfer_zero_no_event) +{ + deployErc20(); + + // Transfer 0 tokens from account(0) to account(1). This is a no-op. + int transfer = 0; + m_sender = account(0); + BOOST_REQUIRE(callContractFunction("transfer(address,uint256)", ACCOUNT(1), u256(transfer)) == SUCCESS); + + // Check that no Event was recorded. + BOOST_CHECK(m_logs.size() == 0); + + // Check that balances have not changed. + BOOST_CHECK(callContractFunction("balanceOf(address)", ACCOUNT(0)) == encodeArgs(TOKENSUPPLY - transfer)); + BOOST_CHECK(callContractFunction("balanceOf(address)", ACCOUNT(1)) == encodeArgs(transfer)); +} + +BOOST_AUTO_TEST_CASE(approval_and_transfer_events) +{ + deployErc20(); + + // Approve account(1) to transfer up to 10000 tokens from account(0). + int allow = 10000; + m_sender = account(0); + BOOST_REQUIRE(callContractFunction("approve(address,uint256)", ACCOUNT(1), u256(allow)) == SUCCESS); + + // Check that an Approval event was recorded and contents are correct. + BOOST_REQUIRE(m_logs.size() == 1); + BOOST_CHECK(m_logs[0].data == encodeArgs(allow)); + BOOST_REQUIRE(m_logs[0].topics.size() == 3); + BOOST_CHECK(m_logs[0].topics[0] == keccak256(string("Approval(address,address,uint256)"))); + BOOST_CHECK(m_logs[0].topics[1] == ACCOUNT(0)); + BOOST_CHECK(m_logs[0].topics[2] == ACCOUNT(1)); + + // Send account(1) some ether for gas. + sendEther(account(1), 1000 * ether); + BOOST_REQUIRE(balanceAt(account(1)) >= 1000 * ether); + + // Transfer 3000 tokens from account(0) to account(2); check that the allowance decreases. + int transfer = 3000; + m_sender = account(1); + BOOST_REQUIRE(callContractFunction("transferFrom(address,address,uint256)", ACCOUNT(0), ACCOUNT(2), u256(transfer)) == SUCCESS); + + // Check that a Transfer event was recorded and contents are correct. + BOOST_REQUIRE(m_logs.size() == 1); + BOOST_CHECK(m_logs[0].data == encodeArgs(transfer)); + BOOST_REQUIRE(m_logs[0].topics.size() == 3); + BOOST_CHECK(m_logs[0].topics[0] == keccak256(string("Transfer(address,address,uint256)"))); + BOOST_CHECK(m_logs[0].topics[1] == ACCOUNT(0)); + BOOST_CHECK(m_logs[0].topics[2] == ACCOUNT(2)); +} + +BOOST_AUTO_TEST_CASE(invalid_transfer_1) +{ + deployErc20(); + + // Transfer more than the total supply; ensure nothing changes. + int transfer = TOKENSUPPLY + 1; + m_sender = account(0); + BOOST_CHECK(callContractFunction("transfer(address,uint256)", ACCOUNT(1), u256(transfer)) != SUCCESS); + BOOST_CHECK(callContractFunction("balanceOf(address)", ACCOUNT(0)) == encodeArgs(TOKENSUPPLY)); + BOOST_CHECK(callContractFunction("balanceOf(address)", ACCOUNT(1)) == encodeArgs(0)); +} + +BOOST_AUTO_TEST_CASE(invalid_transfer_2) +{ + deployErc20(); + + // Separate transfers that together exceed initial balance. + int transfer = 1 + TOKENSUPPLY / 2; + m_sender = account(0); + + // First transfer should succeed. + BOOST_REQUIRE(callContractFunction("transfer(address,uint256)", ACCOUNT(1), u256(transfer)) == SUCCESS); + BOOST_REQUIRE(callContractFunction("balanceOf(address)", ACCOUNT(0)) == encodeArgs(TOKENSUPPLY - transfer)); + BOOST_REQUIRE(callContractFunction("balanceOf(address)", ACCOUNT(1)) == encodeArgs(transfer)); + + // Second transfer should fail. + BOOST_CHECK(callContractFunction("transfer(address,uint256)", ACCOUNT(1), u256(transfer)) != SUCCESS); + BOOST_CHECK(callContractFunction("balanceOf(address)", ACCOUNT(0)) == encodeArgs(TOKENSUPPLY - transfer)); + BOOST_CHECK(callContractFunction("balanceOf(address)", ACCOUNT(1)) == encodeArgs(transfer)); +} + +BOOST_AUTO_TEST_CASE(invalid_transfer_from) +{ + deployErc20(); + + // TransferFrom without approval. + int transfer = 300; + + // Send account(1) some ether for gas. + m_sender = account(0); + sendEther(account(1), 1000 * ether); + BOOST_REQUIRE(balanceAt(account(1)) >= 1000 * ether); + + // Try the transfer; ensure nothing changes. + m_sender = account(1); + BOOST_CHECK(callContractFunction("transferFrom(address,address,uint256)", ACCOUNT(0), ACCOUNT(2), u256(transfer)) != SUCCESS); + BOOST_CHECK(callContractFunction("balanceOf(address)", ACCOUNT(2)) == encodeArgs(0)); + BOOST_CHECK(callContractFunction("balanceOf(address)", ACCOUNT(0)) == encodeArgs(TOKENSUPPLY)); + BOOST_CHECK(callContractFunction("allowance(address,address)", ACCOUNT(0), ACCOUNT(1)) == encodeArgs(0)); +} + +BOOST_AUTO_TEST_CASE(invalid_reapprove) +{ + deployErc20(); + + m_sender = account(0); + + // Approve account(1) to transfer up to 1000 tokens from account(0). + int allow1 = 1000; + BOOST_REQUIRE(callContractFunction("approve(address,uint256)", ACCOUNT(1), u256(allow1)) == SUCCESS); + BOOST_REQUIRE(callContractFunction("allowance(address,address)", ACCOUNT(0), ACCOUNT(1)) == encodeArgs(allow1)); + + // Now approve account(1) to transfer up to 500 tokens from account(0). + // Should fail (we need to reset allowance to 0 first). + int allow2 = 500; + BOOST_CHECK(callContractFunction("approve(address,uint256)", ACCOUNT(1), u256(allow2)) != SUCCESS); + BOOST_CHECK(callContractFunction("allowance(address,address)", ACCOUNT(0), ACCOUNT(1)) == encodeArgs(allow1)); +} + +BOOST_AUTO_TEST_CASE(bad_data) +{ + deployErc20(); + + m_sender = account(0); + + // Correct data: transfer(address _to, 1). + sendMessage((bytes)fromHex("a9059cbb") + (bytes)fromHex("000000000000000000000000123456789a123456789a123456789a123456789a") + encodeArgs(1), false, 0); + BOOST_CHECK(m_output == SUCCESS); + + // Too little data (address is truncated by one byte). + sendMessage((bytes)fromHex("a9059cbb") + (bytes)fromHex("000000000000000000000000123456789a123456789a123456789a12345678") + encodeArgs(1), false, 0); + BOOST_CHECK(m_output != SUCCESS); + + // Too much data (address is extended with a zero byte). + sendMessage((bytes)fromHex("a9059cbb") + (bytes)fromHex("000000000000000000000000123456789a123456789a123456789a123456789a00") + encodeArgs(1), false, 0); + BOOST_CHECK(m_output != SUCCESS); + + // Invalid address (a bit above the 160th is set). + sendMessage((bytes)fromHex("a9059cbb") + (bytes)fromHex("000000000000000000000100123456789a123456789a123456789a123456789a") + encodeArgs(1), false, 0); + BOOST_CHECK(m_output != SUCCESS); +} + +BOOST_AUTO_TEST_SUITE_END() + +} +} +} // end namespaces diff --git a/test/contracts/Wallet.cpp b/test/contracts/Wallet.cpp index ef345d86..d12b7493 100644 --- a/test/contracts/Wallet.cpp +++ b/test/contracts/Wallet.cpp @@ -450,7 +450,8 @@ protected: { m_compiler.reset(false); m_compiler.addSource("", walletCode); - ETH_TEST_REQUIRE_NO_THROW(m_compiler.compile(m_optimize, m_optimizeRuns), "Compiling contract failed"); + m_compiler.setOptimiserSettings(m_optimize, m_optimizeRuns); + ETH_TEST_REQUIRE_NO_THROW(m_compiler.compile(), "Compiling contract failed"); s_compiledWallet.reset(new bytes(m_compiler.object("Wallet").bytecode)); } bytes args = encodeArgs(u256(0x60), _required, _dailyLimit, u256(_owners.size()), _owners); diff --git a/test/libevmasm/Optimiser.cpp b/test/libevmasm/Optimiser.cpp new file mode 100644 index 00000000..5aa81af5 --- /dev/null +++ b/test/libevmasm/Optimiser.cpp @@ -0,0 +1,871 @@ +/* + This file is part of solidity. + + solidity 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. + + solidity 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 solidity. If not, see <http://www.gnu.org/licenses/>. +*/ +/** + * @author Christian <c@ethdev.com> + * @date 2014 + * Tests for the Solidity optimizer. + */ + +#include <libevmasm/CommonSubexpressionEliminator.h> +#include <libevmasm/PeepholeOptimiser.h> +#include <libevmasm/ControlFlowGraph.h> +#include <libevmasm/BlockDeduplicator.h> +#include <libevmasm/Assembly.h> + +#include <boost/test/unit_test.hpp> +#include <boost/lexical_cast.hpp> + +#include <chrono> +#include <string> +#include <tuple> +#include <memory> + +using namespace std; +using namespace dev::eth; + +namespace dev +{ +namespace solidity +{ +namespace test +{ + +namespace +{ + AssemblyItems addDummyLocations(AssemblyItems const& _input) + { + // add dummy locations to each item so that we can check that they are not deleted + AssemblyItems input = _input; + for (AssemblyItem& item: input) + item.setLocation(SourceLocation(1, 3, make_shared<string>(""))); + return input; + } + + eth::KnownState createInitialState(AssemblyItems const& _input) + { + eth::KnownState state; + for (auto const& item: addDummyLocations(_input)) + state.feedItem(item, true); + return state; + } + + AssemblyItems CSE(AssemblyItems const& _input, eth::KnownState const& _state = eth::KnownState()) + { + AssemblyItems input = addDummyLocations(_input); + + eth::CommonSubexpressionEliminator cse(_state); + BOOST_REQUIRE(cse.feedItems(input.begin(), input.end()) == input.end()); + AssemblyItems output = cse.getOptimizedItems(); + + for (AssemblyItem const& item: output) + { + BOOST_CHECK(item == Instruction::POP || !item.location().isEmpty()); + } + return output; + } + + void checkCSE( + AssemblyItems const& _input, + AssemblyItems const& _expectation, + KnownState const& _state = eth::KnownState() + ) + { + AssemblyItems output = CSE(_input, _state); + BOOST_CHECK_EQUAL_COLLECTIONS(_expectation.begin(), _expectation.end(), output.begin(), output.end()); + } + + AssemblyItems CFG(AssemblyItems const& _input) + { + AssemblyItems output = _input; + // Running it four times should be enough for these tests. + for (unsigned i = 0; i < 4; ++i) + { + ControlFlowGraph cfg(output); + AssemblyItems optItems; + for (BasicBlock const& block: cfg.optimisedBlocks()) + copy(output.begin() + block.begin, output.begin() + block.end, + back_inserter(optItems)); + output = move(optItems); + } + return output; + } + + void checkCFG(AssemblyItems const& _input, AssemblyItems const& _expectation) + { + AssemblyItems output = CFG(_input); + BOOST_CHECK_EQUAL_COLLECTIONS(_expectation.begin(), _expectation.end(), output.begin(), output.end()); + } +} + +BOOST_AUTO_TEST_SUITE(Optimiser) + +BOOST_AUTO_TEST_CASE(cse_intermediate_swap) +{ + eth::KnownState state; + eth::CommonSubexpressionEliminator cse(state); + AssemblyItems input{ + Instruction::SWAP1, Instruction::POP, Instruction::ADD, u256(0), Instruction::SWAP1, + Instruction::SLOAD, Instruction::SWAP1, u256(100), Instruction::EXP, Instruction::SWAP1, + Instruction::DIV, u256(0xff), Instruction::AND + }; + BOOST_REQUIRE(cse.feedItems(input.begin(), input.end()) == input.end()); + AssemblyItems output = cse.getOptimizedItems(); + BOOST_CHECK(!output.empty()); +} + +BOOST_AUTO_TEST_CASE(cse_negative_stack_access) +{ + AssemblyItems input{Instruction::DUP2, u256(0)}; + checkCSE(input, input); +} + +BOOST_AUTO_TEST_CASE(cse_negative_stack_end) +{ + AssemblyItems input{Instruction::ADD}; + checkCSE(input, input); +} + +BOOST_AUTO_TEST_CASE(cse_intermediate_negative_stack) +{ + AssemblyItems input{Instruction::ADD, u256(1), Instruction::DUP1}; + checkCSE(input, input); +} + +BOOST_AUTO_TEST_CASE(cse_pop) +{ + checkCSE({Instruction::POP}, {Instruction::POP}); +} + +BOOST_AUTO_TEST_CASE(cse_unneeded_items) +{ + AssemblyItems input{ + Instruction::ADD, + Instruction::SWAP1, + Instruction::POP, + u256(7), + u256(8), + }; + checkCSE(input, input); +} + +BOOST_AUTO_TEST_CASE(cse_constant_addition) +{ + AssemblyItems input{u256(7), u256(8), Instruction::ADD}; + checkCSE(input, {u256(7 + 8)}); +} + +BOOST_AUTO_TEST_CASE(cse_invariants) +{ + AssemblyItems input{ + Instruction::DUP1, + Instruction::DUP1, + u256(0), + Instruction::OR, + Instruction::OR + }; + checkCSE(input, {Instruction::DUP1}); +} + +BOOST_AUTO_TEST_CASE(cse_subself) +{ + checkCSE({Instruction::DUP1, Instruction::SUB}, {Instruction::POP, u256(0)}); +} + +BOOST_AUTO_TEST_CASE(cse_subother) +{ + checkCSE({Instruction::SUB}, {Instruction::SUB}); +} + +BOOST_AUTO_TEST_CASE(cse_double_negation) +{ + checkCSE({Instruction::DUP5, Instruction::NOT, Instruction::NOT}, {Instruction::DUP5}); +} + +BOOST_AUTO_TEST_CASE(cse_double_iszero) +{ + checkCSE({Instruction::GT, Instruction::ISZERO, Instruction::ISZERO}, {Instruction::GT}); + checkCSE({Instruction::GT, Instruction::ISZERO}, {Instruction::GT, Instruction::ISZERO}); + checkCSE( + {Instruction::ISZERO, Instruction::ISZERO, Instruction::ISZERO}, + {Instruction::ISZERO} + ); +} + +BOOST_AUTO_TEST_CASE(cse_associativity) +{ + AssemblyItems input{ + Instruction::DUP1, + Instruction::DUP1, + u256(0), + Instruction::OR, + Instruction::OR + }; + checkCSE(input, {Instruction::DUP1}); +} + +BOOST_AUTO_TEST_CASE(cse_associativity2) +{ + AssemblyItems input{ + u256(0), + Instruction::DUP2, + u256(2), + u256(1), + Instruction::DUP6, + Instruction::ADD, + u256(2), + Instruction::ADD, + Instruction::ADD, + Instruction::ADD, + Instruction::ADD + }; + checkCSE(input, {Instruction::DUP2, Instruction::DUP2, Instruction::ADD, u256(5), Instruction::ADD}); +} + +BOOST_AUTO_TEST_CASE(cse_storage) +{ + AssemblyItems input{ + u256(0), + Instruction::SLOAD, + u256(0), + Instruction::SLOAD, + Instruction::ADD, + u256(0), + Instruction::SSTORE + }; + checkCSE(input, { + u256(0), + Instruction::DUP1, + Instruction::SLOAD, + Instruction::DUP1, + Instruction::ADD, + Instruction::SWAP1, + Instruction::SSTORE + }); +} + +BOOST_AUTO_TEST_CASE(cse_noninterleaved_storage) +{ + // two stores to the same location should be replaced by only one store, even if we + // read in the meantime + AssemblyItems input{ + u256(7), + Instruction::DUP2, + Instruction::SSTORE, + Instruction::DUP1, + Instruction::SLOAD, + u256(8), + Instruction::DUP3, + Instruction::SSTORE + }; + checkCSE(input, { + u256(8), + Instruction::DUP2, + Instruction::SSTORE, + u256(7) + }); +} + +BOOST_AUTO_TEST_CASE(cse_interleaved_storage) +{ + // stores and reads to/from two unknown locations, should not optimize away the first store + AssemblyItems input{ + u256(7), + Instruction::DUP2, + Instruction::SSTORE, // store to "DUP1" + Instruction::DUP2, + Instruction::SLOAD, // read from "DUP2", might be equal to "DUP1" + u256(0), + Instruction::DUP3, + Instruction::SSTORE // store different value to "DUP1" + }; + checkCSE(input, input); +} + +BOOST_AUTO_TEST_CASE(cse_interleaved_storage_same_value) +{ + // stores and reads to/from two unknown locations, should not optimize away the first store + // but it should optimize away the second, since we already know the value will be the same + AssemblyItems input{ + u256(7), + Instruction::DUP2, + Instruction::SSTORE, // store to "DUP1" + Instruction::DUP2, + Instruction::SLOAD, // read from "DUP2", might be equal to "DUP1" + u256(6), + u256(1), + Instruction::ADD, + Instruction::DUP3, + Instruction::SSTORE // store same value to "DUP1" + }; + checkCSE(input, { + u256(7), + Instruction::DUP2, + Instruction::SSTORE, + Instruction::DUP2, + Instruction::SLOAD + }); +} + +BOOST_AUTO_TEST_CASE(cse_interleaved_storage_at_known_location) +{ + // stores and reads to/from two known locations, should optimize away the first store, + // because we know that the location is different + AssemblyItems input{ + u256(0x70), + u256(1), + Instruction::SSTORE, // store to 1 + u256(2), + Instruction::SLOAD, // read from 2, is different from 1 + u256(0x90), + u256(1), + Instruction::SSTORE // store different value at 1 + }; + checkCSE(input, { + u256(2), + Instruction::SLOAD, + u256(0x90), + u256(1), + Instruction::SSTORE + }); +} + +BOOST_AUTO_TEST_CASE(cse_interleaved_storage_at_known_location_offset) +{ + // stores and reads to/from two locations which are known to be different, + // should optimize away the first store, because we know that the location is different + AssemblyItems input{ + u256(0x70), + Instruction::DUP2, + u256(1), + Instruction::ADD, + Instruction::SSTORE, // store to "DUP1"+1 + Instruction::DUP1, + u256(2), + Instruction::ADD, + Instruction::SLOAD, // read from "DUP1"+2, is different from "DUP1"+1 + u256(0x90), + Instruction::DUP3, + u256(1), + Instruction::ADD, + Instruction::SSTORE // store different value at "DUP1"+1 + }; + checkCSE(input, { + u256(2), + Instruction::DUP2, + Instruction::ADD, + Instruction::SLOAD, + u256(0x90), + u256(1), + Instruction::DUP4, + Instruction::ADD, + Instruction::SSTORE + }); +} + +BOOST_AUTO_TEST_CASE(cse_deep_stack) +{ + AssemblyItems input{ + Instruction::ADD, + Instruction::SWAP1, + Instruction::POP, + Instruction::SWAP8, + Instruction::POP, + Instruction::SWAP8, + Instruction::POP, + Instruction::SWAP8, + Instruction::SWAP5, + Instruction::POP, + Instruction::POP, + Instruction::POP, + Instruction::POP, + Instruction::POP, + }; + checkCSE(input, { + Instruction::SWAP4, + Instruction::SWAP12, + Instruction::SWAP3, + Instruction::SWAP11, + Instruction::POP, + Instruction::SWAP1, + Instruction::SWAP3, + Instruction::ADD, + Instruction::SWAP8, + Instruction::POP, + Instruction::SWAP6, + Instruction::POP, + Instruction::POP, + Instruction::POP, + Instruction::POP, + Instruction::POP, + Instruction::POP, + }); +} + +BOOST_AUTO_TEST_CASE(cse_jumpi_no_jump) +{ + AssemblyItems input{ + u256(0), + u256(1), + Instruction::DUP2, + AssemblyItem(PushTag, 1), + Instruction::JUMPI + }; + checkCSE(input, { + u256(0), + u256(1) + }); +} + +BOOST_AUTO_TEST_CASE(cse_jumpi_jump) +{ + AssemblyItems input{ + u256(1), + u256(1), + Instruction::DUP2, + AssemblyItem(PushTag, 1), + Instruction::JUMPI + }; + checkCSE(input, { + u256(1), + Instruction::DUP1, + AssemblyItem(PushTag, 1), + Instruction::JUMP + }); +} + +BOOST_AUTO_TEST_CASE(cse_empty_keccak256) +{ + AssemblyItems input{ + u256(0), + Instruction::DUP2, + Instruction::KECCAK256 + }; + checkCSE(input, { + u256(dev::keccak256(bytesConstRef())) + }); +} + +BOOST_AUTO_TEST_CASE(cse_partial_keccak256) +{ + AssemblyItems input{ + u256(0xabcd) << (256 - 16), + u256(0), + Instruction::MSTORE, + u256(2), + u256(0), + Instruction::KECCAK256 + }; + checkCSE(input, { + u256(0xabcd) << (256 - 16), + u256(0), + Instruction::MSTORE, + u256(dev::keccak256(bytes{0xab, 0xcd})) + }); +} + +BOOST_AUTO_TEST_CASE(cse_keccak256_twice_same_location) +{ + // Keccak-256 twice from same dynamic location + AssemblyItems input{ + Instruction::DUP2, + Instruction::DUP1, + Instruction::MSTORE, + u256(64), + Instruction::DUP2, + Instruction::KECCAK256, + u256(64), + Instruction::DUP3, + Instruction::KECCAK256 + }; + checkCSE(input, { + Instruction::DUP2, + Instruction::DUP1, + Instruction::MSTORE, + u256(64), + Instruction::DUP2, + Instruction::KECCAK256, + Instruction::DUP1 + }); +} + +BOOST_AUTO_TEST_CASE(cse_keccak256_twice_same_content) +{ + // Keccak-256 twice from different dynamic location but with same content + AssemblyItems input{ + Instruction::DUP1, + u256(0x80), + Instruction::MSTORE, // m[128] = DUP1 + u256(0x20), + u256(0x80), + Instruction::KECCAK256, // keccak256(m[128..(128+32)]) + Instruction::DUP2, + u256(12), + Instruction::MSTORE, // m[12] = DUP1 + u256(0x20), + u256(12), + Instruction::KECCAK256 // keccak256(m[12..(12+32)]) + }; + checkCSE(input, { + u256(0x80), + Instruction::DUP2, + Instruction::DUP2, + Instruction::MSTORE, + u256(0x20), + Instruction::SWAP1, + Instruction::KECCAK256, + u256(12), + Instruction::DUP3, + Instruction::SWAP1, + Instruction::MSTORE, + Instruction::DUP1 + }); +} + +BOOST_AUTO_TEST_CASE(cse_keccak256_twice_same_content_dynamic_store_in_between) +{ + // Keccak-256 twice from different dynamic location but with same content, + // dynamic mstore in between, which forces us to re-calculate the hash + AssemblyItems input{ + u256(0x80), + Instruction::DUP2, + Instruction::DUP2, + Instruction::MSTORE, // m[128] = DUP1 + u256(0x20), + Instruction::DUP1, + Instruction::DUP3, + Instruction::KECCAK256, // keccak256(m[128..(128+32)]) + u256(12), + Instruction::DUP5, + Instruction::DUP2, + Instruction::MSTORE, // m[12] = DUP1 + Instruction::DUP12, + Instruction::DUP14, + Instruction::MSTORE, // destroys memory knowledge + Instruction::SWAP2, + Instruction::SWAP1, + Instruction::SWAP2, + Instruction::KECCAK256 // keccak256(m[12..(12+32)]) + }; + checkCSE(input, input); +} + +BOOST_AUTO_TEST_CASE(cse_keccak256_twice_same_content_noninterfering_store_in_between) +{ + // Keccak-256 twice from different dynamic location but with same content, + // dynamic mstore in between, but does not force us to re-calculate the hash + AssemblyItems input{ + u256(0x80), + Instruction::DUP2, + Instruction::DUP2, + Instruction::MSTORE, // m[128] = DUP1 + u256(0x20), + Instruction::DUP1, + Instruction::DUP3, + Instruction::KECCAK256, // keccak256(m[128..(128+32)]) + u256(12), + Instruction::DUP5, + Instruction::DUP2, + Instruction::MSTORE, // m[12] = DUP1 + Instruction::DUP12, + u256(12 + 32), + Instruction::MSTORE, // does not destoy memory knowledge + Instruction::DUP13, + u256(128 - 32), + Instruction::MSTORE, // does not destoy memory knowledge + u256(0x20), + u256(12), + Instruction::KECCAK256 // keccak256(m[12..(12+32)]) + }; + // if this changes too often, only count the number of SHA3 and MSTORE instructions + AssemblyItems output = CSE(input); + BOOST_CHECK_EQUAL(4, count(output.begin(), output.end(), AssemblyItem(Instruction::MSTORE))); + BOOST_CHECK_EQUAL(1, count(output.begin(), output.end(), AssemblyItem(Instruction::KECCAK256))); +} + +BOOST_AUTO_TEST_CASE(cse_with_initially_known_stack) +{ + eth::KnownState state = createInitialState(AssemblyItems{ + u256(0x12), + u256(0x20), + Instruction::ADD + }); + AssemblyItems input{ + u256(0x12 + 0x20) + }; + checkCSE(input, AssemblyItems{Instruction::DUP1}, state); +} + +BOOST_AUTO_TEST_CASE(cse_equality_on_initially_known_stack) +{ + eth::KnownState state = createInitialState(AssemblyItems{Instruction::DUP1}); + AssemblyItems input{ + Instruction::EQ + }; + AssemblyItems output = CSE(input, state); + // check that it directly pushes 1 (true) + BOOST_CHECK(find(output.begin(), output.end(), AssemblyItem(u256(1))) != output.end()); +} + +BOOST_AUTO_TEST_CASE(cse_access_previous_sequence) +{ + // Tests that the code generator detects whether it tries to access SLOAD instructions + // from a sequenced expression which is not in its scope. + eth::KnownState state = createInitialState(AssemblyItems{ + u256(0), + Instruction::SLOAD, + u256(1), + Instruction::ADD, + u256(0), + Instruction::SSTORE + }); + // now stored: val_1 + 1 (value at sequence 1) + // if in the following instructions, the SLOAD cresolves to "val_1 + 1", + // this cannot be generated because we cannot load from sequence 1 anymore. + AssemblyItems input{ + u256(0), + Instruction::SLOAD, + }; + BOOST_CHECK_THROW(CSE(input, state), StackTooDeepException); + // @todo for now, this throws an exception, but it should recover to the following + // (or an even better version) at some point: + // 0, SLOAD, 1, ADD, SSTORE, 0 SLOAD +} + +BOOST_AUTO_TEST_CASE(cse_optimise_return) +{ + checkCSE( + AssemblyItems{u256(0), u256(7), Instruction::RETURN}, + AssemblyItems{Instruction::STOP} + ); +} + +BOOST_AUTO_TEST_CASE(control_flow_graph_remove_unused) +{ + // remove parts of the code that are unused + AssemblyItems input{ + AssemblyItem(PushTag, 1), + Instruction::JUMP, + u256(7), + AssemblyItem(Tag, 1), + }; + checkCFG(input, {}); +} + +BOOST_AUTO_TEST_CASE(control_flow_graph_remove_unused_loop) +{ + AssemblyItems input{ + AssemblyItem(PushTag, 3), + Instruction::JUMP, + AssemblyItem(Tag, 1), + u256(7), + AssemblyItem(PushTag, 2), + Instruction::JUMP, + AssemblyItem(Tag, 2), + u256(8), + AssemblyItem(PushTag, 1), + Instruction::JUMP, + AssemblyItem(Tag, 3), + u256(11) + }; + checkCFG(input, {u256(11)}); +} + +BOOST_AUTO_TEST_CASE(control_flow_graph_reconnect_single_jump_source) +{ + // move code that has only one unconditional jump source + AssemblyItems input{ + u256(1), + AssemblyItem(PushTag, 1), + Instruction::JUMP, + AssemblyItem(Tag, 2), + u256(2), + AssemblyItem(PushTag, 3), + Instruction::JUMP, + AssemblyItem(Tag, 1), + u256(3), + AssemblyItem(PushTag, 2), + Instruction::JUMP, + AssemblyItem(Tag, 3), + u256(4), + }; + checkCFG(input, {u256(1), u256(3), u256(2), u256(4)}); +} + +BOOST_AUTO_TEST_CASE(control_flow_graph_do_not_remove_returned_to) +{ + // do not remove parts that are "returned to" + AssemblyItems input{ + AssemblyItem(PushTag, 1), + AssemblyItem(PushTag, 2), + Instruction::JUMP, + AssemblyItem(Tag, 2), + Instruction::JUMP, + AssemblyItem(Tag, 1), + u256(2) + }; + checkCFG(input, {u256(2)}); +} + +BOOST_AUTO_TEST_CASE(block_deduplicator) +{ + AssemblyItems input{ + AssemblyItem(PushTag, 2), + AssemblyItem(PushTag, 1), + AssemblyItem(PushTag, 3), + u256(6), + Instruction::SWAP3, + Instruction::JUMP, + AssemblyItem(Tag, 1), + u256(6), + Instruction::SWAP3, + Instruction::JUMP, + AssemblyItem(Tag, 2), + u256(6), + Instruction::SWAP3, + Instruction::JUMP, + AssemblyItem(Tag, 3) + }; + BlockDeduplicator dedup(input); + dedup.deduplicate(); + + set<u256> pushTags; + for (AssemblyItem const& item: input) + if (item.type() == PushTag) + pushTags.insert(item.data()); + BOOST_CHECK_EQUAL(pushTags.size(), 2); +} + +BOOST_AUTO_TEST_CASE(block_deduplicator_loops) +{ + AssemblyItems input{ + u256(0), + Instruction::SLOAD, + AssemblyItem(PushTag, 1), + AssemblyItem(PushTag, 2), + Instruction::JUMPI, + Instruction::JUMP, + AssemblyItem(Tag, 1), + u256(5), + u256(6), + Instruction::SSTORE, + AssemblyItem(PushTag, 1), + Instruction::JUMP, + AssemblyItem(Tag, 2), + u256(5), + u256(6), + Instruction::SSTORE, + AssemblyItem(PushTag, 2), + 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_CASE(clear_unreachable_code) +{ + AssemblyItems items{ + AssemblyItem(PushTag, 1), + Instruction::JUMP, + u256(0), + Instruction::SLOAD, + AssemblyItem(Tag, 2), + u256(5), + u256(6), + Instruction::SSTORE, + AssemblyItem(PushTag, 1), + Instruction::JUMP, + u256(5), + u256(6) + }; + AssemblyItems expectation{ + AssemblyItem(PushTag, 1), + Instruction::JUMP, + AssemblyItem(Tag, 2), + u256(5), + u256(6), + Instruction::SSTORE, + AssemblyItem(PushTag, 1), + Instruction::JUMP + }; + PeepholeOptimiser peepOpt(items); + BOOST_REQUIRE(peepOpt.optimise()); + BOOST_CHECK_EQUAL_COLLECTIONS( + items.begin(), items.end(), + expectation.begin(), expectation.end() + ); +} + +BOOST_AUTO_TEST_CASE(peephole_double_push) +{ + AssemblyItems items{ + u256(0), + u256(0), + u256(5), + u256(5), + u256(4), + u256(5) + }; + AssemblyItems expectation{ + u256(0), + Instruction::DUP1, + u256(5), + Instruction::DUP1, + u256(4), + u256(5) + }; + PeepholeOptimiser peepOpt(items); + BOOST_REQUIRE(peepOpt.optimise()); + BOOST_CHECK_EQUAL_COLLECTIONS( + items.begin(), items.end(), + expectation.begin(), expectation.end() + ); +} + +BOOST_AUTO_TEST_CASE(cse_sub_zero) +{ + checkCSE({ + u256(0), + Instruction::DUP2, + Instruction::SUB + }, { + Instruction::DUP1 + }); + + checkCSE({ + Instruction::DUP1, + u256(0), + Instruction::SUB + }, { + u256(0), + Instruction::DUP2, + Instruction::SWAP1, + Instruction::SUB + }); +} + + +BOOST_AUTO_TEST_SUITE_END() + +} +} +} // end namespaces diff --git a/test/libjulia/Parser.cpp b/test/libjulia/Parser.cpp index fa7c45ed..dd6f3d94 100644 --- a/test/libjulia/Parser.cpp +++ b/test/libjulia/Parser.cpp @@ -131,6 +131,11 @@ BOOST_AUTO_TEST_CASE(vardecl_bool) BOOST_CHECK(successParse("{ let x:bool := false:bool }")); } +BOOST_AUTO_TEST_CASE(vardecl_empty) +{ + BOOST_CHECK(successParse("{ let x:u256 }")); +} + BOOST_AUTO_TEST_CASE(assignment) { BOOST_CHECK(successParse("{ let x:u256 := 2:u256 let y:u256 := x }")); diff --git a/test/liblll/EndToEndTest.cpp b/test/liblll/EndToEndTest.cpp index f3bfb438..9292d963 100644 --- a/test/liblll/EndToEndTest.cpp +++ b/test/liblll/EndToEndTest.cpp @@ -165,6 +165,56 @@ BOOST_AUTO_TEST_CASE(conditional_seq) BOOST_CHECK(callFallback() == toBigEndian(u256(1))); } +BOOST_AUTO_TEST_CASE(conditional_nested_else) +{ + char const* sourceCode = R"( + (returnlll + (seq + (def 'input (calldataload 0x04)) + ;; Calculates width in bytes of utf-8 characters. + (return + (if (< input 0x80) 1 + (if (< input 0xE0) 2 + (if (< input 0xF0) 3 + (if (< input 0xF8) 4 + (if (< input 0xFC) 5 + 6)))))))) + + )"; + compileAndRun(sourceCode); + BOOST_CHECK(callContractFunction("test()", 0x00) == encodeArgs(u256(1))); + BOOST_CHECK(callContractFunction("test()", 0x80) == encodeArgs(u256(2))); + BOOST_CHECK(callContractFunction("test()", 0xe0) == encodeArgs(u256(3))); + BOOST_CHECK(callContractFunction("test()", 0xf0) == encodeArgs(u256(4))); + BOOST_CHECK(callContractFunction("test()", 0xf8) == encodeArgs(u256(5))); + BOOST_CHECK(callContractFunction("test()", 0xfc) == encodeArgs(u256(6))); +} + +BOOST_AUTO_TEST_CASE(conditional_nested_then) +{ + char const* sourceCode = R"( + (returnlll + (seq + (def 'input (calldataload 0x04)) + ;; Calculates width in bytes of utf-8 characters. + (return + (if (>= input 0x80) + (if (>= input 0xE0) + (if (>= input 0xF0) + (if (>= input 0xF8) + (if (>= input 0xFC) + 6 5) 4) 3) 2) 1)))) + + )"; + compileAndRun(sourceCode); + BOOST_CHECK(callContractFunction("test()", 0x00) == encodeArgs(u256(1))); + BOOST_CHECK(callContractFunction("test()", 0x80) == encodeArgs(u256(2))); + BOOST_CHECK(callContractFunction("test()", 0xe0) == encodeArgs(u256(3))); + BOOST_CHECK(callContractFunction("test()", 0xf0) == encodeArgs(u256(4))); + BOOST_CHECK(callContractFunction("test()", 0xf8) == encodeArgs(u256(5))); + BOOST_CHECK(callContractFunction("test()", 0xfc) == encodeArgs(u256(6))); +} + BOOST_AUTO_TEST_CASE(exp_operator_const) { char const* sourceCode = R"( @@ -387,6 +437,37 @@ BOOST_AUTO_TEST_CASE(assembly_codecopy) BOOST_CHECK(callFallback() == encodeArgs(string("abcdef"))); } +BOOST_AUTO_TEST_CASE(for_loop) +{ + char const* sourceCode = R"( + (returnlll + (seq + (for + { (set 'i 1) (set 'j 1) } ; INIT + (<= @i 10) ; PRED + [i]:(+ @i 1) ; POST + [j]:(* @j @i)) ; BODY + (return j 0x20))) + )"; + compileAndRun(sourceCode); + BOOST_CHECK(callFallback() == encodeArgs(u256(3628800))); // 10! +} + +BOOST_AUTO_TEST_CASE(while_loop) +{ + char const* sourceCode = R"( + (returnlll + (seq + ;; Euclid's GCD algorithm + (set 'a 1071) + (set 'b 462) + (while @b + [a]:(raw @b [b]:(mod @a @b))) + (return a 0x20))) + )"; + compileAndRun(sourceCode); + BOOST_CHECK(callFallback() == encodeArgs(u256(21))); // GCD(1071,462) +} BOOST_AUTO_TEST_CASE(keccak256_32bytes) { @@ -436,6 +517,61 @@ BOOST_AUTO_TEST_CASE(send_three_args) BOOST_CHECK(balanceAt(Address(0xdead)) == 42); } +// Regression test for edge case that previously failed +BOOST_AUTO_TEST_CASE(alloc_zero) +{ + char const* sourceCode = R"( + (returnlll + (seq + (mstore 0x00 (~ 0)) + (alloc 0) + (return 0x00 0x20))) + )"; + compileAndRun(sourceCode); + BOOST_CHECK(callFallback() == encodeArgs(u256(-1))); +} + +BOOST_AUTO_TEST_CASE(alloc_size) +{ + char const* sourceCode = R"( + (returnlll + (seq + (mstore 0x00 0) ; reserve space for the result of the alloc + (mstore 0x00 (alloc (calldataload 0x04))) + (return (- (msize) (mload 0x00))))) + )"; + compileAndRun(sourceCode); + BOOST_CHECK(callContractFunction("test()", 0) == encodeArgs(u256(0))); + BOOST_CHECK(callContractFunction("test()", 1) == encodeArgs(u256(32))); + BOOST_CHECK(callContractFunction("test()", 32) == encodeArgs(u256(32))); + BOOST_CHECK(callContractFunction("test()", 33) == encodeArgs(u256(64))); +} + +BOOST_AUTO_TEST_CASE(alloc_start) +{ + char const* sourceCode = R"( + (returnlll + (seq + (mstore 0x40 0) ; Set initial MSIZE to 0x60 + (return (alloc 1)))) + )"; + compileAndRun(sourceCode); + BOOST_CHECK(callFallback() == encodeArgs(96)); +} + +BOOST_AUTO_TEST_CASE(alloc_with_variable) +{ + char const* sourceCode = R"( + (returnlll + (seq + (set 'x (alloc 1)) + (mstore8 @x 42) ; ASCII '*' + (return @x 0x20))) + )"; + compileAndRun(sourceCode); + BOOST_CHECK(callFallback() == encodeArgs("*")); +} + BOOST_AUTO_TEST_CASE(msg_six_args) { char const* sourceCode = R"( diff --git a/test/libsolidity/ErrorCheck.cpp b/test/libsolidity/ErrorCheck.cpp index 9b0f9fb7..b1e94061 100644 --- a/test/libsolidity/ErrorCheck.cpp +++ b/test/libsolidity/ErrorCheck.cpp @@ -28,11 +28,11 @@ using namespace std; bool dev::solidity::searchErrorMessage(Error const& _err, std::string const& _substr) { - if (string const* errorMessage = boost::get_error_info<dev::errinfo_comment>(_err)) + if (string const* errorMessage = _err.comment()) { if (errorMessage->find(_substr) == std::string::npos) { - cout << "Expected message \"" << _substr << "\" but found" << *errorMessage << endl; + cout << "Expected message \"" << _substr << "\" but found \"" << *errorMessage << "\".\n"; return false; } return true; diff --git a/test/libsolidity/GasMeter.cpp b/test/libsolidity/GasMeter.cpp index ef560b12..df9afaae 100644 --- a/test/libsolidity/GasMeter.cpp +++ b/test/libsolidity/GasMeter.cpp @@ -47,7 +47,9 @@ public: GasMeterTestFramework() { } void compile(string const& _sourceCode) { - m_compiler.setSource("pragma solidity >= 0.0;" + _sourceCode); + m_compiler.reset(false); + m_compiler.addSource("", "pragma solidity >=0.0;\n" + _sourceCode); + m_compiler.setOptimiserSettings(dev::test::Options::get().optimize); ETH_TEST_REQUIRE_NO_THROW(m_compiler.compile(), "Compiling contract failed"); AssemblyItems const* items = m_compiler.runtimeAssemblyItems(""); diff --git a/test/libsolidity/Imports.cpp b/test/libsolidity/Imports.cpp index 6aa96fb8..03287b28 100644 --- a/test/libsolidity/Imports.cpp +++ b/test/libsolidity/Imports.cpp @@ -20,11 +20,15 @@ * Tests for high level features like import. */ -#include <string> -#include <boost/test/unit_test.hpp> +#include <test/libsolidity/ErrorCheck.h> + #include <libsolidity/interface/Exceptions.h> #include <libsolidity/interface/CompilerStack.h> +#include <boost/test/unit_test.hpp> + +#include <string> + using namespace std; namespace dev @@ -202,6 +206,68 @@ BOOST_AUTO_TEST_CASE(context_dependent_remappings_order_independent) BOOST_CHECK(d.compile()); } +BOOST_AUTO_TEST_CASE(shadowing_via_import) +{ + CompilerStack c; + c.addSource("a", "library A {} pragma solidity >=0.0;"); + c.addSource("b", "library A {} pragma solidity >=0.0;"); + c.addSource("c", "import {A} from \"./a\"; import {A} from \"./b\";"); + BOOST_CHECK(!c.compile()); +} + +BOOST_AUTO_TEST_CASE(shadowing_builtins_with_imports) +{ + CompilerStack c; + c.addSource("B.sol", "contract X {} pragma solidity >=0.0;"); + c.addSource("b", R"( + pragma solidity >=0.0; + import * as msg from "B.sol"; + contract C { + } + )"); + BOOST_CHECK(c.compile()); + size_t errorCount = 0; + for (auto const& e: c.errors()) + { + string const* msg = e->comment(); + BOOST_REQUIRE(msg); + if (msg->find("pre-release") != string::npos) + continue; + BOOST_CHECK( + msg->find("shadows a builtin symbol") != string::npos + ); + errorCount++; + } + BOOST_CHECK_EQUAL(errorCount, 1); +} + +BOOST_AUTO_TEST_CASE(shadowing_builtins_with_multiple_imports) +{ + CompilerStack c; + c.addSource("B.sol", "contract msg {} contract block{} pragma solidity >=0.0;"); + c.addSource("b", R"( + pragma solidity >=0.0; + import {msg, block} from "B.sol"; + contract C { + } + )"); + BOOST_CHECK(c.compile()); + auto numErrors = c.errors().size(); + // Sometimes we get the prerelease warning, sometimes not. + BOOST_CHECK(4 <= numErrors && numErrors <= 5); + for (auto const& e: c.errors()) + { + string const* msg = e->comment(); + BOOST_REQUIRE(msg); + BOOST_CHECK( + msg->find("pre-release") != string::npos || + msg->find("shadows a builtin symbol") != string::npos + ); + } +} + + + BOOST_AUTO_TEST_SUITE_END() } diff --git a/test/libsolidity/InlineAssembly.cpp b/test/libsolidity/InlineAssembly.cpp index 5197f649..4bf4eb48 100644 --- a/test/libsolidity/InlineAssembly.cpp +++ b/test/libsolidity/InlineAssembly.cpp @@ -195,6 +195,11 @@ BOOST_AUTO_TEST_CASE(vardecl_bool) CHECK_PARSE_ERROR("{ let x := false }", ParserError, "True and false are not valid literals."); } +BOOST_AUTO_TEST_CASE(vardecl_empty) +{ + BOOST_CHECK(successParse("{ let x }")); +} + BOOST_AUTO_TEST_CASE(assignment) { BOOST_CHECK(successParse("{ let x := 2 7 8 add =: x }")); diff --git a/test/libsolidity/JSONCompiler.cpp b/test/libsolidity/JSONCompiler.cpp index aa690f0b..536ba730 100644 --- a/test/libsolidity/JSONCompiler.cpp +++ b/test/libsolidity/JSONCompiler.cpp @@ -24,6 +24,7 @@ #include <regex> #include <boost/test/unit_test.hpp> #include <libdevcore/JSON.h> +#include <libsolidity/interface/Version.h> #include "../Metadata.h" #include "../TestHelper.h" @@ -32,7 +33,12 @@ using namespace std; extern "C" { +extern char const* version(); +extern char const* license(); +extern char const* compileJSON(char const* _input, bool _optimize); extern char const* compileJSONMulti(char const* _input, bool _optimize); +extern char const* compileJSONCallback(char const* _input, bool _optimize, void* _readCallback); +extern char const* compileStandard(char const* _input, void* _readCallback); } namespace dev @@ -45,9 +51,29 @@ namespace test namespace { +Json::Value compileSingle(string const& _input) +{ + string output(compileJSON(_input.c_str(), dev::test::Options::get().optimize)); + Json::Value ret; + BOOST_REQUIRE(Json::Reader().parse(output, ret, false)); + return ret; +} + +Json::Value compileMulti(string const& _input, bool _callback) +{ + string output( + _callback ? + compileJSONCallback(_input.c_str(), dev::test::Options::get().optimize, NULL) : + compileJSONMulti(_input.c_str(), dev::test::Options::get().optimize) + ); + Json::Value ret; + BOOST_REQUIRE(Json::Reader().parse(output, ret, false)); + return ret; +} + Json::Value compile(string const& _input) { - string output(compileJSONMulti(_input.c_str(), dev::test::Options::get().optimize)); + string output(compileStandard(_input.c_str(), NULL)); Json::Value ret; BOOST_REQUIRE(Json::Reader().parse(output, ret, false)); return ret; @@ -57,6 +83,18 @@ Json::Value compile(string const& _input) BOOST_AUTO_TEST_SUITE(JSONCompiler) +BOOST_AUTO_TEST_CASE(read_version) +{ + string output(version()); + BOOST_CHECK(output.find(VersionString) == 0); +} + +BOOST_AUTO_TEST_CASE(read_license) +{ + string output(license()); + BOOST_CHECK(output.find("GNU GENERAL PUBLIC LICENSE") != string::npos); +} + BOOST_AUTO_TEST_CASE(basic_compilation) { char const* input = R"( @@ -66,8 +104,15 @@ BOOST_AUTO_TEST_CASE(basic_compilation) } } )"; - Json::Value result = compile(input); + Json::Value result = compileMulti(input, false); BOOST_CHECK(result.isObject()); + + // Compare with compileJSONCallback + BOOST_CHECK_EQUAL( + dev::jsonCompactPrint(result), + dev::jsonCompactPrint(compileMulti(input, true)) + ); + BOOST_CHECK(result["contracts"].isObject()); BOOST_CHECK(result["contracts"]["fileA:A"].isObject()); Json::Value contract = result["contracts"]["fileA:A"]; @@ -104,6 +149,69 @@ BOOST_AUTO_TEST_CASE(basic_compilation) "\"src\":\"0:14:0\"}],\"id\":2,\"name\":\"SourceUnit\",\"src\":\"0:14:0\"}" ); } + +BOOST_AUTO_TEST_CASE(single_compilation) +{ + Json::Value result = compileSingle("contract A { }"); + BOOST_CHECK(result.isObject()); + + BOOST_CHECK(result["contracts"].isObject()); + BOOST_CHECK(result["contracts"][":A"].isObject()); + Json::Value contract = result["contracts"][":A"]; + BOOST_CHECK(contract.isObject()); + BOOST_CHECK(contract["interface"].isString()); + BOOST_CHECK_EQUAL(contract["interface"].asString(), "[]"); + BOOST_CHECK(contract["bytecode"].isString()); + BOOST_CHECK_EQUAL( + dev::test::bytecodeSansMetadata(contract["bytecode"].asString()), + "60606040523415600e57600080fd5b5b603680601c6000396000f30060606040525b600080fd00" + ); + BOOST_CHECK(contract["runtimeBytecode"].isString()); + BOOST_CHECK_EQUAL( + dev::test::bytecodeSansMetadata(contract["runtimeBytecode"].asString()), + "60606040525b600080fd00" + ); + BOOST_CHECK(contract["functionHashes"].isObject()); + BOOST_CHECK(contract["gasEstimates"].isObject()); + BOOST_CHECK_EQUAL( + dev::jsonCompactPrint(contract["gasEstimates"]), + "{\"creation\":[62,10800],\"external\":{},\"internal\":{}}" + ); + BOOST_CHECK(contract["metadata"].isString()); + BOOST_CHECK(dev::test::isValidMetadata(contract["metadata"].asString())); + BOOST_CHECK(result["sources"].isObject()); + BOOST_CHECK(result["sources"][""].isObject()); + BOOST_CHECK(result["sources"][""]["AST"].isObject()); + BOOST_CHECK_EQUAL( + dev::jsonCompactPrint(result["sources"][""]["AST"]), + "{\"attributes\":{\"absolutePath\":\"\",\"exportedSymbols\":{\"A\":[1]}}," + "\"children\":[{\"attributes\":{\"baseContracts\":[null],\"contractDependencies\":[null]," + "\"contractKind\":\"contract\",\"documentation\":null,\"fullyImplemented\":true,\"linearizedBaseContracts\":[1]," + "\"name\":\"A\",\"nodes\":[null],\"scope\":2},\"id\":1,\"name\":\"ContractDefinition\"," + "\"src\":\"0:14:0\"}],\"id\":2,\"name\":\"SourceUnit\",\"src\":\"0:14:0\"}" + ); +} + +BOOST_AUTO_TEST_CASE(standard_compilation) +{ + char const* input = R"( + { + "language": "Solidity", + "sources": { + "fileA": { + "content": "contract A { }" + } + } + } + )"; + Json::Value result = compile(input); + BOOST_CHECK(result.isObject()); + + // Only tests some assumptions. The StandardCompiler is tested properly in another suite. + BOOST_CHECK(result.isMember("sources")); + BOOST_CHECK(result.isMember("contracts")); +} + BOOST_AUTO_TEST_SUITE_END() } diff --git a/test/libsolidity/Metadata.cpp b/test/libsolidity/Metadata.cpp index 60bb2e4e..0d3caddd 100644 --- a/test/libsolidity/Metadata.cpp +++ b/test/libsolidity/Metadata.cpp @@ -43,9 +43,11 @@ BOOST_AUTO_TEST_CASE(metadata_stamp) } )"; CompilerStack compilerStack; - BOOST_REQUIRE(compilerStack.compile(std::string(sourceCode))); + compilerStack.addSource("", std::string(sourceCode)); + compilerStack.setOptimiserSettings(dev::test::Options::get().optimize); + ETH_TEST_REQUIRE_NO_THROW(compilerStack.compile(), "Compiling contract failed"); bytes const& bytecode = compilerStack.runtimeObject("test").bytecode; - std::string const& metadata = compilerStack.onChainMetadata("test"); + std::string const& metadata = compilerStack.metadata("test"); BOOST_CHECK(dev::test::isValidMetadata(metadata)); bytes hash = dev::swarmHash(metadata).asBytes(); BOOST_REQUIRE(hash.size() == 32); @@ -56,6 +58,75 @@ BOOST_AUTO_TEST_CASE(metadata_stamp) BOOST_CHECK(std::equal(expectation.begin(), expectation.end(), bytecode.end() - metadataCBORSize - 2)); } +BOOST_AUTO_TEST_CASE(metadata_relevant_sources) +{ + CompilerStack compilerStack; + char const* sourceCode = R"( + pragma solidity >=0.0; + contract A { + function g(function(uint) external returns (uint) x) {} + } + )"; + compilerStack.addSource("A", std::string(sourceCode)); + sourceCode = R"( + pragma solidity >=0.0; + contract B { + function g(function(uint) external returns (uint) x) {} + } + )"; + compilerStack.addSource("B", std::string(sourceCode)); + compilerStack.setOptimiserSettings(dev::test::Options::get().optimize); + ETH_TEST_REQUIRE_NO_THROW(compilerStack.compile(), "Compiling contract failed"); + + std::string const& serialisedMetadata = compilerStack.metadata("A"); + BOOST_CHECK(dev::test::isValidMetadata(serialisedMetadata)); + Json::Value metadata; + BOOST_REQUIRE(Json::Reader().parse(serialisedMetadata, metadata, false)); + + BOOST_CHECK_EQUAL(metadata["sources"].size(), 1); + BOOST_CHECK(metadata["sources"].isMember("A")); +} + +BOOST_AUTO_TEST_CASE(metadata_relevant_sources_imports) +{ + CompilerStack compilerStack; + char const* sourceCode = R"( + pragma solidity >=0.0; + contract A { + function g(function(uint) external returns (uint) x) {} + } + )"; + compilerStack.addSource("A", std::string(sourceCode)); + sourceCode = R"( + pragma solidity >=0.0; + import "./A"; + contract B is A { + function g(function(uint) external returns (uint) x) {} + } + )"; + compilerStack.addSource("B", std::string(sourceCode)); + sourceCode = R"( + pragma solidity >=0.0; + import "./B"; + contract C is B { + function g(function(uint) external returns (uint) x) {} + } + )"; + compilerStack.addSource("C", std::string(sourceCode)); + compilerStack.setOptimiserSettings(dev::test::Options::get().optimize); + ETH_TEST_REQUIRE_NO_THROW(compilerStack.compile(), "Compiling contract failed"); + + std::string const& serialisedMetadata = compilerStack.metadata("C"); + BOOST_CHECK(dev::test::isValidMetadata(serialisedMetadata)); + Json::Value metadata; + BOOST_REQUIRE(Json::Reader().parse(serialisedMetadata, metadata, false)); + + BOOST_CHECK_EQUAL(metadata["sources"].size(), 3); + BOOST_CHECK(metadata["sources"].isMember("A")); + BOOST_CHECK(metadata["sources"].isMember("B")); + BOOST_CHECK(metadata["sources"].isMember("C")); +} + BOOST_AUTO_TEST_SUITE_END() } diff --git a/test/libsolidity/SolidityABIJSON.cpp b/test/libsolidity/SolidityABIJSON.cpp index f87390e1..452a2662 100644 --- a/test/libsolidity/SolidityABIJSON.cpp +++ b/test/libsolidity/SolidityABIJSON.cpp @@ -42,7 +42,9 @@ public: void checkInterface(std::string const& _code, std::string const& _expectedInterfaceString) { - ETH_TEST_REQUIRE_NO_THROW(m_compilerStack.parseAndAnalyze("pragma solidity >=0.0;\n" + _code), "Parsing contract failed"); + m_compilerStack.reset(false); + m_compilerStack.addSource("", "pragma solidity >=0.0;\n" + _code); + ETH_TEST_REQUIRE_NO_THROW(m_compilerStack.parseAndAnalyze(), "Parsing contract failed"); Json::Value generatedInterface = m_compilerStack.contractABI(""); Json::Value expectedInterface; diff --git a/test/libsolidity/SolidityEndToEndTest.cpp b/test/libsolidity/SolidityEndToEndTest.cpp index c9771fbd..db7f59ee 100644 --- a/test/libsolidity/SolidityEndToEndTest.cpp +++ b/test/libsolidity/SolidityEndToEndTest.cpp @@ -2696,6 +2696,34 @@ BOOST_AUTO_TEST_CASE(function_modifier_for_constructor) BOOST_CHECK(callContractFunction("getData()") == encodeArgs(4 | 2)); } +BOOST_AUTO_TEST_CASE(function_modifier_multiple_times) +{ + char const* sourceCode = R"( + contract C { + uint public a; + modifier mod(uint x) { a += x; _; } + function f(uint x) mod(2) mod(5) mod(x) returns(uint) { return a; } + } + )"; + compileAndRun(sourceCode); + BOOST_CHECK(callContractFunction("f(uint256)", u256(3)) == encodeArgs(2 + 5 + 3)); + BOOST_CHECK(callContractFunction("a()") == encodeArgs(2 + 5 + 3)); +} + +BOOST_AUTO_TEST_CASE(function_modifier_multiple_times_local_vars) +{ + char const* sourceCode = R"( + contract C { + uint public a; + modifier mod(uint x) { uint b = x; a += b; _; a -= b; assert(b == x); } + function f(uint x) mod(2) mod(5) mod(x) returns(uint) { return a; } + } + )"; + compileAndRun(sourceCode); + BOOST_CHECK(callContractFunction("f(uint256)", u256(3)) == encodeArgs(2 + 5 + 3)); + BOOST_CHECK(callContractFunction("a()") == encodeArgs(0)); +} + BOOST_AUTO_TEST_CASE(crazy_elementary_typenames_on_stack) { char const* sourceCode = R"( @@ -8223,6 +8251,53 @@ BOOST_AUTO_TEST_CASE(failing_ecrecover_invalid_input) BOOST_CHECK(callContractFunction("f()") == encodeArgs(u256(0))); } +BOOST_AUTO_TEST_CASE(failing_ecrecover_invalid_input_proper) +{ + char const* sourceCode = R"( + contract C { + function f() returns (address) { + return recover( + 0x77e5189111eb6557e8a637b27ef8fbb15bc61d61c2f00cc48878f3a296e5e0ca, + 0, // invalid v value + 0x6944c77849b18048f6abe0db8084b0d0d0689cdddb53d2671c36967b58691ad4, + 0xef4f06ba4f78319baafd0424365777241af4dfd3da840471b4b4b087b7750d0d, + 0xca35b7d915458ef540ade6068dfe2f44e8fa733c, + 0xca35b7d915458ef540ade6068dfe2f44e8fa733c + ); + } + function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s, uint blockExpired, bytes32 salt) + returns (address) + { + require(hash == keccak256(blockExpired, salt)); + return ecrecover(hash, v, r, s); + } + } + )"; + compileAndRun(sourceCode, 0, "C"); + BOOST_CHECK(callContractFunction("f()") == encodeArgs(u256(0))); +} + +BOOST_AUTO_TEST_CASE(failing_ecrecover_invalid_input_asm) +{ + char const* sourceCode = R"( + contract C { + function f() returns (address) { + assembly { + mstore(mload(0x40), 0xca35b7d915458ef540ade6068dfe2f44e8fa733c) + } + return ecrecover( + 0x77e5189111eb6557e8a637b27ef8fbb15bc61d61c2f00cc48878f3a296e5e0ca, + 0, // invalid v value + 0x6944c77849b18048f6abe0db8084b0d0d0689cdddb53d2671c36967b58691ad4, + 0xef4f06ba4f78319baafd0424365777241af4dfd3da840471b4b4b087b7750d0d + ); + } + } + )"; + compileAndRun(sourceCode, 0, "C"); + BOOST_CHECK(callContractFunction("f()") == encodeArgs(u256(0))); +} + BOOST_AUTO_TEST_CASE(calling_nonexisting_contract_throws) { char const* sourceCode = R"( @@ -9622,7 +9697,7 @@ BOOST_AUTO_TEST_CASE(scientific_notation) BOOST_CHECK(callContractFunction("k()") == encodeArgs(u256(-25))); } -BOOST_AUTO_TEST_CASE(interface) +BOOST_AUTO_TEST_CASE(interface_contract) { char const* sourceCode = R"( interface I { @@ -9723,6 +9798,24 @@ BOOST_AUTO_TEST_CASE(multi_modifiers) BOOST_CHECK(callContractFunction("x()") == encodeArgs(u256(12))); } +BOOST_AUTO_TEST_CASE(inlineasm_empty_let) +{ + char const* sourceCode = R"( + contract C { + function f() returns (uint a, uint b) { + assembly { + let x + let y, z + a := x + b := z + } + } + } + )"; + compileAndRun(sourceCode, 0, "C"); + BOOST_CHECK(callContractFunction("f()") == encodeArgs(u256(0), u256(0))); +} + BOOST_AUTO_TEST_SUITE_END() } diff --git a/test/libsolidity/SolidityExecutionFramework.h b/test/libsolidity/SolidityExecutionFramework.h index 03e3a881..a8e58c25 100644 --- a/test/libsolidity/SolidityExecutionFramework.h +++ b/test/libsolidity/SolidityExecutionFramework.h @@ -56,7 +56,9 @@ public: std::string sourceCode = "pragma solidity >=0.0;\n" + _sourceCode; m_compiler.reset(false); m_compiler.addSource("", sourceCode); - if (!m_compiler.compile(m_optimize, m_optimizeRuns, _libraryAddresses)) + m_compiler.setLibraries(_libraryAddresses); + m_compiler.setOptimiserSettings(m_optimize, m_optimizeRuns); + if (!m_compiler.compile()) { for (auto const& error: m_compiler.errors()) SourceReferenceFormatter::printExceptionInformation( diff --git a/test/libsolidity/SolidityNameAndTypeResolution.cpp b/test/libsolidity/SolidityNameAndTypeResolution.cpp index 108128f7..cd922cc8 100644 --- a/test/libsolidity/SolidityNameAndTypeResolution.cpp +++ b/test/libsolidity/SolidityNameAndTypeResolution.cpp @@ -112,7 +112,14 @@ parseAnalyseAndReturnError(string const& _source, bool _reportWarnings = false, ) { if (error && !_allowMultipleErrors) - BOOST_FAIL("Multiple errors found"); + { + string message("Multiple errors found: "); + for (auto const& e: errorReporter.errors()) + if (string const* description = boost::get_error_info<errinfo_comment>(*e)) + message += *description + ", "; + + BOOST_FAIL(message); + } if (!error) error = currentError; } @@ -1108,7 +1115,7 @@ BOOST_AUTO_TEST_CASE(function_modifier_double_invocation) modifier mod(uint a) { if (a > 0) _; } } )"; - CHECK_ERROR(text, DeclarationError, "Modifier already used for this function"); + success(text); } BOOST_AUTO_TEST_CASE(base_constructor_double_invocation) @@ -2283,6 +2290,9 @@ BOOST_AUTO_TEST_CASE(test_fromElementaryTypeName) BOOST_CHECK(*Type::fromElementaryTypeName(ElementaryTypeNameToken(Token::BytesM, 30, 0)) == *make_shared<FixedBytesType>(30)); BOOST_CHECK(*Type::fromElementaryTypeName(ElementaryTypeNameToken(Token::BytesM, 31, 0)) == *make_shared<FixedBytesType>(31)); BOOST_CHECK(*Type::fromElementaryTypeName(ElementaryTypeNameToken(Token::BytesM, 32, 0)) == *make_shared<FixedBytesType>(32)); + + BOOST_CHECK(*Type::fromElementaryTypeName(ElementaryTypeNameToken(Token::Fixed, 0, 0)) == *make_shared<FixedPointType>(128, 19, FixedPointType::Modifier::Signed)); + BOOST_CHECK(*Type::fromElementaryTypeName(ElementaryTypeNameToken(Token::UFixed, 0, 0)) == *make_shared<FixedPointType>(128, 19, FixedPointType::Modifier::Unsigned)); } BOOST_AUTO_TEST_CASE(test_byte_is_alias_of_byte1) @@ -4026,7 +4036,7 @@ BOOST_AUTO_TEST_CASE(invalid_fixed_types_0x7_mxn) fixed0x7 a = .3; } )"; - BOOST_CHECK(!success(text)); + CHECK_ERROR(text, DeclarationError, "Identifier not found"); } BOOST_AUTO_TEST_CASE(invalid_fixed_types_long_invalid_identifier) @@ -4036,7 +4046,7 @@ BOOST_AUTO_TEST_CASE(invalid_fixed_types_long_invalid_identifier) fixed99999999999999999999999999999999999999x7 b = 9.5; } )"; - BOOST_CHECK(!success(text)); + CHECK_ERROR(text, DeclarationError, "Identifier not found"); } BOOST_AUTO_TEST_CASE(invalid_fixed_types_7x8_mxn) @@ -4046,7 +4056,7 @@ BOOST_AUTO_TEST_CASE(invalid_fixed_types_7x8_mxn) fixed7x8 c = 3.12345678; } )"; - BOOST_CHECK(!success(text)); + CHECK_ERROR(text, DeclarationError, "Identifier not found"); } BOOST_AUTO_TEST_CASE(library_instances_cannot_be_used) @@ -4060,7 +4070,7 @@ BOOST_AUTO_TEST_CASE(library_instances_cannot_be_used) } } )"; - BOOST_CHECK(!success(text)); + CHECK_ERROR(text, TypeError, "Member \"l\" not found or not visible after argument-dependent lookup in library L"); } BOOST_AUTO_TEST_CASE(invalid_fixed_type_long) @@ -4072,7 +4082,7 @@ BOOST_AUTO_TEST_CASE(invalid_fixed_type_long) } } )"; - BOOST_CHECK(!success(text)); + CHECK_ERROR(text, DeclarationError, "Identifier not found"); } BOOST_AUTO_TEST_CASE(fixed_type_int_conversion) @@ -4080,8 +4090,8 @@ BOOST_AUTO_TEST_CASE(fixed_type_int_conversion) char const* text = R"( contract test { function f() { - uint128 a = 3; - int128 b = 4; + uint64 a = 3; + int64 b = 4; fixed c = b; ufixed d = a; c; d; @@ -4130,7 +4140,7 @@ BOOST_AUTO_TEST_CASE(invalid_int_implicit_conversion_from_fixed) } } )"; - BOOST_CHECK(!success(text)); + CHECK_ERROR(text, TypeError, "Type fixed128x19 is not implicitly convertible to expected type int256"); } BOOST_AUTO_TEST_CASE(rational_unary_operation) @@ -4138,10 +4148,9 @@ BOOST_AUTO_TEST_CASE(rational_unary_operation) char const* text = R"( contract test { function f() { - ufixed8x16 a = 3.25; - fixed8x16 b = -3.25; - a; - b; + ufixed16x2 a = 3.25; + fixed16x2 b = -3.25; + a; b; } } )"; @@ -4149,13 +4158,13 @@ BOOST_AUTO_TEST_CASE(rational_unary_operation) text = R"( contract test { function f() { - ufixed8x16 a = +3.25; - fixed8x16 b = -3.25; + ufixed16x2 a = +3.25; + fixed16x2 b = -3.25; a; b; } } )"; - CHECK_WARNING(text,"Use of unary + is deprecated"); + CHECK_WARNING(text, "Use of unary + is deprecated"); text = R"( contract test { function f(uint x) { @@ -4172,10 +4181,10 @@ BOOST_AUTO_TEST_CASE(leading_zero_rationals_convert) char const* text = R"( contract A { function f() { - ufixed0x8 a = 0.5; - ufixed0x56 b = 0.0000000000000006661338147750939242541790008544921875; - fixed0x8 c = -0.5; - fixed0x56 d = -0.0000000000000006661338147750939242541790008544921875; + ufixed16x2 a = 0.5; + ufixed256x52 b = 0.0000000000000006661338147750939242541790008544921875; + fixed16x2 c = -0.5; + fixed256x52 d = -0.0000000000000006661338147750939242541790008544921875; a; b; c; d; } } @@ -4188,12 +4197,12 @@ BOOST_AUTO_TEST_CASE(size_capabilities_of_fixed_point_types) char const* text = R"( contract test { function f() { - ufixed248x8 a = 123456781234567979695948382928485849359686494864095409282048094275023098123.5; - ufixed0x256 b = 0.920890746623327805482905058466021565416131529487595827354393978494366605267637829135688384325135165352082715782143655824815685807141335814463015972119819459298455224338812271036061391763384038070334798471324635050876128428143374549108557403087615966796875; - ufixed0x256 c = 0.0000000000015198847363997979984922685411315294875958273543939784943666052676464653042434787697605517039455161817147718251801220885263595179331845639229818863564267318422845592626219390573301877339317935702714669975697814319204326238832436501979827880859375; - fixed248x8 d = -123456781234567979695948382928485849359686494864095409282048094275023098123.5; - fixed0x256 e = -0.93322335481643744342575580035176794825198893968114429702091846411734101080123092162893656820177312738451291806995868682861328125; - fixed0x256 g = -0.00011788606643744342575580035176794825198893968114429702091846411734101080123092162893656820177312738451291806995868682861328125; + ufixed256x1 a = 123456781234567979695948382928485849359686494864095409282048094275023098123.5; + ufixed256x77 b = 0.920890746623327805482905058466021565416131529487595827354393978494366605267637; + ufixed224x78 c = 0.000000000001519884736399797998492268541131529487595827354393978494366605267646; + fixed256x1 d = -123456781234567979695948382928485849359686494864095409282048094275023098123.5; + fixed256x76 e = -0.93322335481643744342575580035176794825198893968114429702091846411734101080123; + fixed256x79 g = -0.0001178860664374434257558003517679482519889396811442970209184641173410108012309; a; b; c; d; e; g; } } @@ -4201,17 +4210,30 @@ BOOST_AUTO_TEST_CASE(size_capabilities_of_fixed_point_types) CHECK_SUCCESS(text); } +BOOST_AUTO_TEST_CASE(zero_handling) +{ + char const* text = R"( + contract test { + function f() { + fixed16x2 a = 0; a; + ufixed32x1 b = 0; b; + } + } + )"; + CHECK_SUCCESS(text); +} + BOOST_AUTO_TEST_CASE(fixed_type_invalid_implicit_conversion_size) { char const* text = R"( contract test { function f() { ufixed a = 11/4; - ufixed248x8 b = a; + ufixed248x8 b = a; b; } } )"; - BOOST_CHECK(!success(text)); + CHECK_ERROR(text, TypeError, "Type ufixed128x19 is not implicitly convertible to expected type ufixed248x8"); } BOOST_AUTO_TEST_CASE(fixed_type_invalid_implicit_conversion_lost_data) @@ -4219,11 +4241,11 @@ BOOST_AUTO_TEST_CASE(fixed_type_invalid_implicit_conversion_lost_data) char const* text = R"( contract test { function f() { - ufixed0x256 a = 1/3; + ufixed256x1 a = 1/3; a; } } )"; - BOOST_CHECK(!success(text)); + CHECK_ERROR(text, TypeError, "is not implicitly convertible to expected type ufixed256x1"); } BOOST_AUTO_TEST_CASE(fixed_type_valid_explicit_conversions) @@ -4231,10 +4253,9 @@ BOOST_AUTO_TEST_CASE(fixed_type_valid_explicit_conversions) char const* text = R"( contract test { function f() { - ufixed0x256 a = ufixed0x256(1/3); - ufixed0x248 b = ufixed0x248(1/3); - ufixed0x8 c = ufixed0x8(1/3); - a; b; c; + ufixed256x80 a = ufixed256x80(1/3); a; + ufixed248x80 b = ufixed248x80(1/3); b; + ufixed8x1 c = ufixed8x1(1/3); c; } } )"; @@ -4246,23 +4267,35 @@ BOOST_AUTO_TEST_CASE(invalid_array_declaration_with_rational) char const* text = R"( contract test { function f() { - uint[3.5] a; + uint[3.5] a; a; } } )"; - BOOST_CHECK(!success(text)); + CHECK_ERROR(text, TypeError, "Invalid array length, expected integer literal"); } -BOOST_AUTO_TEST_CASE(invalid_array_declaration_with_fixed_type) +BOOST_AUTO_TEST_CASE(invalid_array_declaration_with_signed_fixed_type) { char const* text = R"( contract test { function f() { - uint[fixed(3.5)] a; + uint[fixed(3.5)] a; a; } } )"; - BOOST_CHECK(!success(text)); + CHECK_ERROR(text, TypeError, "Invalid array length, expected integer literal"); +} + +BOOST_AUTO_TEST_CASE(invalid_array_declaration_with_unsigned_fixed_type) +{ + char const* text = R"( + contract test { + function f() { + uint[ufixed(3.5)] a; a; + } + } + )"; + CHECK_ERROR(text, TypeError, "Invalid array length, expected integer literal"); } BOOST_AUTO_TEST_CASE(rational_to_bytes_implicit_conversion) @@ -4270,11 +4303,11 @@ BOOST_AUTO_TEST_CASE(rational_to_bytes_implicit_conversion) char const* text = R"( contract test { function f() { - bytes32 c = 3.2; + bytes32 c = 3.2; c; } } )"; - BOOST_CHECK(!success(text)); + CHECK_ERROR(text, TypeError, "is not implicitly convertible to expected type bytes32"); } BOOST_AUTO_TEST_CASE(fixed_to_bytes_implicit_conversion) @@ -4283,18 +4316,18 @@ BOOST_AUTO_TEST_CASE(fixed_to_bytes_implicit_conversion) contract test { function f() { fixed a = 3.25; - bytes32 c = a; + bytes32 c = a; c; } } )"; - BOOST_CHECK(!success(text)); + CHECK_ERROR(text, TypeError, "fixed128x19 is not implicitly convertible to expected type bytes32"); } BOOST_AUTO_TEST_CASE(mapping_with_fixed_literal) { char const* text = R"( contract test { - mapping(ufixed8x248 => string) fixedString; + mapping(ufixed8x1 => string) fixedString; function f() { fixedString[0.5] = "Half"; } @@ -4334,7 +4367,7 @@ BOOST_AUTO_TEST_CASE(inline_array_rationals) char const* text = R"( contract test { function f() { - ufixed8x8[4] memory a = [3.5, 4.125, 2.5, 4.0]; + ufixed128x3[4] memory a = [ufixed128x3(3.5), 4.125, 2.5, 4.0]; } } )"; @@ -4351,7 +4384,7 @@ BOOST_AUTO_TEST_CASE(rational_index_access) } } )"; - BOOST_CHECK(!success(text)); + CHECK_ERROR(text, TypeError, "rational_const 1/2 is not implicitly convertible to expected type uint256"); } BOOST_AUTO_TEST_CASE(rational_to_fixed_literal_expression) @@ -4359,12 +4392,12 @@ BOOST_AUTO_TEST_CASE(rational_to_fixed_literal_expression) char const* text = R"( contract test { function f() { - ufixed8x8 a = 3.5 * 3; - ufixed8x8 b = 4 - 2.5; - ufixed8x8 c = 11 / 4; - ufixed16x240 d = 599 + 0.21875; - ufixed8x248 e = ufixed8x248(35.245 % 12.9); - ufixed8x248 f = ufixed8x248(1.2 % 2); + ufixed64x8 a = 3.5 * 3; + ufixed64x8 b = 4 - 2.5; + ufixed64x8 c = 11 / 4; + ufixed240x5 d = 599 + 0.21875; + ufixed256x80 e = ufixed256x80(35.245 % 12.9); + ufixed256x80 f = ufixed256x80(1.2 % 2); fixed g = 2 ** -2; a; b; c; d; e; f; g; } @@ -4373,7 +4406,7 @@ BOOST_AUTO_TEST_CASE(rational_to_fixed_literal_expression) CHECK_SUCCESS(text); } -BOOST_AUTO_TEST_CASE(rational_as_exponent_value_neg_decimal) +BOOST_AUTO_TEST_CASE(rational_as_exponent_value_signed) { char const* text = R"( contract test { @@ -4382,10 +4415,10 @@ BOOST_AUTO_TEST_CASE(rational_as_exponent_value_neg_decimal) } } )"; - BOOST_CHECK(!success(text)); + CHECK_ERROR(text, TypeError, "not compatible with types"); } -BOOST_AUTO_TEST_CASE(rational_as_exponent_value_pos_decimal) +BOOST_AUTO_TEST_CASE(rational_as_exponent_value_unsigned) { char const* text = R"( contract test { @@ -4394,7 +4427,7 @@ BOOST_AUTO_TEST_CASE(rational_as_exponent_value_pos_decimal) } } )"; - BOOST_CHECK(!success(text)); + CHECK_ERROR(text, TypeError, "not compatible with types"); } BOOST_AUTO_TEST_CASE(rational_as_exponent_half) @@ -4402,11 +4435,11 @@ BOOST_AUTO_TEST_CASE(rational_as_exponent_half) char const* text = R"( contract test { function f() { - ufixed24x24 b = 2 ** (1/2); + 2 ** (1/2); } } )"; - BOOST_CHECK(!success(text)); + CHECK_ERROR(text, TypeError, "not compatible with types"); } BOOST_AUTO_TEST_CASE(rational_as_exponent_value_neg_quarter) @@ -4414,11 +4447,11 @@ BOOST_AUTO_TEST_CASE(rational_as_exponent_value_neg_quarter) char const* text = R"( contract test { function f() { - fixed40x40 c = 42 ** (-1/4); + 42 ** (-1/4); } } )"; - BOOST_CHECK(!success(text)); + CHECK_ERROR(text, TypeError, "not compatible with types"); } BOOST_AUTO_TEST_CASE(fixed_point_casting_exponents_15) @@ -4426,23 +4459,11 @@ BOOST_AUTO_TEST_CASE(fixed_point_casting_exponents_15) char const* text = R"( contract test { function f() { - ufixed a = 3 ** ufixed(1.5); - } - } - )"; - BOOST_CHECK(!success(text)); -} - -BOOST_AUTO_TEST_CASE(fixed_point_casting_exponents_half) -{ - char const* text = R"( - contract test { - function f() { - ufixed b = 2 ** ufixed(1/2); + var a = 3 ** ufixed(1.5); } } )"; - BOOST_CHECK(!success(text)); + CHECK_ERROR(text, TypeError, "not compatible with types"); } BOOST_AUTO_TEST_CASE(fixed_point_casting_exponents_neg) @@ -4450,23 +4471,11 @@ BOOST_AUTO_TEST_CASE(fixed_point_casting_exponents_neg) char const* text = R"( contract test { function f() { - fixed c = 42 ** fixed(-1/4); - } - } - )"; - BOOST_CHECK(!success(text)); -} - -BOOST_AUTO_TEST_CASE(fixed_point_casting_exponents_neg_decimal) -{ - char const* text = R"( - contract test { - function f() { - fixed d = 16 ** fixed(-0.5); + var c = 42 ** fixed(-1/4); } } )"; - BOOST_CHECK(!success(text)); + CHECK_ERROR(text, TypeError, "not compatible with types"); } BOOST_AUTO_TEST_CASE(var_capable_of_holding_constant_rationals) @@ -4506,7 +4515,7 @@ BOOST_AUTO_TEST_CASE(var_handle_divided_integers) } } )"; - CHECK_SUCCESS(text); + CHECK_SUCCESS(text); } BOOST_AUTO_TEST_CASE(rational_bitnot_unary_operation) @@ -4514,11 +4523,11 @@ BOOST_AUTO_TEST_CASE(rational_bitnot_unary_operation) char const* text = R"( contract test { function f() { - fixed a = ~3.5; + ~fixed(3.5); } } )"; - BOOST_CHECK(!success(text)); + CHECK_ERROR(text, TypeError, "cannot be applied"); } BOOST_AUTO_TEST_CASE(rational_bitor_binary_operation) @@ -4526,11 +4535,11 @@ BOOST_AUTO_TEST_CASE(rational_bitor_binary_operation) char const* text = R"( contract test { function f() { - fixed a = 1.5 | 3; + fixed(1.5) | 3; } } )"; - BOOST_CHECK(!success(text)); + CHECK_ERROR(text, TypeError, "not compatible with types"); } BOOST_AUTO_TEST_CASE(rational_bitxor_binary_operation) @@ -4538,11 +4547,11 @@ BOOST_AUTO_TEST_CASE(rational_bitxor_binary_operation) char const* text = R"( contract test { function f() { - fixed a = 1.75 ^ 3; + fixed(1.75) ^ 3; } } )"; - BOOST_CHECK(!success(text)); + CHECK_ERROR(text, TypeError, "not compatible with types"); } BOOST_AUTO_TEST_CASE(rational_bitand_binary_operation) @@ -4550,25 +4559,11 @@ BOOST_AUTO_TEST_CASE(rational_bitand_binary_operation) char const* text = R"( contract test { function f() { - fixed a = 1.75 & 3; - } - } - )"; - BOOST_CHECK(!success(text)); -} - -BOOST_AUTO_TEST_CASE(zero_handling) -{ - char const* text = R"( - contract test { - function f() { - fixed8x8 a = 0; - ufixed8x8 b = 0; - a; b; + fixed(1.75) & 3; } } )"; - CHECK_SUCCESS(text); + CHECK_ERROR(text, TypeError, "not compatible with types"); } BOOST_AUTO_TEST_CASE(missing_bool_conversion) @@ -4588,7 +4583,7 @@ BOOST_AUTO_TEST_CASE(integer_and_fixed_interaction) char const* text = R"( contract test { function f() { - ufixed a = uint128(1) + ufixed(2); + ufixed a = uint64(1) + ufixed(2); } } )"; @@ -4618,7 +4613,7 @@ BOOST_AUTO_TEST_CASE(one_divided_by_three_integer_conversion) } } )"; - BOOST_CHECK(!success(text)); + CHECK_ERROR(text, TypeError, "is not implicitly convertible to expected type uint256. Try converting to type ufixed256x77"); } BOOST_AUTO_TEST_CASE(unused_return_value) @@ -5428,6 +5423,20 @@ BOOST_AUTO_TEST_CASE(inline_assembly_storage_variable_access_out_of_functions) CHECK_SUCCESS_NO_WARNINGS(text); } +BOOST_AUTO_TEST_CASE(inline_assembly_calldata_variables) +{ + char const* text = R"( + contract C { + function f(bytes bytesAsCalldata) external { + assembly { + let x := bytesAsCalldata + } + } + } + )"; + CHECK_ERROR(text, TypeError, "Call data elements cannot be accessed directly."); +} + BOOST_AUTO_TEST_CASE(invalid_mobile_type) { char const* text = R"( @@ -5489,22 +5498,6 @@ BOOST_AUTO_TEST_CASE(does_not_warn_msg_value_in_library) CHECK_SUCCESS_NO_WARNINGS(text); } -BOOST_AUTO_TEST_CASE(does_not_warn_non_magic_msg_value) -{ - char const* text = R"( - contract C { - struct msg { - uint256 value; - } - - function f() { - msg.value; - } - } - )"; - CHECK_SUCCESS_NO_WARNINGS(text); -} - BOOST_AUTO_TEST_CASE(does_not_warn_msg_value_in_modifier_following_non_payable_public_function) { char const* text = R"( @@ -6118,6 +6111,85 @@ BOOST_AUTO_TEST_CASE(no_unused_inline_asm) CHECK_SUCCESS_NO_WARNINGS(text); } +BOOST_AUTO_TEST_CASE(shadowing_builtins_with_functions) +{ + char const* text = R"( + contract C { + function keccak256() {} + } + )"; + CHECK_WARNING(text, "shadows a builtin symbol"); +} + +BOOST_AUTO_TEST_CASE(shadowing_builtins_with_variables) +{ + char const* text = R"( + contract C { + function f() { + uint msg; + msg; + } + } + )"; + CHECK_WARNING(text, "shadows a builtin symbol"); +} + +BOOST_AUTO_TEST_CASE(shadowing_builtins_with_parameters) +{ + char const* text = R"( + contract C { + function f(uint require) { + require = 2; + } + } + )"; + CHECK_WARNING(text, "shadows a builtin symbol"); +} + +BOOST_AUTO_TEST_CASE(shadowing_builtins_with_return_parameters) +{ + char const* text = R"( + contract C { + function f() returns (uint require) { + require = 2; + } + } + )"; + CHECK_WARNING(text, "shadows a builtin symbol"); +} + +BOOST_AUTO_TEST_CASE(shadowing_builtins_with_events) +{ + char const* text = R"( + contract C { + event keccak256(); + } + )"; + CHECK_WARNING(text, "shadows a builtin symbol"); +} + +BOOST_AUTO_TEST_CASE(shadowing_builtins_ignores_struct) +{ + char const* text = R"( + contract C { + struct a { + uint msg; + } + } + )"; + CHECK_SUCCESS_NO_WARNINGS(text); +} + +BOOST_AUTO_TEST_CASE(shadowing_builtins_ignores_constructor) +{ + char const* text = R"( + contract C { + function C() {} + } + )"; + CHECK_SUCCESS_NO_WARNINGS(text); +} + BOOST_AUTO_TEST_CASE(callable_crash) { char const* text = R"( @@ -6132,35 +6204,115 @@ BOOST_AUTO_TEST_CASE(callable_crash) CHECK_ERROR(text, TypeError, "Type is not callable"); } -BOOST_AUTO_TEST_CASE(returndatacopy_as_variable) +BOOST_AUTO_TEST_CASE(error_transfer_non_payable_fallback) { char const* text = R"( - contract c { function f() { uint returndatasize; assembly { returndatasize }}} + contract A { + function() {} + } + + contract B { + A a; + + function() { + a.transfer(100); + } + } )"; - CHECK_WARNING_ALLOW_MULTI(text, "Variable is shadowed in inline assembly by an instruction of the same name"); + CHECK_ERROR(text, TypeError, "Value transfer to a contract without a payable fallback function."); } -BOOST_AUTO_TEST_CASE(create2_as_variable) +BOOST_AUTO_TEST_CASE(error_transfer_no_fallback) { char const* text = R"( - contract c { function f() { uint create2; assembly { create2(0, 0, 0, 0) }}} + contract A {} + + contract B { + A a; + + function() { + a.transfer(100); + } + } )"; - CHECK_WARNING_ALLOW_MULTI(text, "Variable is shadowed in inline assembly by an instruction of the same name"); + CHECK_ERROR(text, TypeError, "Value transfer to a contract without a payable fallback function."); } -BOOST_AUTO_TEST_CASE(shadowing_warning_can_be_removed) +BOOST_AUTO_TEST_CASE(error_send_non_payable_fallback) { char const* text = R"( - contract C {function f() {assembly {}}} + contract A { + function() {} + } + + contract B { + A a; + + function() { + require(a.send(100)); + } + } + )"; + CHECK_ERROR(text, TypeError, "Value transfer to a contract without a payable fallback function."); +} + +BOOST_AUTO_TEST_CASE(does_not_error_transfer_payable_fallback) +{ + char const* text = R"( + contract A { + function() payable {} + } + + contract B { + A a; + + function() { + a.transfer(100); + } + } + )"; + CHECK_SUCCESS_NO_WARNINGS(text); +} + +BOOST_AUTO_TEST_CASE(does_not_error_transfer_regular_function) +{ + char const* text = R"( + contract A { + function transfer(uint) {} + } + + contract B { + A a; + + function() { + a.transfer(100); + } + } )"; CHECK_SUCCESS_NO_WARNINGS(text); } +BOOST_AUTO_TEST_CASE(returndatacopy_as_variable) +{ + char const* text = R"( + contract c { function f() { uint returndatasize; assembly { returndatasize }}} + )"; + CHECK_WARNING_ALLOW_MULTI(text, "Variable is shadowed in inline assembly by an instruction of the same name"); +} + +BOOST_AUTO_TEST_CASE(create2_as_variable) +{ + char const* text = R"( + contract c { function f() { uint create2; assembly { create2(0, 0, 0, 0) }}} + )"; + CHECK_WARNING_ALLOW_MULTI(text, "Variable is shadowed in inline assembly by an instruction of the same name"); +} + BOOST_AUTO_TEST_CASE(warn_unspecified_storage) { char const* text = R"( contract C { - struct S { uint a; } + struct S { uint a; string b; } S x; function f() { S storage y = x; @@ -6182,6 +6334,122 @@ BOOST_AUTO_TEST_CASE(warn_unspecified_storage) CHECK_WARNING(text, "is declared as a storage pointer. Use an explicit \"storage\" keyword to silence this warning"); } +BOOST_AUTO_TEST_CASE(implicit_conversion_disallowed) +{ + char const* text = R"( + contract C { + function f() returns (bytes4) { + uint32 tmp = 1; + return tmp; + } + } + )"; + CHECK_ERROR(text, TypeError, "Return argument type uint32 is not implicitly convertible to expected type (type of first return variable) bytes4."); +} + +BOOST_AUTO_TEST_CASE(too_large_arrays_for_calldata) +{ + char const* text = R"( + contract C { + function f(uint[85678901234] a) external { + } + } + )"; + CHECK_ERROR(text, TypeError, "Array is too large to be encoded as calldata."); + text = R"( + contract C { + function f(uint[85678901234] a) internal { + } + } + )"; + CHECK_SUCCESS_NO_WARNINGS(text); + text = R"( + contract C { + function f(uint[85678901234] a) { + } + } + )"; + CHECK_ERROR(text, TypeError, "Array is too large to be encoded as calldata."); +} + +BOOST_AUTO_TEST_CASE(explicit_literal_to_storage_string) +{ + char const* text = R"( + contract C { + function f() { + string memory x = "abc"; + x; + } + } + )"; + CHECK_SUCCESS_NO_WARNINGS(text); + text = R"( + contract C { + function f() { + string storage x = "abc"; + } + } + )"; + CHECK_ERROR(text, TypeError, "Type literal_string \"abc\" is not implicitly convertible to expected type string storage pointer."); + text = R"( + contract C { + function f() { + string x = "abc"; + } + } + )"; + CHECK_ERROR(text, TypeError, "Type literal_string \"abc\" is not implicitly convertible to expected type string storage pointer."); + text = R"( + contract C { + function f() { + string("abc"); + } + } + )"; + CHECK_ERROR(text, TypeError, "Explicit type conversion not allowed from \"literal_string \"abc\"\" to \"string storage pointer\""); +} + +BOOST_AUTO_TEST_CASE(modifiers_access_storage_pointer) +{ + char const* text = R"( + contract C { + struct S { } + modifier m(S storage x) { + x; + _; + } + } + )"; + CHECK_SUCCESS_NO_WARNINGS(text); +} + +BOOST_AUTO_TEST_CASE(using_this_in_constructor) +{ + char const* text = R"( + contract C { + function C() { + this.f(); + } + function f() { + } + } + )"; + CHECK_WARNING(text, "\"this\" used in constructor"); +} + +BOOST_AUTO_TEST_CASE(do_not_crash_on_not_lalue) +{ + // This checks for a bug that caused a crash because of continued analysis. + char const* text = R"( + contract C { + mapping (uint => uint) m; + function f() { + m(1) = 2; + } + } + )"; + CHECK_ERROR_ALLOW_MULTI(text, TypeError, "is not callable"); +} BOOST_AUTO_TEST_SUITE_END() diff --git a/test/libsolidity/SolidityNatspecJSON.cpp b/test/libsolidity/SolidityNatspecJSON.cpp index 2a7376b9..be20a9f2 100644 --- a/test/libsolidity/SolidityNatspecJSON.cpp +++ b/test/libsolidity/SolidityNatspecJSON.cpp @@ -45,7 +45,9 @@ public: bool _userDocumentation ) { - ETH_TEST_REQUIRE_NO_THROW(m_compilerStack.parseAndAnalyze("pragma solidity >=0.0;\n" + _code), "Parsing failed"); + m_compilerStack.reset(false); + m_compilerStack.addSource("", "pragma solidity >=0.0;\n" + _code); + ETH_TEST_REQUIRE_NO_THROW(m_compilerStack.parseAndAnalyze(), "Parsing contract failed"); Json::Value generatedDocumentation; if (_userDocumentation) @@ -63,7 +65,9 @@ public: void expectNatspecError(std::string const& _code) { - BOOST_CHECK(!m_compilerStack.parseAndAnalyze(_code)); + m_compilerStack.reset(false); + m_compilerStack.addSource("", "pragma solidity >=0.0;\n" + _code); + BOOST_CHECK(!m_compilerStack.parseAndAnalyze()); BOOST_REQUIRE(Error::containsErrorOfType(m_compilerStack.errors(), Error::Type::DocstringParsingError)); } diff --git a/test/libsolidity/SolidityOptimizer.cpp b/test/libsolidity/SolidityOptimizer.cpp index a4d80c99..bd635c33 100644 --- a/test/libsolidity/SolidityOptimizer.cpp +++ b/test/libsolidity/SolidityOptimizer.cpp @@ -22,11 +22,7 @@ #include <test/libsolidity/SolidityExecutionFramework.h> -#include <libevmasm/CommonSubexpressionEliminator.h> -#include <libevmasm/PeepholeOptimiser.h> -#include <libevmasm/ControlFlowGraph.h> -#include <libevmasm/Assembly.h> -#include <libevmasm/BlockDeduplicator.h> +#include <libevmasm/Instruction.h> #include <boost/test/unit_test.hpp> #include <boost/lexical_cast.hpp> @@ -106,71 +102,6 @@ public: "\nOptimized: " + toHex(optimizedOutput)); } - AssemblyItems addDummyLocations(AssemblyItems const& _input) - { - // add dummy locations to each item so that we can check that they are not deleted - AssemblyItems input = _input; - for (AssemblyItem& item: input) - item.setLocation(SourceLocation(1, 3, make_shared<string>(""))); - return input; - } - - eth::KnownState createInitialState(AssemblyItems const& _input) - { - eth::KnownState state; - for (auto const& item: addDummyLocations(_input)) - state.feedItem(item, true); - return state; - } - - AssemblyItems CSE(AssemblyItems const& _input, eth::KnownState const& _state = eth::KnownState()) - { - AssemblyItems input = addDummyLocations(_input); - - eth::CommonSubexpressionEliminator cse(_state); - BOOST_REQUIRE(cse.feedItems(input.begin(), input.end()) == input.end()); - AssemblyItems output = cse.getOptimizedItems(); - - for (AssemblyItem const& item: output) - { - BOOST_CHECK(item == Instruction::POP || !item.location().isEmpty()); - } - return output; - } - - void checkCSE( - AssemblyItems const& _input, - AssemblyItems const& _expectation, - KnownState const& _state = eth::KnownState() - ) - { - AssemblyItems output = CSE(_input, _state); - BOOST_CHECK_EQUAL_COLLECTIONS(_expectation.begin(), _expectation.end(), output.begin(), output.end()); - } - - AssemblyItems CFG(AssemblyItems const& _input) - { - AssemblyItems output = _input; - // Running it four times should be enough for these tests. - for (unsigned i = 0; i < 4; ++i) - { - ControlFlowGraph cfg(output); - AssemblyItems optItems; - for (BasicBlock const& block: cfg.optimisedBlocks()) - copy(output.begin() + block.begin, output.begin() + block.end, - back_inserter(optItems)); - output = move(optItems); - } - return output; - } - - void checkCFG(AssemblyItems const& _input, AssemblyItems const& _expectation) - { - AssemblyItems output = CFG(_input); - BOOST_CHECK_EQUAL_COLLECTIONS(_expectation.begin(), _expectation.end(), output.begin(), output.end()); - } - -protected: /// @returns the number of intructions in the given bytecode, not taking the metadata hash /// into account. size_t numInstructions(bytes const& _bytecode) @@ -187,6 +118,7 @@ protected: return instructions; } +protected: Address m_optimizedContract; Address m_nonOptimizedContract; }; @@ -434,734 +366,6 @@ BOOST_AUTO_TEST_CASE(sequence_number_for_calls) compareVersions("f(string,string)", 0x40, 0x80, 3, "abc", 3, "def"); } -BOOST_AUTO_TEST_CASE(cse_intermediate_swap) -{ - eth::KnownState state; - eth::CommonSubexpressionEliminator cse(state); - AssemblyItems input{ - Instruction::SWAP1, Instruction::POP, Instruction::ADD, u256(0), Instruction::SWAP1, - Instruction::SLOAD, Instruction::SWAP1, u256(100), Instruction::EXP, Instruction::SWAP1, - Instruction::DIV, u256(0xff), Instruction::AND - }; - BOOST_REQUIRE(cse.feedItems(input.begin(), input.end()) == input.end()); - AssemblyItems output = cse.getOptimizedItems(); - BOOST_CHECK(!output.empty()); -} - -BOOST_AUTO_TEST_CASE(cse_negative_stack_access) -{ - AssemblyItems input{Instruction::DUP2, u256(0)}; - checkCSE(input, input); -} - -BOOST_AUTO_TEST_CASE(cse_negative_stack_end) -{ - AssemblyItems input{Instruction::ADD}; - checkCSE(input, input); -} - -BOOST_AUTO_TEST_CASE(cse_intermediate_negative_stack) -{ - AssemblyItems input{Instruction::ADD, u256(1), Instruction::DUP1}; - checkCSE(input, input); -} - -BOOST_AUTO_TEST_CASE(cse_pop) -{ - checkCSE({Instruction::POP}, {Instruction::POP}); -} - -BOOST_AUTO_TEST_CASE(cse_unneeded_items) -{ - AssemblyItems input{ - Instruction::ADD, - Instruction::SWAP1, - Instruction::POP, - u256(7), - u256(8), - }; - checkCSE(input, input); -} - -BOOST_AUTO_TEST_CASE(cse_constant_addition) -{ - AssemblyItems input{u256(7), u256(8), Instruction::ADD}; - checkCSE(input, {u256(7 + 8)}); -} - -BOOST_AUTO_TEST_CASE(cse_invariants) -{ - AssemblyItems input{ - Instruction::DUP1, - Instruction::DUP1, - u256(0), - Instruction::OR, - Instruction::OR - }; - checkCSE(input, {Instruction::DUP1}); -} - -BOOST_AUTO_TEST_CASE(cse_subself) -{ - checkCSE({Instruction::DUP1, Instruction::SUB}, {Instruction::POP, u256(0)}); -} - -BOOST_AUTO_TEST_CASE(cse_subother) -{ - checkCSE({Instruction::SUB}, {Instruction::SUB}); -} - -BOOST_AUTO_TEST_CASE(cse_double_negation) -{ - checkCSE({Instruction::DUP5, Instruction::NOT, Instruction::NOT}, {Instruction::DUP5}); -} - -BOOST_AUTO_TEST_CASE(cse_double_iszero) -{ - checkCSE({Instruction::GT, Instruction::ISZERO, Instruction::ISZERO}, {Instruction::GT}); - checkCSE({Instruction::GT, Instruction::ISZERO}, {Instruction::GT, Instruction::ISZERO}); - checkCSE( - {Instruction::ISZERO, Instruction::ISZERO, Instruction::ISZERO}, - {Instruction::ISZERO} - ); -} - -BOOST_AUTO_TEST_CASE(cse_associativity) -{ - AssemblyItems input{ - Instruction::DUP1, - Instruction::DUP1, - u256(0), - Instruction::OR, - Instruction::OR - }; - checkCSE(input, {Instruction::DUP1}); -} - -BOOST_AUTO_TEST_CASE(cse_associativity2) -{ - AssemblyItems input{ - u256(0), - Instruction::DUP2, - u256(2), - u256(1), - Instruction::DUP6, - Instruction::ADD, - u256(2), - Instruction::ADD, - Instruction::ADD, - Instruction::ADD, - Instruction::ADD - }; - checkCSE(input, {Instruction::DUP2, Instruction::DUP2, Instruction::ADD, u256(5), Instruction::ADD}); -} - -BOOST_AUTO_TEST_CASE(cse_storage) -{ - AssemblyItems input{ - u256(0), - Instruction::SLOAD, - u256(0), - Instruction::SLOAD, - Instruction::ADD, - u256(0), - Instruction::SSTORE - }; - checkCSE(input, { - u256(0), - Instruction::DUP1, - Instruction::SLOAD, - Instruction::DUP1, - Instruction::ADD, - Instruction::SWAP1, - Instruction::SSTORE - }); -} - -BOOST_AUTO_TEST_CASE(cse_noninterleaved_storage) -{ - // two stores to the same location should be replaced by only one store, even if we - // read in the meantime - AssemblyItems input{ - u256(7), - Instruction::DUP2, - Instruction::SSTORE, - Instruction::DUP1, - Instruction::SLOAD, - u256(8), - Instruction::DUP3, - Instruction::SSTORE - }; - checkCSE(input, { - u256(8), - Instruction::DUP2, - Instruction::SSTORE, - u256(7) - }); -} - -BOOST_AUTO_TEST_CASE(cse_interleaved_storage) -{ - // stores and reads to/from two unknown locations, should not optimize away the first store - AssemblyItems input{ - u256(7), - Instruction::DUP2, - Instruction::SSTORE, // store to "DUP1" - Instruction::DUP2, - Instruction::SLOAD, // read from "DUP2", might be equal to "DUP1" - u256(0), - Instruction::DUP3, - Instruction::SSTORE // store different value to "DUP1" - }; - checkCSE(input, input); -} - -BOOST_AUTO_TEST_CASE(cse_interleaved_storage_same_value) -{ - // stores and reads to/from two unknown locations, should not optimize away the first store - // but it should optimize away the second, since we already know the value will be the same - AssemblyItems input{ - u256(7), - Instruction::DUP2, - Instruction::SSTORE, // store to "DUP1" - Instruction::DUP2, - Instruction::SLOAD, // read from "DUP2", might be equal to "DUP1" - u256(6), - u256(1), - Instruction::ADD, - Instruction::DUP3, - Instruction::SSTORE // store same value to "DUP1" - }; - checkCSE(input, { - u256(7), - Instruction::DUP2, - Instruction::SSTORE, - Instruction::DUP2, - Instruction::SLOAD - }); -} - -BOOST_AUTO_TEST_CASE(cse_interleaved_storage_at_known_location) -{ - // stores and reads to/from two known locations, should optimize away the first store, - // because we know that the location is different - AssemblyItems input{ - u256(0x70), - u256(1), - Instruction::SSTORE, // store to 1 - u256(2), - Instruction::SLOAD, // read from 2, is different from 1 - u256(0x90), - u256(1), - Instruction::SSTORE // store different value at 1 - }; - checkCSE(input, { - u256(2), - Instruction::SLOAD, - u256(0x90), - u256(1), - Instruction::SSTORE - }); -} - -BOOST_AUTO_TEST_CASE(cse_interleaved_storage_at_known_location_offset) -{ - // stores and reads to/from two locations which are known to be different, - // should optimize away the first store, because we know that the location is different - AssemblyItems input{ - u256(0x70), - Instruction::DUP2, - u256(1), - Instruction::ADD, - Instruction::SSTORE, // store to "DUP1"+1 - Instruction::DUP1, - u256(2), - Instruction::ADD, - Instruction::SLOAD, // read from "DUP1"+2, is different from "DUP1"+1 - u256(0x90), - Instruction::DUP3, - u256(1), - Instruction::ADD, - Instruction::SSTORE // store different value at "DUP1"+1 - }; - checkCSE(input, { - u256(2), - Instruction::DUP2, - Instruction::ADD, - Instruction::SLOAD, - u256(0x90), - u256(1), - Instruction::DUP4, - Instruction::ADD, - Instruction::SSTORE - }); -} - -BOOST_AUTO_TEST_CASE(cse_deep_stack) -{ - AssemblyItems input{ - Instruction::ADD, - Instruction::SWAP1, - Instruction::POP, - Instruction::SWAP8, - Instruction::POP, - Instruction::SWAP8, - Instruction::POP, - Instruction::SWAP8, - Instruction::SWAP5, - Instruction::POP, - Instruction::POP, - Instruction::POP, - Instruction::POP, - Instruction::POP, - }; - checkCSE(input, { - Instruction::SWAP4, - Instruction::SWAP12, - Instruction::SWAP3, - Instruction::SWAP11, - Instruction::POP, - Instruction::SWAP1, - Instruction::SWAP3, - Instruction::ADD, - Instruction::SWAP8, - Instruction::POP, - Instruction::SWAP6, - Instruction::POP, - Instruction::POP, - Instruction::POP, - Instruction::POP, - Instruction::POP, - Instruction::POP, - }); -} - -BOOST_AUTO_TEST_CASE(cse_jumpi_no_jump) -{ - AssemblyItems input{ - u256(0), - u256(1), - Instruction::DUP2, - AssemblyItem(PushTag, 1), - Instruction::JUMPI - }; - checkCSE(input, { - u256(0), - u256(1) - }); -} - -BOOST_AUTO_TEST_CASE(cse_jumpi_jump) -{ - AssemblyItems input{ - u256(1), - u256(1), - Instruction::DUP2, - AssemblyItem(PushTag, 1), - Instruction::JUMPI - }; - checkCSE(input, { - u256(1), - Instruction::DUP1, - AssemblyItem(PushTag, 1), - Instruction::JUMP - }); -} - -BOOST_AUTO_TEST_CASE(cse_empty_keccak256) -{ - AssemblyItems input{ - u256(0), - Instruction::DUP2, - Instruction::KECCAK256 - }; - checkCSE(input, { - u256(dev::keccak256(bytesConstRef())) - }); -} - -BOOST_AUTO_TEST_CASE(cse_partial_keccak256) -{ - AssemblyItems input{ - u256(0xabcd) << (256 - 16), - u256(0), - Instruction::MSTORE, - u256(2), - u256(0), - Instruction::KECCAK256 - }; - checkCSE(input, { - u256(0xabcd) << (256 - 16), - u256(0), - Instruction::MSTORE, - u256(dev::keccak256(bytes{0xab, 0xcd})) - }); -} - -BOOST_AUTO_TEST_CASE(cse_keccak256_twice_same_location) -{ - // Keccak-256 twice from same dynamic location - AssemblyItems input{ - Instruction::DUP2, - Instruction::DUP1, - Instruction::MSTORE, - u256(64), - Instruction::DUP2, - Instruction::KECCAK256, - u256(64), - Instruction::DUP3, - Instruction::KECCAK256 - }; - checkCSE(input, { - Instruction::DUP2, - Instruction::DUP1, - Instruction::MSTORE, - u256(64), - Instruction::DUP2, - Instruction::KECCAK256, - Instruction::DUP1 - }); -} - -BOOST_AUTO_TEST_CASE(cse_keccak256_twice_same_content) -{ - // Keccak-256 twice from different dynamic location but with same content - AssemblyItems input{ - Instruction::DUP1, - u256(0x80), - Instruction::MSTORE, // m[128] = DUP1 - u256(0x20), - u256(0x80), - Instruction::KECCAK256, // keccak256(m[128..(128+32)]) - Instruction::DUP2, - u256(12), - Instruction::MSTORE, // m[12] = DUP1 - u256(0x20), - u256(12), - Instruction::KECCAK256 // keccak256(m[12..(12+32)]) - }; - checkCSE(input, { - u256(0x80), - Instruction::DUP2, - Instruction::DUP2, - Instruction::MSTORE, - u256(0x20), - Instruction::SWAP1, - Instruction::KECCAK256, - u256(12), - Instruction::DUP3, - Instruction::SWAP1, - Instruction::MSTORE, - Instruction::DUP1 - }); -} - -BOOST_AUTO_TEST_CASE(cse_keccak256_twice_same_content_dynamic_store_in_between) -{ - // Keccak-256 twice from different dynamic location but with same content, - // dynamic mstore in between, which forces us to re-calculate the hash - AssemblyItems input{ - u256(0x80), - Instruction::DUP2, - Instruction::DUP2, - Instruction::MSTORE, // m[128] = DUP1 - u256(0x20), - Instruction::DUP1, - Instruction::DUP3, - Instruction::KECCAK256, // keccak256(m[128..(128+32)]) - u256(12), - Instruction::DUP5, - Instruction::DUP2, - Instruction::MSTORE, // m[12] = DUP1 - Instruction::DUP12, - Instruction::DUP14, - Instruction::MSTORE, // destroys memory knowledge - Instruction::SWAP2, - Instruction::SWAP1, - Instruction::SWAP2, - Instruction::KECCAK256 // keccak256(m[12..(12+32)]) - }; - checkCSE(input, input); -} - -BOOST_AUTO_TEST_CASE(cse_keccak256_twice_same_content_noninterfering_store_in_between) -{ - // Keccak-256 twice from different dynamic location but with same content, - // dynamic mstore in between, but does not force us to re-calculate the hash - AssemblyItems input{ - u256(0x80), - Instruction::DUP2, - Instruction::DUP2, - Instruction::MSTORE, // m[128] = DUP1 - u256(0x20), - Instruction::DUP1, - Instruction::DUP3, - Instruction::KECCAK256, // keccak256(m[128..(128+32)]) - u256(12), - Instruction::DUP5, - Instruction::DUP2, - Instruction::MSTORE, // m[12] = DUP1 - Instruction::DUP12, - u256(12 + 32), - Instruction::MSTORE, // does not destoy memory knowledge - Instruction::DUP13, - u256(128 - 32), - Instruction::MSTORE, // does not destoy memory knowledge - u256(0x20), - u256(12), - Instruction::KECCAK256 // keccak256(m[12..(12+32)]) - }; - // if this changes too often, only count the number of SHA3 and MSTORE instructions - AssemblyItems output = CSE(input); - BOOST_CHECK_EQUAL(4, count(output.begin(), output.end(), AssemblyItem(Instruction::MSTORE))); - BOOST_CHECK_EQUAL(1, count(output.begin(), output.end(), AssemblyItem(Instruction::KECCAK256))); -} - -BOOST_AUTO_TEST_CASE(cse_with_initially_known_stack) -{ - eth::KnownState state = createInitialState(AssemblyItems{ - u256(0x12), - u256(0x20), - Instruction::ADD - }); - AssemblyItems input{ - u256(0x12 + 0x20) - }; - checkCSE(input, AssemblyItems{Instruction::DUP1}, state); -} - -BOOST_AUTO_TEST_CASE(cse_equality_on_initially_known_stack) -{ - eth::KnownState state = createInitialState(AssemblyItems{Instruction::DUP1}); - AssemblyItems input{ - Instruction::EQ - }; - AssemblyItems output = CSE(input, state); - // check that it directly pushes 1 (true) - BOOST_CHECK(find(output.begin(), output.end(), AssemblyItem(u256(1))) != output.end()); -} - -BOOST_AUTO_TEST_CASE(cse_access_previous_sequence) -{ - // Tests that the code generator detects whether it tries to access SLOAD instructions - // from a sequenced expression which is not in its scope. - eth::KnownState state = createInitialState(AssemblyItems{ - u256(0), - Instruction::SLOAD, - u256(1), - Instruction::ADD, - u256(0), - Instruction::SSTORE - }); - // now stored: val_1 + 1 (value at sequence 1) - // if in the following instructions, the SLOAD cresolves to "val_1 + 1", - // this cannot be generated because we cannot load from sequence 1 anymore. - AssemblyItems input{ - u256(0), - Instruction::SLOAD, - }; - BOOST_CHECK_THROW(CSE(input, state), StackTooDeepException); - // @todo for now, this throws an exception, but it should recover to the following - // (or an even better version) at some point: - // 0, SLOAD, 1, ADD, SSTORE, 0 SLOAD -} - -BOOST_AUTO_TEST_CASE(cse_optimise_return) -{ - checkCSE( - AssemblyItems{u256(0), u256(7), Instruction::RETURN}, - AssemblyItems{Instruction::STOP} - ); -} - -BOOST_AUTO_TEST_CASE(control_flow_graph_remove_unused) -{ - // remove parts of the code that are unused - AssemblyItems input{ - AssemblyItem(PushTag, 1), - Instruction::JUMP, - u256(7), - AssemblyItem(Tag, 1), - }; - checkCFG(input, {}); -} - -BOOST_AUTO_TEST_CASE(control_flow_graph_remove_unused_loop) -{ - AssemblyItems input{ - AssemblyItem(PushTag, 3), - Instruction::JUMP, - AssemblyItem(Tag, 1), - u256(7), - AssemblyItem(PushTag, 2), - Instruction::JUMP, - AssemblyItem(Tag, 2), - u256(8), - AssemblyItem(PushTag, 1), - Instruction::JUMP, - AssemblyItem(Tag, 3), - u256(11) - }; - checkCFG(input, {u256(11)}); -} - -BOOST_AUTO_TEST_CASE(control_flow_graph_reconnect_single_jump_source) -{ - // move code that has only one unconditional jump source - AssemblyItems input{ - u256(1), - AssemblyItem(PushTag, 1), - Instruction::JUMP, - AssemblyItem(Tag, 2), - u256(2), - AssemblyItem(PushTag, 3), - Instruction::JUMP, - AssemblyItem(Tag, 1), - u256(3), - AssemblyItem(PushTag, 2), - Instruction::JUMP, - AssemblyItem(Tag, 3), - u256(4), - }; - checkCFG(input, {u256(1), u256(3), u256(2), u256(4)}); -} - -BOOST_AUTO_TEST_CASE(control_flow_graph_do_not_remove_returned_to) -{ - // do not remove parts that are "returned to" - AssemblyItems input{ - AssemblyItem(PushTag, 1), - AssemblyItem(PushTag, 2), - Instruction::JUMP, - AssemblyItem(Tag, 2), - Instruction::JUMP, - AssemblyItem(Tag, 1), - u256(2) - }; - checkCFG(input, {u256(2)}); -} - -BOOST_AUTO_TEST_CASE(block_deduplicator) -{ - AssemblyItems input{ - AssemblyItem(PushTag, 2), - AssemblyItem(PushTag, 1), - AssemblyItem(PushTag, 3), - u256(6), - Instruction::SWAP3, - Instruction::JUMP, - AssemblyItem(Tag, 1), - u256(6), - Instruction::SWAP3, - Instruction::JUMP, - AssemblyItem(Tag, 2), - u256(6), - Instruction::SWAP3, - Instruction::JUMP, - AssemblyItem(Tag, 3) - }; - BlockDeduplicator dedup(input); - dedup.deduplicate(); - - set<u256> pushTags; - for (AssemblyItem const& item: input) - if (item.type() == PushTag) - pushTags.insert(item.data()); - BOOST_CHECK_EQUAL(pushTags.size(), 2); -} - -BOOST_AUTO_TEST_CASE(block_deduplicator_loops) -{ - AssemblyItems input{ - u256(0), - Instruction::SLOAD, - AssemblyItem(PushTag, 1), - AssemblyItem(PushTag, 2), - Instruction::JUMPI, - Instruction::JUMP, - AssemblyItem(Tag, 1), - u256(5), - u256(6), - Instruction::SSTORE, - AssemblyItem(PushTag, 1), - Instruction::JUMP, - AssemblyItem(Tag, 2), - u256(5), - u256(6), - Instruction::SSTORE, - AssemblyItem(PushTag, 2), - 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_CASE(clear_unreachable_code) -{ - AssemblyItems items{ - AssemblyItem(PushTag, 1), - Instruction::JUMP, - u256(0), - Instruction::SLOAD, - AssemblyItem(Tag, 2), - u256(5), - u256(6), - Instruction::SSTORE, - AssemblyItem(PushTag, 1), - Instruction::JUMP, - u256(5), - u256(6) - }; - AssemblyItems expectation{ - AssemblyItem(PushTag, 1), - Instruction::JUMP, - AssemblyItem(Tag, 2), - u256(5), - u256(6), - Instruction::SSTORE, - AssemblyItem(PushTag, 1), - Instruction::JUMP - }; - PeepholeOptimiser peepOpt(items); - BOOST_REQUIRE(peepOpt.optimise()); - BOOST_CHECK_EQUAL_COLLECTIONS( - items.begin(), items.end(), - expectation.begin(), expectation.end() - ); -} - -BOOST_AUTO_TEST_CASE(peephole_double_push) -{ - AssemblyItems items{ - u256(0), - u256(0), - u256(5), - u256(5), - u256(4), - u256(5) - }; - AssemblyItems expectation{ - u256(0), - Instruction::DUP1, - u256(5), - Instruction::DUP1, - u256(4), - u256(5) - }; - PeepholeOptimiser peepOpt(items); - BOOST_REQUIRE(peepOpt.optimise()); - BOOST_CHECK_EQUAL_COLLECTIONS( - items.begin(), items.end(), - expectation.begin(), expectation.end() - ); -} - BOOST_AUTO_TEST_CASE(computing_constants) { char const* sourceCode = R"( @@ -1377,29 +581,6 @@ BOOST_AUTO_TEST_CASE(invalid_state_at_control_flow_join) compareVersions("test()"); } -BOOST_AUTO_TEST_CASE(cse_sub_zero) -{ - checkCSE({ - u256(0), - Instruction::DUP2, - Instruction::SUB - }, { - Instruction::DUP1 - }); - - checkCSE({ - Instruction::DUP1, - u256(0), - Instruction::SUB - }, { - u256(0), - Instruction::DUP2, - Instruction::SWAP1, - Instruction::SUB - }); -} - - BOOST_AUTO_TEST_SUITE_END() } |