Merge pull request #2667 from ethereum/develop

Merge develop into release in proparation for 0.4.14
This commit is contained in:
chriseth 2017-07-31 16:14:46 +02:00 committed by GitHub
commit c2215d4605
194 changed files with 17494 additions and 1583 deletions

View File

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

View File

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

19
ReleaseChecklist.md Normal file
View File

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

View File

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

View File

@ -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.
@ -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",

View File

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

View File

@ -1,4 +1,11 @@
[
{
"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.",

View File

@ -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"
],

View File

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

View File

@ -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.
``require``-style exceptions will not consume any gas starting from the Metropolis release.

View File

@ -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;
}
}

View File

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

View File

@ -83,6 +83,10 @@ If you want to use the cutting edge developer version:
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:
.. code:: bash

View File

@ -210,4 +210,3 @@ for the two input parameters and two returned values.
p = 2 * (w + h);
}
}

View File

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

View File

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

View File

@ -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,14 +500,9 @@ 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
/// to the beneficiary.

View File

@ -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 {
@ -621,6 +613,7 @@ possible:
// 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
some complications because of how arrays are passed in the ABI.
@ -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);
}
}

View File

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

View File

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

49
libdevcore/Exceptions.cpp Normal file
View File

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

View File

@ -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; } }

View File

@ -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;
if (_settings.runPeephole)
{
PeepholeOptimiser peepOpt(m_items);
while (peepOpt.optimise())
count++;
if (!_enable)
continue;
}
// This only modifies PushTags, we have to run again to actually remove code.
if (_settings.runDeduplicate)
{
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
);

View File

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

View File

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

View File

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

View File

@ -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();
if (_varDecl.value)
{
boost::apply_visitor(*this, *_varDecl.value);
expectDeposit(expectedItems, height);
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));

View File

@ -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;
}

View File

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

View File

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

View File

@ -104,30 +104,19 @@ 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."
);
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)

View File

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

View File

@ -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. "

View File

@ -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;
}

View File

@ -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;
};
}

View File

@ -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,6 +731,9 @@ bool TypeChecker::visit(InlineAssembly const& _inlineAssembly)
}
else if (var->type()->sizeOnStack() != 1)
{
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,6 +1122,8 @@ bool TypeChecker::visit(Assignment const& _assignment)
_assignment.annotation().type = make_shared<TupleType>();
expectType(_assignment.rightHandSide(), *tupleType);
// 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()))

View File

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

View File

@ -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; }

View File

@ -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.");
}
}

View File

@ -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,12 +756,8 @@ 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 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.");
}
}

View File

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

View File

@ -124,13 +124,14 @@ 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), "");
solAssert(m_localVariables.count(&_declaration) && !m_localVariables[&_declaration].empty(), "");
m_localVariables[&_declaration].pop_back();
if (m_localVariables[&_declaration].empty())
m_localVariables.erase(&_declaration);
}
@ -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)

View File

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

View File

@ -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.");
}

View File

@ -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;
}

View File

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

View File

@ -174,14 +174,20 @@ bool AsmAnalyzer::operator()(assembly::Assignment const& _assignment)
bool AsmAnalyzer::operator()(assembly::VariableDeclaration const& _varDecl)
{
int const expectedItems = _varDecl.variables.size();
bool success = true;
int const numVariables = _varDecl.variables.size();
if (_varDecl.value)
{
int const stackHeight = m_stackHeight;
bool success = boost::apply_visitor(*this, *_varDecl.value);
if ((m_stackHeight - stackHeight) != expectedItems)
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)
{

View File

@ -347,10 +347,15 @@ assembly::VariableDeclaration Parser::parseVariableDeclaration()
else
break;
}
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;
}

View File

@ -128,8 +128,11 @@ string AsmPrinter::operator()(assembly::VariableDeclaration const& _variableDecl
),
", "
);
if (_variableDeclaration.value)
{
out += " := ";
out += boost::apply_visitor(*this, *_variableDeclaration.value);
}
return out;
}

View File

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

View File

@ -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,17 +424,19 @@ 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;
break;
default:
BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Illegal documentation type."));
}
// caches the result
if (!*doc)
doc->reset(new Json::Value(Natspec::documentation(*_contract.contract, _type)));
doc->reset(new Json::Value(Natspec::devDocumentation(*_contract.contract)));
break;
default:
solAssert(false, "Illegal documentation 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);
}

View File

@ -93,87 +93,116 @@ public:
m_errorList(),
m_errorReporter(m_errorList) {}
/// @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);
/// Sets path remappings in the format "context:prefix=target"
void setRemappings(std::vector<std::string> const& _remappings);
/// Resets the compiler to a state where the sources are not parsed or even removed.
void reset(bool _keepSources = false);
/// 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>{})
{
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.
void addSources(StringMap const& _nameContents, bool _isLibrary = false)
{
for (auto const& i: _nameContents) addSource(i.first, i.second, _isLibrary);
}
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;

View File

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

View File

@ -41,29 +41,29 @@ 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()
SourceLocation const& _location,
std::string const& _description
);
void declarationError(
SourceLocation const& _location,
SecondarySourceLocation const& _secondaryLocation = SecondarySourceLocation(),
std::string const& _description = std::string()
SecondarySourceLocation const& _secondaryLocation,
std::string const& _description
);
void declarationError(
SourceLocation const& _location,
std::string const& _description = std::string()
);
void declarationError(SourceLocation const& _location, std::string const& _description);
void fatalDeclarationError(SourceLocation const& _location, std::string const& _description);

View File

@ -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;
}

View File

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

View File

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

View File

@ -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,25 +285,28 @@ 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",
"",
"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)
{
errors.append(formatErrorWithException(
@ -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);

View File

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

View File

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

View File

@ -44,7 +44,7 @@
#include <libdevcore/Common.h>
#include <libsolidity/interface/Exceptions.h>
#include <libdevcore/UndefMacros.h>
#include <libsolidity/parsing/UndefMacros.h>
namespace dev
{

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -21,7 +21,6 @@
#if defined(_WIN32)
#include <windows.h>
#include "libdevcore/UndefMacros.h"
#else
#include <sys/types.h>
#include <sys/socket.h>

View File

@ -49,6 +49,8 @@ test_suite* init_unit_test_suite( int /*argc*/, char* /*argv*/[] )
"SolidityAuctionRegistrar",
"SolidityFixedFeeRegistrar",
"SolidityWallet",
"LLLERC20",
"LLLENS",
"LLLEndToEndTest",
"GasMeterTests",
"SolidityEndToEndTest",

View File

@ -28,26 +28,86 @@
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
output=$("$SOLC" "$f" 2>&1)
"$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" $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
@ -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

View File

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

View File

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

View File

@ -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];
}
}

View File

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

View File

@ -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;
}
}

View File

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

View File

@ -0,0 +1,3 @@
MultiSigWallet contracts, originally from
https://github.com/ConsenSys/MultiSigWallet

View File

@ -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];
}
}

View File

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

View File

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

View File

@ -0,0 +1,3 @@
CORION contracts, originally from
https://github.com/CORIONplatform/solidity

View File

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

View File

@ -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 arrays 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 its 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);
}

View File

@ -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 );
_;
}
}

View File

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

View File

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

View File

@ -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;
}
}

View File

@ -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 Modulhandlers 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 principals 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 principals 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 principals 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 senders address to the receivers 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 receivers 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);
}

View File

@ -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 clients 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 providers 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 Providers name.
@website Providers website
@country Providers country
@info Providers 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 admins 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 providers 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 Providers 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 theyve 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 providers 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 dont enter any address then the amount will be transfered to the callers 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 callers 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 providers address from the checked rounds.
@adminReward Admins 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 its 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);
}

View File

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

View File

@ -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;
}
}

View File

@ -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 (its 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 isnt 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 cant call this function, only a natural address.
*/
require( msg.sender == tx.origin ); _;
}
}

View File

@ -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 owners 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 owners 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 owners 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 callers address to receivers 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);
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

Some files were not shown because too many files have changed in this diff Show More