aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorchriseth <chris@ethereum.org>2017-07-05 18:28:15 +0800
committerchriseth <chris@ethereum.org>2017-07-05 18:39:55 +0800
commitac84b36144f746662e5ddb984d283e053c7d06ba (patch)
treef50ee438a384e60574a4c28ea32d2b6ae2315795
parent05a26fc98c1201057c618c536ca0537e456c9b15 (diff)
downloaddexon-solidity-ac84b36144f746662e5ddb984d283e053c7d06ba.tar
dexon-solidity-ac84b36144f746662e5ddb984d283e053c7d06ba.tar.gz
dexon-solidity-ac84b36144f746662e5ddb984d283e053c7d06ba.tar.bz2
dexon-solidity-ac84b36144f746662e5ddb984d283e053c7d06ba.tar.lz
dexon-solidity-ac84b36144f746662e5ddb984d283e053c7d06ba.tar.xz
dexon-solidity-ac84b36144f746662e5ddb984d283e053c7d06ba.tar.zst
dexon-solidity-ac84b36144f746662e5ddb984d283e053c7d06ba.zip
Added various contracts for testing.
-rwxr-xr-xscripts/tests.sh23
-rw-r--r--test/compilationTests/MultiSigWallet/Factory.sol28
-rw-r--r--test/compilationTests/MultiSigWallet/LICENSE674
-rw-r--r--test/compilationTests/MultiSigWallet/MultiSigWallet.sol366
-rw-r--r--test/compilationTests/MultiSigWallet/MultiSigWalletFactory.sol21
-rw-r--r--test/compilationTests/MultiSigWallet/MultiSigWalletWithDailyLimit.sol97
-rw-r--r--test/compilationTests/MultiSigWallet/MultiSigWalletWithDailyLimitFactory.sol22
-rw-r--r--test/compilationTests/MultiSigWallet/README.md3
-rw-r--r--test/compilationTests/MultiSigWallet/TestToken.sol76
-rw-r--r--test/compilationTests/README.md5
-rw-r--r--test/compilationTests/corion/LICENSE674
-rw-r--r--test/compilationTests/corion/README.md3
-rw-r--r--test/compilationTests/corion/announcementTypes.sol35
-rw-r--r--test/compilationTests/corion/ico.sol376
-rw-r--r--test/compilationTests/corion/module.sol143
-rw-r--r--test/compilationTests/corion/moduleHandler.sol448
-rw-r--r--test/compilationTests/corion/multiOwner.sol83
-rw-r--r--test/compilationTests/corion/owned.sol28
-rw-r--r--test/compilationTests/corion/premium.sol346
-rw-r--r--test/compilationTests/corion/provider.sol797
-rw-r--r--test/compilationTests/corion/publisher.sol278
-rw-r--r--test/compilationTests/corion/safeMath.sol33
-rw-r--r--test/compilationTests/corion/schelling.sol577
-rw-r--r--test/compilationTests/corion/token.sol518
-rw-r--r--test/compilationTests/corion/tokenDB.sol77
-rw-r--r--test/compilationTests/milestonetracker/LICENSE675
-rw-r--r--test/compilationTests/milestonetracker/MilestoneTracker.sol367
-rw-r--r--test/compilationTests/milestonetracker/README.md3
-rw-r--r--test/compilationTests/milestonetracker/RLP.sol416
-rw-r--r--test/compilationTests/stringutils/LICENSE201
-rw-r--r--test/compilationTests/stringutils/README.md4
-rw-r--r--test/compilationTests/stringutils/strings.sol709
-rw-r--r--test/compilationTests/zeppelin/Bounty.sol78
-rw-r--r--test/compilationTests/zeppelin/DayLimit.sol75
-rw-r--r--test/compilationTests/zeppelin/LICENSE22
-rw-r--r--test/compilationTests/zeppelin/LimitBalance.sol33
-rw-r--r--test/compilationTests/zeppelin/MultisigWallet.sol127
-rw-r--r--test/compilationTests/zeppelin/README.md3
-rw-r--r--test/compilationTests/zeppelin/ReentrancyGuard.sol34
-rw-r--r--test/compilationTests/zeppelin/crowdsale/CappedCrowdsale.sol33
-rw-r--r--test/compilationTests/zeppelin/crowdsale/Crowdsale.sol108
-rw-r--r--test/compilationTests/zeppelin/crowdsale/FinalizableCrowdsale.sol39
-rw-r--r--test/compilationTests/zeppelin/crowdsale/RefundVault.sol56
-rw-r--r--test/compilationTests/zeppelin/crowdsale/RefundableCrowdsale.sol59
-rw-r--r--test/compilationTests/zeppelin/lifecycle/Destructible.sol25
-rw-r--r--test/compilationTests/zeppelin/lifecycle/Migrations.sol21
-rw-r--r--test/compilationTests/zeppelin/lifecycle/Pausable.sol51
-rw-r--r--test/compilationTests/zeppelin/lifecycle/TokenDestructible.sol36
-rw-r--r--test/compilationTests/zeppelin/math/Math.sol24
-rw-r--r--test/compilationTests/zeppelin/math/SafeMath.sol32
-rw-r--r--test/compilationTests/zeppelin/ownership/Claimable.sol40
-rw-r--r--test/compilationTests/zeppelin/ownership/Contactable.sol21
-rw-r--r--test/compilationTests/zeppelin/ownership/DelayedClaimable.sol43
-rw-r--r--test/compilationTests/zeppelin/ownership/HasNoContracts.sol21
-rw-r--r--test/compilationTests/zeppelin/ownership/HasNoEther.sol44
-rw-r--r--test/compilationTests/zeppelin/ownership/HasNoTokens.sol34
-rw-r--r--test/compilationTests/zeppelin/ownership/Multisig.sol28
-rw-r--r--test/compilationTests/zeppelin/ownership/NoOwner.sol14
-rw-r--r--test/compilationTests/zeppelin/ownership/Ownable.sol43
-rw-r--r--test/compilationTests/zeppelin/ownership/Shareable.sol189
-rw-r--r--test/compilationTests/zeppelin/payment/PullPayment.sol50
-rw-r--r--test/compilationTests/zeppelin/token/BasicToken.sol37
-rw-r--r--test/compilationTests/zeppelin/token/ERC20.sol16
-rw-r--r--test/compilationTests/zeppelin/token/ERC20Basic.sol14
-rw-r--r--test/compilationTests/zeppelin/token/LimitedTransferToken.sol57
-rw-r--r--test/compilationTests/zeppelin/token/MintableToken.sol50
-rw-r--r--test/compilationTests/zeppelin/token/PausableToken.sol21
-rw-r--r--test/compilationTests/zeppelin/token/SimpleToken.sol28
-rw-r--r--test/compilationTests/zeppelin/token/StandardToken.sol65
-rw-r--r--test/compilationTests/zeppelin/token/TokenTimelock.sol41
-rw-r--r--test/compilationTests/zeppelin/token/VestedToken.sol248
71 files changed, 10063 insertions, 3 deletions
diff --git a/scripts/tests.sh b/scripts/tests.sh
index 6b76c154..64b4121f 100755
--- a/scripts/tests.sh
+++ b/scripts/tests.sh
@@ -30,13 +30,30 @@ set -e
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"
+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"
+ ../../../build/solc/solc --optimize \
+ --combined-json abi,asm,ast,bin,bin-runtime,clone-bin,compact-format,devdoc,hashes,interface,metadata,opcodes,srcmap,srcmap-runtime,userdoc \
+ *.sol */*.sol > /dev/null 2>&1
+ cd ..
+ fi
+done
+)
+
+echo "Running commandline tests..."
+"$REPO_ROOT/test/cmdlineTests.sh"
+
# This conditional is only needed because we don't have a working Homebrew
# install for `eth` at the time of writing, so we unzip the ZIP file locally
# instead. This will go away soon.
diff --git a/test/compilationTests/MultiSigWallet/Factory.sol b/test/compilationTests/MultiSigWallet/Factory.sol
new file mode 100644
index 00000000..f1be6884
--- /dev/null
+++ b/test/compilationTests/MultiSigWallet/Factory.sol
@@ -0,0 +1,28 @@
+contract Factory {
+
+ event ContractInstantiation(address sender, address instantiation);
+
+ mapping(address => bool) public isInstantiation;
+ mapping(address => address[]) public instantiations;
+
+ /// @dev Returns number of instantiations by creator.
+ /// @param creator Contract creator.
+ /// @return Returns number of instantiations by creator.
+ function getInstantiationCount(address creator)
+ public
+ constant
+ returns (uint)
+ {
+ return instantiations[creator].length;
+ }
+
+ /// @dev Registers contract in factory registry.
+ /// @param instantiation Address of contract instantiation.
+ function register(address instantiation)
+ internal
+ {
+ isInstantiation[instantiation] = true;
+ instantiations[msg.sender].push(instantiation);
+ ContractInstantiation(msg.sender, instantiation);
+ }
+}
diff --git a/test/compilationTests/MultiSigWallet/LICENSE b/test/compilationTests/MultiSigWallet/LICENSE
new file mode 100644
index 00000000..94a9ed02
--- /dev/null
+++ b/test/compilationTests/MultiSigWallet/LICENSE
@@ -0,0 +1,674 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users. We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors. You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
+
+ Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+ For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+ Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so. This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software. The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products. If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+ Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary. To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Use with the GNU Affero General Public License.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+ <one line to give the program's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+ <program> Copyright (C) <year> <name of author>
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+<http://www.gnu.org/licenses/>.
+
+ The GNU General Public License does not permit incorporating your program
+into proprietary programs. If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License. But first, please read
+<http://www.gnu.org/philosophy/why-not-lgpl.html>.
diff --git a/test/compilationTests/MultiSigWallet/MultiSigWallet.sol b/test/compilationTests/MultiSigWallet/MultiSigWallet.sol
new file mode 100644
index 00000000..a6f67c7a
--- /dev/null
+++ b/test/compilationTests/MultiSigWallet/MultiSigWallet.sol
@@ -0,0 +1,366 @@
+pragma solidity ^0.4.4;
+
+
+/// @title Multisignature wallet - Allows multiple parties to agree on transactions before execution.
+/// @author Stefan George - <stefan.george@consensys.net>
+contract MultiSigWallet {
+
+ uint constant public MAX_OWNER_COUNT = 50;
+
+ event Confirmation(address indexed sender, uint indexed transactionId);
+ event Revocation(address indexed sender, uint indexed transactionId);
+ event Submission(uint indexed transactionId);
+ event Execution(uint indexed transactionId);
+ event ExecutionFailure(uint indexed transactionId);
+ event Deposit(address indexed sender, uint value);
+ event OwnerAddition(address indexed owner);
+ event OwnerRemoval(address indexed owner);
+ event RequirementChange(uint required);
+
+ mapping (uint => Transaction) public transactions;
+ mapping (uint => mapping (address => bool)) public confirmations;
+ mapping (address => bool) public isOwner;
+ address[] public owners;
+ uint public required;
+ uint public transactionCount;
+
+ struct Transaction {
+ address destination;
+ uint value;
+ bytes data;
+ bool executed;
+ }
+
+ modifier onlyWallet() {
+ if (msg.sender != address(this))
+ throw;
+ _;
+ }
+
+ modifier ownerDoesNotExist(address owner) {
+ if (isOwner[owner])
+ throw;
+ _;
+ }
+
+ modifier ownerExists(address owner) {
+ if (!isOwner[owner])
+ throw;
+ _;
+ }
+
+ modifier transactionExists(uint transactionId) {
+ if (transactions[transactionId].destination == 0)
+ throw;
+ _;
+ }
+
+ modifier confirmed(uint transactionId, address owner) {
+ if (!confirmations[transactionId][owner])
+ throw;
+ _;
+ }
+
+ modifier notConfirmed(uint transactionId, address owner) {
+ if (confirmations[transactionId][owner])
+ throw;
+ _;
+ }
+
+ modifier notExecuted(uint transactionId) {
+ if (transactions[transactionId].executed)
+ throw;
+ _;
+ }
+
+ modifier notNull(address _address) {
+ if (_address == 0)
+ throw;
+ _;
+ }
+
+ modifier validRequirement(uint ownerCount, uint _required) {
+ if ( ownerCount > MAX_OWNER_COUNT
+ || _required > ownerCount
+ || _required == 0
+ || ownerCount == 0)
+ throw;
+ _;
+ }
+
+ /// @dev Fallback function allows to deposit ether.
+ function()
+ payable
+ {
+ if (msg.value > 0)
+ Deposit(msg.sender, msg.value);
+ }
+
+ /*
+ * Public functions
+ */
+ /// @dev Contract constructor sets initial owners and required number of confirmations.
+ /// @param _owners List of initial owners.
+ /// @param _required Number of required confirmations.
+ function MultiSigWallet(address[] _owners, uint _required)
+ public
+ validRequirement(_owners.length, _required)
+ {
+ for (uint i=0; i<_owners.length; i++) {
+ if (isOwner[_owners[i]] || _owners[i] == 0)
+ throw;
+ isOwner[_owners[i]] = true;
+ }
+ owners = _owners;
+ required = _required;
+ }
+
+ /// @dev Allows to add a new owner. Transaction has to be sent by wallet.
+ /// @param owner Address of new owner.
+ function addOwner(address owner)
+ public
+ onlyWallet
+ ownerDoesNotExist(owner)
+ notNull(owner)
+ validRequirement(owners.length + 1, required)
+ {
+ isOwner[owner] = true;
+ owners.push(owner);
+ OwnerAddition(owner);
+ }
+
+ /// @dev Allows to remove an owner. Transaction has to be sent by wallet.
+ /// @param owner Address of owner.
+ function removeOwner(address owner)
+ public
+ onlyWallet
+ ownerExists(owner)
+ {
+ isOwner[owner] = false;
+ for (uint i=0; i<owners.length - 1; i++)
+ if (owners[i] == owner) {
+ owners[i] = owners[owners.length - 1];
+ break;
+ }
+ owners.length -= 1;
+ if (required > owners.length)
+ changeRequirement(owners.length);
+ OwnerRemoval(owner);
+ }
+
+ /// @dev Allows to replace an owner with a new owner. Transaction has to be sent by wallet.
+ /// @param owner Address of owner to be replaced.
+ /// @param owner Address of new owner.
+ function replaceOwner(address owner, address newOwner)
+ public
+ onlyWallet
+ ownerExists(owner)
+ ownerDoesNotExist(newOwner)
+ {
+ for (uint i=0; i<owners.length; i++)
+ if (owners[i] == owner) {
+ owners[i] = newOwner;
+ break;
+ }
+ isOwner[owner] = false;
+ isOwner[newOwner] = true;
+ OwnerRemoval(owner);
+ OwnerAddition(newOwner);
+ }
+
+ /// @dev Allows to change the number of required confirmations. Transaction has to be sent by wallet.
+ /// @param _required Number of required confirmations.
+ function changeRequirement(uint _required)
+ public
+ onlyWallet
+ validRequirement(owners.length, _required)
+ {
+ required = _required;
+ RequirementChange(_required);
+ }
+
+ /// @dev Allows an owner to submit and confirm a transaction.
+ /// @param destination Transaction target address.
+ /// @param value Transaction ether value.
+ /// @param data Transaction data payload.
+ /// @return Returns transaction ID.
+ function submitTransaction(address destination, uint value, bytes data)
+ public
+ returns (uint transactionId)
+ {
+ transactionId = addTransaction(destination, value, data);
+ confirmTransaction(transactionId);
+ }
+
+ /// @dev Allows an owner to confirm a transaction.
+ /// @param transactionId Transaction ID.
+ function confirmTransaction(uint transactionId)
+ public
+ ownerExists(msg.sender)
+ transactionExists(transactionId)
+ notConfirmed(transactionId, msg.sender)
+ {
+ confirmations[transactionId][msg.sender] = true;
+ Confirmation(msg.sender, transactionId);
+ executeTransaction(transactionId);
+ }
+
+ /// @dev Allows an owner to revoke a confirmation for a transaction.
+ /// @param transactionId Transaction ID.
+ function revokeConfirmation(uint transactionId)
+ public
+ ownerExists(msg.sender)
+ confirmed(transactionId, msg.sender)
+ notExecuted(transactionId)
+ {
+ confirmations[transactionId][msg.sender] = false;
+ Revocation(msg.sender, transactionId);
+ }
+
+ /// @dev Allows anyone to execute a confirmed transaction.
+ /// @param transactionId Transaction ID.
+ function executeTransaction(uint transactionId)
+ public
+ notExecuted(transactionId)
+ {
+ if (isConfirmed(transactionId)) {
+ Transaction tx = transactions[transactionId];
+ tx.executed = true;
+ if (tx.destination.call.value(tx.value)(tx.data))
+ Execution(transactionId);
+ else {
+ ExecutionFailure(transactionId);
+ tx.executed = false;
+ }
+ }
+ }
+
+ /// @dev Returns the confirmation status of a transaction.
+ /// @param transactionId Transaction ID.
+ /// @return Confirmation status.
+ function isConfirmed(uint transactionId)
+ public
+ constant
+ returns (bool)
+ {
+ uint count = 0;
+ for (uint i=0; i<owners.length; i++) {
+ if (confirmations[transactionId][owners[i]])
+ count += 1;
+ if (count == required)
+ return true;
+ }
+ }
+
+ /*
+ * Internal functions
+ */
+ /// @dev Adds a new transaction to the transaction mapping, if transaction does not exist yet.
+ /// @param destination Transaction target address.
+ /// @param value Transaction ether value.
+ /// @param data Transaction data payload.
+ /// @return Returns transaction ID.
+ function addTransaction(address destination, uint value, bytes data)
+ internal
+ notNull(destination)
+ returns (uint transactionId)
+ {
+ transactionId = transactionCount;
+ transactions[transactionId] = Transaction({
+ destination: destination,
+ value: value,
+ data: data,
+ executed: false
+ });
+ transactionCount += 1;
+ Submission(transactionId);
+ }
+
+ /*
+ * Web3 call functions
+ */
+ /// @dev Returns number of confirmations of a transaction.
+ /// @param transactionId Transaction ID.
+ /// @return Number of confirmations.
+ function getConfirmationCount(uint transactionId)
+ public
+ constant
+ returns (uint count)
+ {
+ for (uint i=0; i<owners.length; i++)
+ if (confirmations[transactionId][owners[i]])
+ count += 1;
+ }
+
+ /// @dev Returns total number of transactions after filers are applied.
+ /// @param pending Include pending transactions.
+ /// @param executed Include executed transactions.
+ /// @return Total number of transactions after filters are applied.
+ function getTransactionCount(bool pending, bool executed)
+ public
+ constant
+ returns (uint count)
+ {
+ for (uint i=0; i<transactionCount; i++)
+ if ( pending && !transactions[i].executed
+ || executed && transactions[i].executed)
+ count += 1;
+ }
+
+ /// @dev Returns list of owners.
+ /// @return List of owner addresses.
+ function getOwners()
+ public
+ constant
+ returns (address[])
+ {
+ return owners;
+ }
+
+ /// @dev Returns array with owner addresses, which confirmed transaction.
+ /// @param transactionId Transaction ID.
+ /// @return Returns array of owner addresses.
+ function getConfirmations(uint transactionId)
+ public
+ constant
+ returns (address[] _confirmations)
+ {
+ address[] memory confirmationsTemp = new address[](owners.length);
+ uint count = 0;
+ uint i;
+ for (i=0; i<owners.length; i++)
+ if (confirmations[transactionId][owners[i]]) {
+ confirmationsTemp[count] = owners[i];
+ count += 1;
+ }
+ _confirmations = new address[](count);
+ for (i=0; i<count; i++)
+ _confirmations[i] = confirmationsTemp[i];
+ }
+
+ /// @dev Returns list of transaction IDs in defined range.
+ /// @param from Index start position of transaction array.
+ /// @param to Index end position of transaction array.
+ /// @param pending Include pending transactions.
+ /// @param executed Include executed transactions.
+ /// @return Returns array of transaction IDs.
+ function getTransactionIds(uint from, uint to, bool pending, bool executed)
+ public
+ constant
+ returns (uint[] _transactionIds)
+ {
+ uint[] memory transactionIdsTemp = new uint[](transactionCount);
+ uint count = 0;
+ uint i;
+ for (i=0; i<transactionCount; i++)
+ if ( pending && !transactions[i].executed
+ || executed && transactions[i].executed)
+ {
+ transactionIdsTemp[count] = i;
+ count += 1;
+ }
+ _transactionIds = new uint[](to - from);
+ for (i=from; i<to; i++)
+ _transactionIds[i - from] = transactionIdsTemp[i];
+ }
+}
diff --git a/test/compilationTests/MultiSigWallet/MultiSigWalletFactory.sol b/test/compilationTests/MultiSigWallet/MultiSigWalletFactory.sol
new file mode 100644
index 00000000..cb58ab1c
--- /dev/null
+++ b/test/compilationTests/MultiSigWallet/MultiSigWalletFactory.sol
@@ -0,0 +1,21 @@
+pragma solidity ^0.4.4;
+import "Factory.sol";
+import "MultiSigWallet.sol";
+
+
+/// @title Multisignature wallet factory - Allows creation of multisig wallet.
+/// @author Stefan George - <stefan.george@consensys.net>
+contract MultiSigWalletFactory is Factory {
+
+ /// @dev Allows verified creation of multisignature wallet.
+ /// @param _owners List of initial owners.
+ /// @param _required Number of required confirmations.
+ /// @return Returns wallet address.
+ function create(address[] _owners, uint _required)
+ public
+ returns (address wallet)
+ {
+ wallet = new MultiSigWallet(_owners, _required);
+ register(wallet);
+ }
+}
diff --git a/test/compilationTests/MultiSigWallet/MultiSigWalletWithDailyLimit.sol b/test/compilationTests/MultiSigWallet/MultiSigWalletWithDailyLimit.sol
new file mode 100644
index 00000000..024d3ef4
--- /dev/null
+++ b/test/compilationTests/MultiSigWallet/MultiSigWalletWithDailyLimit.sol
@@ -0,0 +1,97 @@
+pragma solidity ^0.4.4;
+import "MultiSigWallet.sol";
+
+
+/// @title Multisignature wallet with daily limit - Allows an owner to withdraw a daily limit without multisig.
+/// @author Stefan George - <stefan.george@consensys.net>
+contract MultiSigWalletWithDailyLimit is MultiSigWallet {
+
+ event DailyLimitChange(uint dailyLimit);
+
+ uint public dailyLimit;
+ uint public lastDay;
+ uint public spentToday;
+
+ /*
+ * Public functions
+ */
+ /// @dev Contract constructor sets initial owners, required number of confirmations and daily withdraw limit.
+ /// @param _owners List of initial owners.
+ /// @param _required Number of required confirmations.
+ /// @param _dailyLimit Amount in wei, which can be withdrawn without confirmations on a daily basis.
+ function MultiSigWalletWithDailyLimit(address[] _owners, uint _required, uint _dailyLimit)
+ public
+ MultiSigWallet(_owners, _required)
+ {
+ dailyLimit = _dailyLimit;
+ }
+
+ /// @dev Allows to change the daily limit. Transaction has to be sent by wallet.
+ /// @param _dailyLimit Amount in wei.
+ function changeDailyLimit(uint _dailyLimit)
+ public
+ onlyWallet
+ {
+ dailyLimit = _dailyLimit;
+ DailyLimitChange(_dailyLimit);
+ }
+
+ /// @dev Allows anyone to execute a confirmed transaction or ether withdraws until daily limit is reached.
+ /// @param transactionId Transaction ID.
+ function executeTransaction(uint transactionId)
+ public
+ notExecuted(transactionId)
+ {
+ Transaction tx = transactions[transactionId];
+ bool confirmed = isConfirmed(transactionId);
+ if (confirmed || tx.data.length == 0 && isUnderLimit(tx.value)) {
+ tx.executed = true;
+ if (!confirmed)
+ spentToday += tx.value;
+ if (tx.destination.call.value(tx.value)(tx.data))
+ Execution(transactionId);
+ else {
+ ExecutionFailure(transactionId);
+ tx.executed = false;
+ if (!confirmed)
+ spentToday -= tx.value;
+ }
+ }
+ }
+
+ /*
+ * Internal functions
+ */
+ /// @dev Returns if amount is within daily limit and resets spentToday after one day.
+ /// @param amount Amount to withdraw.
+ /// @return Returns if amount is under daily limit.
+ function isUnderLimit(uint amount)
+ internal
+ returns (bool)
+ {
+ if (now > lastDay + 24 hours) {
+ lastDay = now;
+ spentToday = 0;
+ }
+ if (spentToday + amount > dailyLimit || spentToday + amount < spentToday)
+ return false;
+ return true;
+ }
+
+ /*
+ * Web3 call functions
+ */
+ /// @dev Returns maximum withdraw amount.
+ /// @return Returns amount.
+ function calcMaxWithdraw()
+ public
+ constant
+ returns (uint)
+ {
+ if (now > lastDay + 24 hours)
+ return dailyLimit;
+ if (dailyLimit < spentToday)
+ return 0;
+ return dailyLimit - spentToday;
+ }
+}
diff --git a/test/compilationTests/MultiSigWallet/MultiSigWalletWithDailyLimitFactory.sol b/test/compilationTests/MultiSigWallet/MultiSigWalletWithDailyLimitFactory.sol
new file mode 100644
index 00000000..8a2efa32
--- /dev/null
+++ b/test/compilationTests/MultiSigWallet/MultiSigWalletWithDailyLimitFactory.sol
@@ -0,0 +1,22 @@
+pragma solidity ^0.4.4;
+import "Factory.sol";
+import "MultiSigWalletWithDailyLimit.sol";
+
+
+/// @title Multisignature wallet factory for daily limit version - Allows creation of multisig wallet.
+/// @author Stefan George - <stefan.george@consensys.net>
+contract MultiSigWalletWithDailyLimitFactory is Factory {
+
+ /// @dev Allows verified creation of multisignature wallet.
+ /// @param _owners List of initial owners.
+ /// @param _required Number of required confirmations.
+ /// @param _dailyLimit Amount in wei, which can be withdrawn without confirmations on a daily basis.
+ /// @return Returns wallet address.
+ function create(address[] _owners, uint _required, uint _dailyLimit)
+ public
+ returns (address wallet)
+ {
+ wallet = new MultiSigWalletWithDailyLimit(_owners, _required, _dailyLimit);
+ register(wallet);
+ }
+}
diff --git a/test/compilationTests/MultiSigWallet/README.md b/test/compilationTests/MultiSigWallet/README.md
new file mode 100644
index 00000000..2d96f3a1
--- /dev/null
+++ b/test/compilationTests/MultiSigWallet/README.md
@@ -0,0 +1,3 @@
+MultiSigWallet contracts, originally from
+
+https://github.com/ConsenSys/MultiSigWallet
diff --git a/test/compilationTests/MultiSigWallet/TestToken.sol b/test/compilationTests/MultiSigWallet/TestToken.sol
new file mode 100644
index 00000000..0f6cd20e
--- /dev/null
+++ b/test/compilationTests/MultiSigWallet/TestToken.sol
@@ -0,0 +1,76 @@
+pragma solidity ^0.4.4;
+
+
+/// @title Test token contract - Allows testing of token transfers with multisig wallet.
+contract TestToken {
+
+ event Transfer(address indexed from, address indexed to, uint256 value);
+ event Approval(address indexed owner, address indexed spender, uint256 value);
+
+ mapping (address => uint256) balances;
+ mapping (address => mapping (address => uint256)) allowed;
+ uint256 public totalSupply;
+
+ string constant public name = "Test Token";
+ string constant public symbol = "TT";
+ uint8 constant public decimals = 1;
+
+ function issueTokens(address _to, uint256 _value)
+ public
+ {
+ balances[_to] += _value;
+ totalSupply += _value;
+ }
+
+ function transfer(address _to, uint256 _value)
+ public
+ returns (bool success)
+ {
+ if (balances[msg.sender] < _value) {
+ throw;
+ }
+ balances[msg.sender] -= _value;
+ balances[_to] += _value;
+ Transfer(msg.sender, _to, _value);
+ return true;
+ }
+
+ function transferFrom(address _from, address _to, uint256 _value)
+ public
+ returns (bool success)
+ {
+ if (balances[_from] < _value || allowed[_from][msg.sender] < _value) {
+ throw;
+ }
+ balances[_to] += _value;
+ balances[_from] -= _value;
+ allowed[_from][msg.sender] -= _value;
+ Transfer(_from, _to, _value);
+ return true;
+ }
+
+ function approve(address _spender, uint256 _value)
+ public
+ returns (bool success)
+ {
+ allowed[msg.sender][_spender] = _value;
+ Approval(msg.sender, _spender, _value);
+ return true;
+ }
+
+ function allowance(address _owner, address _spender)
+ constant
+ public
+ returns (uint256 remaining)
+ {
+ return allowed[_owner][_spender];
+ }
+
+ function balanceOf(address _owner)
+ constant
+ public
+ returns (uint256 balance)
+ {
+ return balances[_owner];
+ }
+}
diff --git a/test/compilationTests/README.md b/test/compilationTests/README.md
new file mode 100644
index 00000000..c827b348
--- /dev/null
+++ b/test/compilationTests/README.md
@@ -0,0 +1,5 @@
+This directory contains various Solidity contract source code files
+that are compiled as part of the regular tests.
+
+These contracts are externally contributed and their presence in this
+repository does not make any statement about their quality or usefulness.
diff --git a/test/compilationTests/corion/LICENSE b/test/compilationTests/corion/LICENSE
new file mode 100644
index 00000000..9cecc1d4
--- /dev/null
+++ b/test/compilationTests/corion/LICENSE
@@ -0,0 +1,674 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users. We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors. You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
+
+ Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+ For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+ Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so. This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software. The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products. If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+ Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary. To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Use with the GNU Affero General Public License.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+ {one line to give the program's name and a brief idea of what it does.}
+ Copyright (C) {year} {name of author}
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+ {project} Copyright (C) {year} {fullname}
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+<http://www.gnu.org/licenses/>.
+
+ The GNU General Public License does not permit incorporating your program
+into proprietary programs. If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License. But first, please read
+<http://www.gnu.org/philosophy/why-not-lgpl.html>.
diff --git a/test/compilationTests/corion/README.md b/test/compilationTests/corion/README.md
new file mode 100644
index 00000000..f0bb8ea8
--- /dev/null
+++ b/test/compilationTests/corion/README.md
@@ -0,0 +1,3 @@
+CORION contracts, originally from
+
+https://github.com/CORIONplatform/solidity
diff --git a/test/compilationTests/corion/announcementTypes.sol b/test/compilationTests/corion/announcementTypes.sol
new file mode 100644
index 00000000..f31d580e
--- /dev/null
+++ b/test/compilationTests/corion/announcementTypes.sol
@@ -0,0 +1,35 @@
+pragma solidity ^0.4.11;
+
+contract announcementTypes {
+
+ enum announcementType {
+ /*
+ type of announcements
+ */
+ newModule,
+ dropModule,
+ replaceModule,
+ replaceModuleHandler,
+ question,
+ transactionFeeRate,
+ transactionFeeMin,
+ transactionFeeMax,
+ transactionFeeBurn,
+ providerPublicFunds,
+ providerPrivateFunds,
+ providerPrivateClientLimit,
+ providerPublicMinRate,
+ providerPublicMaxRate,
+ providerPrivateMinRate,
+ providerPrivateMaxRate,
+ providerGasProtect,
+ providerInterestMinFunds,
+ providerRentRate,
+ schellingRoundBlockDelay,
+ schellingCheckRounds,
+ schellingCheckAboves,
+ schellingRate,
+ publisherMinAnnouncementDelay,
+ publisherOppositeRate
+ }
+} \ No newline at end of file
diff --git a/test/compilationTests/corion/ico.sol b/test/compilationTests/corion/ico.sol
new file mode 100644
index 00000000..6c9f8cb2
--- /dev/null
+++ b/test/compilationTests/corion/ico.sol
@@ -0,0 +1,376 @@
+pragma solidity ^0.4.11;
+
+import "./safeMath.sol";
+import "./token.sol";
+import "./premium.sol";
+import "./moduleHandler.sol";
+
+contract ico is safeMath {
+
+ struct icoLevels_s {
+ uint256 block;
+ uint8 rate;
+ }
+ struct affiliate_s {
+ uint256 weight;
+ uint256 paid;
+ }
+ struct interest_s {
+ uint256 amount;
+ bool empty;
+ }
+ struct brought_s {
+ uint256 eth;
+ uint256 cor;
+ uint256 corp;
+ }
+
+ uint256 constant oneSegment = 40320;
+
+ address public owner;
+ address public tokenAddr;
+ address public premiumAddr;
+ uint256 public startBlock;
+ uint256 public icoDelay;
+ address public foundationAddress;
+ address public icoEtcPriceAddr;
+ uint256 public icoExchangeRate;
+ uint256 public icoExchangeRateSetBlock;
+ uint256 constant icoExchangeRateM = 1e4;
+ uint256 constant interestOnICO = 25;
+ uint256 constant interestOnICOM = 1e3;
+ uint256 constant interestBlockDelay = 720;
+ uint256 constant exchangeRateDelay = 125;
+ bool public aborted;
+ bool public closed;
+ icoLevels_s[] public icoLevels;
+ mapping (address => affiliate_s) public affiliate;
+ mapping (address => brought_s) public brought;
+ mapping (address => mapping(uint256 => interest_s)) public interestDB;
+ uint256 public totalMint;
+ uint256 public totalPremiumMint;
+
+ function ico(address foundation, address priceSet, uint256 exchangeRate, uint256 startBlockNum, address[] genesisAddr, uint256[] genesisValue) {
+ /*
+ Installation function.
+
+ @foundation The ETC address of the foundation
+ @priceSet The address which will be able to make changes on the rate later on.
+ @exchangeRate The current ETC/USD rate multiplied by 1e4. For example: 2.5 USD/ETC = 25000
+ @startBlockNum The height (level) of the beginning of the ICO. If it is 0 then it will be the current array’s height.
+ @genesisAddr Array of Genesis addresses
+ @genesisValue Array of balance of genesis addresses
+ */
+ foundationAddress = foundation;
+ icoExchangeRate = exchangeRate;
+ icoExchangeRateSetBlock = block.number + exchangeRateDelay;
+ icoEtcPriceAddr = priceSet;
+ owner = msg.sender;
+ if ( startBlockNum > 0 ) {
+ require( startBlockNum >= block.number );
+ startBlock = startBlockNum;
+ } else {
+ startBlock = block.number;
+ }
+ icoLevels.push(icoLevels_s(startBlock + oneSegment * 1, 3));
+ icoLevels.push(icoLevels_s(startBlock + oneSegment / 7, 5));
+ icoLevels.push(icoLevels_s(startBlock, 10));
+ icoDelay = startBlock + oneSegment * 3;
+ for ( uint256 a=0 ; a<genesisAddr.length ; a++ ) {
+ interestDB[genesisAddr[a]][0].amount = genesisValue[a];
+ }
+ }
+
+ function ICObonus() public constant returns(uint256 bonus) {
+ /*
+ Query of current bonus
+
+ @bonus Bonus %
+ */
+ for ( uint8 a=0 ; a<icoLevels.length ; a++ ) {
+ if ( block.number > icoLevels[a].block ) {
+ return icoLevels[a].rate;
+ }
+ }
+ }
+
+ function setInterestDB(address addr, uint256 balance) external returns(bool success) {
+ /*
+ Setting interest database. It can be requested by Token contract only.
+ A database has to be built in order that after ICO closed everybody can get their compound interest on their capital accumulated
+
+ @addr Sender
+ @balance Quantity
+
+ @success Was the process successful or not
+ */
+ require( msg.sender == tokenAddr );
+ uint256 _num = (block.number - startBlock) / interestBlockDelay;
+ interestDB[addr][_num].amount = balance;
+ if ( balance == 0 ) {
+ interestDB[addr][_num].empty = true;
+ }
+ return true;
+ }
+
+ function checkInterest(address addr) public constant returns(uint256 amount) {
+ /*
+ Query of compound interest
+
+ @addr Address
+
+ @amount Amount of compound interest
+ */
+ uint256 _lastBal;
+ uint256 _tamount;
+ bool _empty;
+ interest_s memory _idb;
+ uint256 _to = (block.number - startBlock) / interestBlockDelay;
+
+ if ( _to == 0 || aborted ) { return 0; }
+
+ for ( uint256 r=0 ; r < _to ; r++ ) {
+ if ( r*interestBlockDelay+startBlock >= icoDelay ) { break; }
+ _idb = interestDB[addr][r];
+ if ( _idb.amount > 0 ) {
+ if ( _empty ) {
+ _lastBal = _idb.amount + amount;
+ } else {
+ _lastBal = _idb.amount;
+ }
+ }
+ if ( _idb.empty ) {
+ _lastBal = 0;
+ _empty = _idb.empty;
+ }
+ _lastBal += _tamount;
+ _tamount = _lastBal * interestOnICO / interestOnICOM / 100;
+ amount += _tamount;
+ }
+ }
+
+ function getInterest(address beneficiary) external {
+ /*
+ Request of compound interest. This is deleted from the database after the ICO closed and following the query of the compound interest.
+
+ @beneficiary Beneficiary who will receive the interest
+ */
+ uint256 _lastBal;
+ uint256 _tamount;
+ uint256 _amount;
+ bool _empty;
+ interest_s memory _idb;
+ address _addr = beneficiary;
+ uint256 _to = (block.number - startBlock) / interestBlockDelay;
+ if ( _addr == 0x00 ) { _addr = msg.sender; }
+
+ require( block.number > icoDelay );
+ require( ! aborted );
+
+ for ( uint256 r=0 ; r < _to ; r++ ) {
+ if ( r*interestBlockDelay+startBlock >= icoDelay ) { break; }
+ _idb = interestDB[msg.sender][r];
+ if ( _idb.amount > 0 ) {
+ if ( _empty ) {
+ _lastBal = _idb.amount + _amount;
+ } else {
+ _lastBal = _idb.amount;
+ }
+ }
+ if ( _idb.empty ) {
+ _lastBal = 0;
+ _empty = _idb.empty;
+ }
+ _lastBal += _tamount;
+ _tamount = _lastBal * interestOnICO / interestOnICOM / 100;
+ _amount += _tamount;
+ delete interestDB[msg.sender][r];
+ }
+
+ require( _amount > 0 );
+ token(tokenAddr).mint(_addr, _amount);
+ }
+
+ function setICOEthPrice(uint256 value) external {
+ /*
+ Setting of the ICO ETC USD rates which can only be calle by a pre-defined address.
+ After this function is completed till the call of the next function (which is at least an exchangeRateDelay array) this rate counts.
+ With this process avoiding the sudden rate changes.
+
+ @value The ETC/USD rate multiplied by 1e4. For example: 2.5 USD/ETC = 25000
+ */
+ require( isICO() );
+ require( icoEtcPriceAddr == msg.sender );
+ require( icoExchangeRateSetBlock < block.number);
+ icoExchangeRateSetBlock = block.number + exchangeRateDelay;
+ icoExchangeRate = value;
+ }
+
+ function extendICO() external {
+ /*
+ Extend the period of the ICO with one segment.
+
+ It is only possible during the ICO and only callable by the owner.
+ */
+ require( isICO() );
+ require( msg.sender == owner );
+ icoDelay += oneSegment;
+ }
+
+ function closeICO() external {
+ /*
+ Closing the ICO.
+ It is only possible when the ICO period passed and only by the owner.
+ The 96% of the whole amount of the token is generated to the address of the fundation.
+ Ethers which are situated in this contract will be sent to the address of the fundation.
+ */
+ require( msg.sender == owner );
+ require( block.number > icoDelay );
+ require( ! closed );
+ closed = true;
+ require( ! aborted );
+ require( token(tokenAddr).mint(foundationAddress, token(tokenAddr).totalSupply() * 96 / 100) );
+ require( premium(premiumAddr).mint(foundationAddress, totalMint / 5000 - totalPremiumMint) );
+ require( foundationAddress.send(this.balance) );
+ require( token(tokenAddr).closeIco() );
+ require( premium(premiumAddr).closeIco() );
+ }
+
+ function abortICO() external {
+ /*
+ Withdrawal of the ICO.
+ It is only possible during the ICO period.
+ Only callable by the owner.
+ After this process only the receiveFunds function will be available for the customers.
+ */
+ require( isICO() );
+ require( msg.sender == owner );
+ aborted = true;
+ }
+
+ function connectTokens(address tokenContractAddr, address premiumContractAddr) external {
+ /*
+ Installation function which joins the two token contracts with this contract.
+ Only callable by the owner
+
+ @tokenContractAddr Address of the corion token contract.
+ @premiumContractAddr Address of the corion premium token contract
+ */
+ require( msg.sender == owner );
+ require( tokenAddr == 0x00 && premiumAddr == 0x00 );
+ tokenAddr = tokenContractAddr;
+ premiumAddr = premiumContractAddr;
+ }
+
+ function receiveFunds() external {
+ /*
+ Refund the amount which was purchased during the ICO period.
+ This one is only callable if the ICO is withdrawn.
+ In this case the address gets back the 90% of the amount which was spent for token during the ICO period.
+ */
+ require( aborted );
+ require( brought[msg.sender].eth > 0 );
+ uint256 _val = brought[msg.sender].eth * 90 / 100;
+ delete brought[msg.sender];
+ require( msg.sender.send(_val) );
+ }
+
+ function () payable {
+ /*
+ Callback function. Simply calls the buy function as a beneficiary and there is no affilate address.
+ If they call the contract without any function then this process will be taken place.
+ */
+ require( isICO() );
+ require( buy(msg.sender, 0x00) );
+ }
+
+ function buy(address beneficiaryAddress, address affilateAddress) payable returns (bool success) {
+ /*
+ Buying a token
+
+ If there is not at least 0.2 ether balance on the beneficiaryAddress then the amount of the ether which was intended for the purchase will be reduced by 0.2 and that will be sent to the address of the beneficiary.
+ From the remaining amount calculate the reward with the help of the getIcoReward function.
+ Only that affilate address is valid which has some token on it’s account.
+ If there is a valid affilate address then calculate and credit the reward as well in the following way:
+ With more than 1e12 token contract credit 5% reward based on the calculation that how many tokens did they buy when he was added as an affilate.
+ More than 1e11 token: 4%
+ More than 1e10 token: 3%
+ More than 1e9 token: 2% below 1%
+ @beneficiaryAddress The address of the accredited where the token will be sent.
+ @affilateAddress The address of the person who offered who will get the referral reward. It can not be equal with the beneficiaryAddress.
+ */
+ require( isICO() );
+ if ( beneficiaryAddress == 0x00) { beneficiaryAddress = msg.sender; }
+ if ( beneficiaryAddress == affilateAddress ) {
+ affilateAddress = 0x00;
+ }
+ uint256 _value = msg.value;
+ if ( beneficiaryAddress.balance < 0.2 ether ) {
+ require( beneficiaryAddress.send(0.2 ether) );
+ _value = safeSub(_value, 0.2 ether);
+ }
+ var _reward = getIcoReward(_value);
+ require( _reward > 0 );
+ require( token(tokenAddr).mint(beneficiaryAddress, _reward) );
+ brought[beneficiaryAddress].eth = safeAdd(brought[beneficiaryAddress].eth, _value);
+ brought[beneficiaryAddress].cor = safeAdd(brought[beneficiaryAddress].cor, _reward);
+ totalMint = safeAdd(totalMint, _reward);
+ require( foundationAddress.send(_value * 10 / 100) );
+ uint256 extra;
+ if ( affilateAddress != 0x00 && ( brought[affilateAddress].eth > 0 || interestDB[affilateAddress][0].amount > 0 ) ) {
+ affiliate[affilateAddress].weight = safeAdd(affiliate[affilateAddress].weight, _reward);
+ extra = affiliate[affilateAddress].weight;
+ uint256 rate;
+ if (extra >= 1e12) {
+ rate = 5;
+ } else if (extra >= 1e11) {
+ rate = 4;
+ } else if (extra >= 1e10) {
+ rate = 3;
+ } else if (extra >= 1e9) {
+ rate = 2;
+ } else {
+ rate = 1;
+ }
+ extra = safeSub(extra * rate / 100, affiliate[affilateAddress].paid);
+ affiliate[affilateAddress].paid = safeAdd(affiliate[affilateAddress].paid, extra);
+ token(tokenAddr).mint(affilateAddress, extra);
+ }
+ checkPremium(beneficiaryAddress);
+ EICO(beneficiaryAddress, _reward, affilateAddress, extra);
+ return true;
+ }
+
+ function checkPremium(address owner) internal {
+ /*
+ Crediting the premium token
+
+ @owner The corion token balance of this address will be set based on the calculation which shows that how many times can be the amount of the purchased tokens devided by 5000. So after each 5000 token we give 1 premium token.
+ */
+ uint256 _reward = (brought[owner].cor / 5e9) - brought[owner].corp;
+ if ( _reward > 0 ) {
+ require( premium(premiumAddr).mint(owner, _reward) );
+ brought[owner].corp = safeAdd(brought[owner].corp, _reward);
+ totalPremiumMint = safeAdd(totalPremiumMint, _reward);
+ }
+ }
+
+ function getIcoReward(uint256 value) public constant returns (uint256 reward) {
+ /*
+ Expected token volume at token purchase
+
+ @value The amount of ether for the purchase
+ @reward Amount of the token
+ x = (value * 1e6 * USD_ETC_exchange rate / 1e4 / 1e18) * bonus percentage
+ 2.700000 token = (1e18 * 1e6 * 22500 / 1e4 / 1e18) * 1.20
+ */
+ reward = (value * 1e6 * icoExchangeRate / icoExchangeRateM / 1 ether) * (ICObonus() + 100) / 100;
+ if ( reward < 5e6) { return 0; }
+ }
+
+ function isICO() public constant returns (bool success) {
+ return startBlock <= block.number && block.number <= icoDelay && ( ! aborted ) && ( ! closed );
+ }
+
+ event EICO(address indexed Address, uint256 indexed value, address Affilate, uint256 AffilateValue);
+}
diff --git a/test/compilationTests/corion/module.sol b/test/compilationTests/corion/module.sol
new file mode 100644
index 00000000..d64044cb
--- /dev/null
+++ b/test/compilationTests/corion/module.sol
@@ -0,0 +1,143 @@
+pragma solidity ^0.4.11;
+
+contract abstractModuleHandler {
+ function transfer(address from, address to, uint256 value, bool fee) external returns (bool success) {}
+ function balanceOf(address owner) public constant returns (bool success, uint256 value) {}
+}
+
+contract module {
+ /*
+ Module
+ */
+
+ enum status {
+ New,
+ Connected,
+ Disconnected,
+ Disabled
+ }
+
+ status public moduleStatus;
+ uint256 public disabledUntil;
+ address public moduleHandlerAddress;
+
+ function disableModule(bool forever) external onlyForModuleHandler returns (bool success) {
+ _disableModule(forever);
+ return true;
+ }
+ function _disableModule(bool forever) internal {
+ /*
+ Disable the module for one week, if the forever true then for forever.
+ This function calls the Publisher module.
+
+ @forever For forever or not
+ */
+ if ( forever ) { moduleStatus = status.Disabled; }
+ else { disabledUntil = block.number + 5760; }
+ }
+
+ function replaceModuleHandler(address newModuleHandlerAddress) external onlyForModuleHandler returns (bool success) {
+ _replaceModuleHandler(newModuleHandlerAddress);
+ return true;
+ }
+ function _replaceModuleHandler(address newModuleHandlerAddress) internal {
+ /*
+ Replace the ModuleHandler address.
+ This function calls the Publisher module.
+
+ @newModuleHandlerAddress New module handler address
+ */
+ require( moduleStatus == status.Connected );
+ moduleHandlerAddress = newModuleHandlerAddress;
+ }
+
+ function connectModule() external onlyForModuleHandler returns (bool success) {
+ _connectModule();
+ return true;
+ }
+ function _connectModule() internal {
+ /*
+ Registering and/or connecting-to ModuleHandler.
+ This function is called by ModuleHandler load or by Publisher.
+ */
+ require( moduleStatus == status.New );
+ moduleStatus = status.Connected;
+ }
+
+ function disconnectModule() external onlyForModuleHandler returns (bool success) {
+ _disconnectModule();
+ return true;
+ }
+ function _disconnectModule() internal {
+ /*
+ Disconnect the module from the ModuleHandler.
+ This function calls the Publisher module.
+ */
+ require( moduleStatus != status.New && moduleStatus != status.Disconnected );
+ moduleStatus = status.Disconnected;
+ }
+
+ function replaceModule(address newModuleAddress) external onlyForModuleHandler returns (bool success) {
+ _replaceModule(newModuleAddress);
+ return true;
+ }
+ function _replaceModule(address newModuleAddress) internal {
+ /*
+ Replace the module for an another new module.
+ This function calls the Publisher module.
+ We send every Token and ether to the new module.
+
+ @newModuleAddress New module handler address
+ */
+ require( moduleStatus != status.New && moduleStatus != status.Disconnected);
+ var (_success, _balance) = abstractModuleHandler(moduleHandlerAddress).balanceOf(address(this));
+ require( _success );
+ if ( _balance > 0 ) {
+ require( abstractModuleHandler(moduleHandlerAddress).transfer(address(this), newModuleAddress, _balance, false) );
+ }
+ if ( this.balance > 0 ) {
+ require( newModuleAddress.send(this.balance) );
+ }
+ moduleStatus = status.Disconnected;
+ }
+
+ function transferEvent(address from, address to, uint256 value) external onlyForModuleHandler returns (bool success) {
+ return true;
+ }
+ function newSchellingRoundEvent(uint256 roundID, uint256 reward) external onlyForModuleHandler returns (bool success) {
+ return true;
+ }
+
+ function registerModuleHandler(address _moduleHandlerAddress) internal {
+ /*
+ Module constructor function for registering ModuleHandler address.
+ */
+ moduleHandlerAddress = _moduleHandlerAddress;
+ }
+ function isModuleHandler(address addr) internal returns (bool ret) {
+ /*
+ Test for ModuleHandler address.
+ If the module is not connected then returns always false.
+
+ @addr Address to check
+
+ @ret This is the module handler address or not
+ */
+ if ( moduleHandlerAddress == 0x00 ) { return true; }
+ if ( moduleStatus != status.Connected ) { return false; }
+ return addr == moduleHandlerAddress;
+ }
+ function isActive() public constant returns (bool success, bool active) {
+ /*
+ Check self for ready for functions or not.
+
+ @success Function call was successfull or not
+ @active Ready for functions or not
+ */
+ return (true, moduleStatus == status.Connected && block.number >= disabledUntil);
+ }
+ modifier onlyForModuleHandler() {
+ require( msg.sender == moduleHandlerAddress );
+ _;
+ }
+}
diff --git a/test/compilationTests/corion/moduleHandler.sol b/test/compilationTests/corion/moduleHandler.sol
new file mode 100644
index 00000000..682f81dd
--- /dev/null
+++ b/test/compilationTests/corion/moduleHandler.sol
@@ -0,0 +1,448 @@
+pragma solidity ^0.4.11;
+
+import "./module.sol";
+import "./announcementTypes.sol";
+import "./multiOwner.sol";
+
+import "./publisher.sol";
+import "./token.sol";
+import "./provider.sol";
+import "./schelling.sol";
+import "./premium.sol";
+import "./ico.sol";
+
+contract abstractModule {
+ function connectModule() external returns (bool success) {}
+ function disconnectModule() external returns (bool success) {}
+ function replaceModule(address addr) external returns (bool success) {}
+ function disableModule(bool forever) external returns (bool success) {}
+ function isActive() public constant returns (bool success) {}
+ function replaceModuleHandler(address newHandler) external returns (bool success) {}
+ function transferEvent(address from, address to, uint256 value) external returns (bool success) {}
+ function newSchellingRoundEvent(uint256 roundID, uint256 reward) external returns (bool success) {}
+}
+
+contract moduleHandler is multiOwner, announcementTypes {
+
+ struct modules_s {
+ address addr;
+ bytes32 name;
+ bool schellingEvent;
+ bool transferEvent;
+ }
+
+ modules_s[] public modules;
+ address public foundationAddress;
+ uint256 debugModeUntil = block.number + 1000000;
+
+ function moduleHandler(address[] newOwners) multiOwner(newOwners) {}
+
+ function load(address foundation, bool forReplace, address Token, address Premium, address Publisher, address Schelling, address Provider) {
+ /*
+ Loading modulest to ModuleHandler.
+
+ This module can be called only once and only by the owner, if every single module and its database are already put on the blockchain.
+ If forReaplace is true, than the ModuleHandler will be replaced. Before the publishing of its replace, the new contract must be already on the blockchain.
+
+ @foundation Address of foundation.
+ @forReplace Is it for replace or not. If not, it will be connected to the module.
+ @Token address of token.
+ @Publisher address of publisher.
+ @Schelling address of Schelling.
+ @Provider address of provider
+ */
+ require( owners[msg.sender] );
+ require( modules.length == 0 );
+ foundationAddress = foundation;
+ addModule( modules_s(Token, sha3('Token'), false, false), ! forReplace);
+ addModule( modules_s(Premium, sha3('Premium'), false, false), ! forReplace);
+ addModule( modules_s(Publisher, sha3('Publisher'), false, true), ! forReplace);
+ addModule( modules_s(Schelling, sha3('Schelling'), false, true), ! forReplace);
+ addModule( modules_s(Provider, sha3('Provider'), true, true), ! forReplace);
+ }
+ function addModule(modules_s input, bool call) internal {
+ /*
+ Inside function for registration of the modules in the database.
+ If the call is false, wont happen any direct call.
+
+ @input _Structure of module.
+ @call Is connect to the module or not.
+ */
+ if ( call ) { require( abstractModule(input.addr).connectModule() ); }
+ var (success, found, id) = getModuleIDByAddress(input.addr);
+ require( success && ! found );
+ (success, found, id) = getModuleIDByHash(input.name);
+ require( success && ! found );
+ (success, found, id) = getModuleIDByAddress(0x00);
+ require( success );
+ if ( ! found ) {
+ id = modules.length;
+ modules.length++;
+ }
+ modules[id] = input;
+ }
+ function getModuleAddressByName(string name) public constant returns( bool success, bool found, address addr ) {
+ /*
+ Search by name for module. The result is an Ethereum address.
+
+ @name Name of module.
+ @addr Address of module.
+ @found Is there any result.
+ @success Was the transaction succesfull or not.
+ */
+ var (_success, _found, _id) = getModuleIDByName(name);
+ if ( _success && _found ) { return (true, true, modules[_id].addr); }
+ return (true, false, 0x00);
+ }
+ function getModuleIDByHash(bytes32 hashOfName) public constant returns( bool success, bool found, uint256 id ) {
+ /*
+ Search by hash of name in the module array. The result is an index array.
+
+ @name Name of module.
+ @id Index of module.
+ @found Was there any result or not.
+ */
+ for ( uint256 a=0 ; a<modules.length ; a++ ) {
+ if ( modules[a].name == hashOfName ) {
+ return (true, true, a);
+ }
+ }
+ return (true, false, 0);
+ }
+ function getModuleIDByName(string name) public constant returns( bool success, bool found, uint256 id ) {
+ /*
+ Search by name for module. The result is an index array.
+
+ @name Name of module.
+ @id Index of module.
+ @found Was there any result or not.
+ */
+ bytes32 _name = sha3(name);
+ for ( uint256 a=0 ; a<modules.length ; a++ ) {
+ if ( modules[a].name == _name ) {
+ return (true, true, a);
+ }
+ }
+ return (true, false, 0);
+ }
+ function getModuleIDByAddress(address addr) public constant returns( bool success, bool found, uint256 id ) {
+ /*
+ Search by ethereum address for module. The result is an index array.
+
+ @name Name of module.
+ @id Index of module.
+ @found Was there any result or not.
+ */
+ for ( uint256 a=0 ; a<modules.length ; a++ ) {
+ if ( modules[a].addr == addr ) {
+ return (true, true, a);
+ }
+ }
+ return (true, false, 0);
+ }
+ function replaceModule(string name, address addr, bool callCallback) external returns (bool success) {
+ /*
+ Module replace, can be called only by the Publisher contract.
+
+ @name Name of module.
+ @addr Address of module.
+ @bool Was there any result or not.
+ @callCallback Call the replaceable module to confirm replacement or not.
+ */
+ var (_success, _found, _id) = getModuleIDByAddress(msg.sender);
+ require( _success );
+ if ( ! ( _found && modules[_id].name == sha3('Publisher') )) {
+ require( block.number < debugModeUntil );
+ if ( ! insertAndCheckDo(calcDoHash("replaceModule", sha3(name, addr, callCallback))) ) {
+ return true;
+ }
+ }
+ (_success, _found, _id) = getModuleIDByName(name);
+ require( _success && _found );
+ if ( callCallback ) {
+ require( abstractModule(modules[_id].addr).replaceModule(addr) );
+ }
+ require( abstractModule(addr).connectModule() );
+ modules[_id].addr = addr;
+ return true;
+ }
+
+ function callReplaceCallback(string moduleName, address newModule) external returns (bool success) {
+ require( block.number < debugModeUntil );
+ if ( ! insertAndCheckDo(calcDoHash("callReplaceCallback", sha3(moduleName, newModule))) ) {
+ return true;
+ }
+ var (_success, _found, _id) = getModuleIDByName(moduleName);
+ require( _success);
+ require( abstractModule(modules[_id].addr).replaceModule(newModule) );
+ return true;
+ }
+
+ function newModule(string name, address addr, bool schellingEvent, bool transferEvent) external returns (bool success) {
+ /*
+ Adding new module to the database. Can be called only by the Publisher contract.
+
+ @name Name of module.
+ @addr Address of module.
+ @schellingEvent Gets it new Schelling round notification?
+ @transferEvent Gets it new transaction notification?
+ @bool Was there any result or not.
+ */
+ var (_success, _found, _id) = getModuleIDByAddress(msg.sender);
+ require( _success );
+ if ( ! ( _found && modules[_id].name == sha3('Publisher') )) {
+ require( block.number < debugModeUntil );
+ if ( ! insertAndCheckDo(calcDoHash("newModule", sha3(name, addr, schellingEvent, transferEvent))) ) {
+ return true;
+ }
+ }
+ addModule( modules_s(addr, sha3(name), schellingEvent, transferEvent), true);
+ return true;
+ }
+ function dropModule(string name, bool callCallback) external returns (bool success) {
+ /*
+ Deleting module from the database. Can be called only by the Publisher contract.
+
+ @name Name of module to delete.
+ @bool Was the function successfull?
+ @callCallback Call the replaceable module to confirm replacement or not.
+ */
+ var (_success, _found, _id) = getModuleIDByAddress(msg.sender);
+ require( _success );
+ if ( ! ( _found && modules[_id].name == sha3('Publisher') )) {
+ require( block.number < debugModeUntil );
+ if ( ! insertAndCheckDo(calcDoHash("replaceModule", sha3(name, callCallback))) ) {
+ return true;
+ }
+ }
+ (_success, _found, _id) = getModuleIDByName(name);
+ require( _success && _found );
+ if( callCallback ) {
+ abstractModule(modules[_id].addr).disableModule(true);
+ }
+ delete modules[_id];
+ return true;
+ }
+
+ function callDisableCallback(string moduleName) external returns (bool success) {
+ require( block.number < debugModeUntil );
+ if ( ! insertAndCheckDo(calcDoHash("callDisableCallback", sha3(moduleName))) ) {
+ return true;
+ }
+ var (_success, _found, _id) = getModuleIDByName(moduleName);
+ require( _success);
+ require( abstractModule(modules[_id].addr).disableModule(true) );
+ return true;
+ }
+
+ function broadcastTransfer(address from, address to, uint256 value) external returns (bool success) {
+ /*
+ Announcing transactions for the modules.
+
+ Can be called only by the token module.
+ Only the configured modules get notifications.( transferEvent )
+
+ @from from who.
+ @to to who.
+ @value amount.
+ @bool Was the function successfull?
+ */
+ var (_success, _found, _id) = getModuleIDByAddress(msg.sender);
+ require( _success && _found && modules[_id].name == sha3('Token') );
+ for ( uint256 a=0 ; a<modules.length ; a++ ) {
+ if ( modules[a].transferEvent && abstractModule(modules[a].addr).isActive() ) {
+ require( abstractModule(modules[a].addr).transferEvent(from, to, value) );
+ }
+ }
+ return true;
+ }
+ function broadcastSchellingRound(uint256 roundID, uint256 reward) external returns (bool success) {
+ /*
+ Announcing new Schelling round for the modules.
+ Can be called only by the Schelling module.
+ Only the configured modules get notifications( schellingEvent ).
+
+ @roundID Number of Schelling round.
+ @reward Coin emission in this Schelling round.
+ @bool Was the function successfull?
+ */
+ var (_success, _found, _id) = getModuleIDByAddress(msg.sender);
+ require( _success && _found && modules[_id].name == sha3('Schelling') );
+ for ( uint256 a=0 ; a<modules.length ; a++ ) {
+ if ( modules[a].schellingEvent && abstractModule(modules[a].addr).isActive() ) {
+ require( abstractModule(modules[a].addr).newSchellingRoundEvent(roundID, reward) );
+ }
+ }
+ return true;
+ }
+ function replaceModuleHandler(address newHandler) external returns (bool success) {
+ /*
+ Replacing ModuleHandler.
+
+ Can be called only by the publisher.
+ Every module will be informed about the ModuleHandler replacement.
+
+ @newHandler Address of the new ModuleHandler.
+ @bool Was the function successfull?
+ */
+ var (_success, _found, _id) = getModuleIDByAddress(msg.sender);
+ require( _success );
+ if ( ! ( _found && modules[_id].name == sha3('Publisher') )) {
+ require( block.number < debugModeUntil );
+ if ( ! insertAndCheckDo(calcDoHash("replaceModuleHandler", sha3(newHandler))) ) {
+ return true;
+ }
+ }
+ for ( uint256 a=0 ; a<modules.length ; a++ ) {
+ require( abstractModule(modules[a].addr).replaceModuleHandler(newHandler) );
+ }
+ return true;
+ }
+ function balanceOf(address owner) public constant returns (bool success, uint256 value) {
+ /*
+ Query of token balance.
+
+ @owner address
+ @value balance.
+ @success was the function successfull?
+ */
+ var (_success, _found, _id) = getModuleIDByName('Token');
+ require( _success && _found );
+ return (true, token(modules[_id].addr).balanceOf(owner));
+ }
+ function totalSupply() public constant returns (bool success, uint256 value) {
+ /*
+ Query of the whole token amount.
+
+ @value amount.
+ @success was the function successfull?
+ */
+ var (_success, _found, _id) = getModuleIDByName('Token');
+ require( _success && _found );
+ return (true, token(modules[_id].addr).totalSupply());
+ }
+ function isICO() public constant returns (bool success, bool ico) {
+ /*
+ Query of ICO state
+
+ @ico Is ICO in progress?.
+ @success was the function successfull?
+ */
+ var (_success, _found, _id) = getModuleIDByName('Token');
+ require( _success && _found );
+ return (true, token(modules[_id].addr).isICO());
+ }
+ function getCurrentSchellingRoundID() public constant returns (bool success, uint256 round) {
+ /*
+ Query of number of the actual Schelling round.
+
+ @round Schelling round.
+ @success was the function successfull?
+ */
+ var (_success, _found, _id) = getModuleIDByName('Schelling');
+ require( _success && _found );
+ return (true, schelling(modules[_id].addr).getCurrentSchellingRoundID());
+ }
+ function mint(address to, uint256 value) external returns (bool success) {
+ /*
+ Token emission request. Can be called only by the provider.
+
+ @to Place of new token
+ @value Token amount
+
+ @success Was the function successfull?
+ */
+ var (_success, _found, _id) = getModuleIDByAddress(msg.sender);
+ require( _success && _found && modules[_id].name == sha3('Provider') );
+ (_success, _found, _id) = getModuleIDByName('Token');
+ require( _success && _found );
+ require( token(modules[_id].addr).mint(to, value) );
+ return true;
+ }
+ function transfer(address from, address to, uint256 value, bool fee) external returns (bool success) {
+ /*
+ Token transaction request. Can be called only by a module.
+
+ @from from who.
+ @to To who.
+ @value Token amount.
+ @fee Transaction fee will be charged or not?
+ @success Was the function successfull?
+ */
+ var (_success, _found, _id) = getModuleIDByAddress(msg.sender);
+ require( _success && _found );
+ (_success, _found, _id) = getModuleIDByName('Token');
+ require( _success && _found );
+ require( token(modules[_id].addr).transferFromByModule(from, to, value, fee) );
+ return true;
+ }
+ function processTransactionFee(address from, uint256 value) external returns (bool success) {
+ /*
+ Token transaction fee. Can be called only by the provider.
+
+ @from From who.
+ @value Token amount.
+ @success Was the function successfull?
+ */
+ var (_success, _found, _id) = getModuleIDByAddress(msg.sender);
+ require( _success && _found && modules[_id].name == sha3('Provider') );
+ (_success, _found, _id) = getModuleIDByName('Token');
+ require( _success && _found );
+ require( token(modules[_id].addr).processTransactionFee(from, value) );
+ return true;
+ }
+ function burn(address from, uint256 value) external returns (bool success) {
+ /*
+ Token burn. Can be called only by Schelling.
+
+ @from From who.
+ @value Token amount.
+ @success Was the function successfull?
+ */
+ var (_success, _found, _id) = getModuleIDByAddress(msg.sender);
+ require( _success && _found && modules[_id].name == sha3('Schelling') );
+ (_success, _found, _id) = getModuleIDByName('Token');
+ require( _success && _found );
+ require( token(modules[_id].addr).burn(from, value) );
+ return true;
+ }
+ function configureModule(string moduleName, announcementType aType, uint256 value) external returns (bool success) {
+ /*
+ Changing configuration of a module. Can be called only by Publisher or while debug mode by owners.
+
+ @moduleName Module name which will be configured
+ @aType Type of variable (announcementType).
+ @value New value
+ @success Was the function successfull?
+ */
+ var (_success, _found, _id) = getModuleIDByAddress(msg.sender);
+ require( _success );
+ if ( ! ( _found && modules[_id].name == sha3('Publisher') )) {
+ require( block.number < debugModeUntil );
+ if ( ! insertAndCheckDo(calcDoHash("configureModule", sha3(moduleName, aType, value))) ) {
+ return true;
+ }
+ }
+ (_success, _found, _id) = getModuleIDByName(moduleName);
+ require( _success && _found );
+ require( schelling(modules[_id].addr).configure(aType, value) );
+ return true;
+ }
+ function freezing(bool forever) external {
+ /*
+ Freezing CORION Platform. Can be called only by the owner.
+ Freez can not be recalled!
+
+ @forever Is it forever or not?
+ */
+ require( owners[msg.sender] );
+ if ( forever ) {
+ if ( ! insertAndCheckDo(calcDoHash("freezing", sha3(forever))) ) {
+ return;
+ }
+ }
+ for ( uint256 a=0 ; a<modules.length ; a++ ) {
+ require( abstractModule(modules[a].addr).disableModule(forever) );
+ }
+ }
+}
diff --git a/test/compilationTests/corion/multiOwner.sol b/test/compilationTests/corion/multiOwner.sol
new file mode 100644
index 00000000..9aae0ebd
--- /dev/null
+++ b/test/compilationTests/corion/multiOwner.sol
@@ -0,0 +1,83 @@
+pragma solidity ^0.4.11;
+
+import "./safeMath.sol";
+
+contract multiOwner is safeMath {
+
+ mapping(address => bool) public owners;
+ uint256 public ownerCount;
+
+ mapping(bytes32 => address[]) public doDB;
+
+ /*
+ Constructor
+ */
+ function multiOwner(address[] newOwners) {
+ for ( uint256 a=0 ; a<newOwners.length ; a++ ) {
+ _addOwner(newOwners[a]);
+ }
+ }
+ /*
+ Externals
+ */
+ function insertOwner(address addr) external {
+ if ( insertAndCheckDo(calcDoHash("insertOwner", sha3(addr))) ) {
+ _addOwner(addr);
+ }
+ }
+ function dropOwner(address addr) external {
+ if ( insertAndCheckDo(calcDoHash("dropOwner", sha3(addr))) ) {
+ _delOwner(addr);
+ }
+ }
+ function cancelDo(bytes32 doHash) external {
+ if ( insertAndCheckDo(calcDoHash("cancelDo", doHash)) ) {
+ delete doDB[doHash];
+ }
+ }
+ /*
+ Constants
+ */
+ function ownersForChange() public constant returns (uint256 owners) {
+ return ownerCount * 75 / 100;
+ }
+ function calcDoHash(string job, bytes32 data) public constant returns (bytes32 hash) {
+ return sha3(job, data);
+ }
+ function validDoHash(bytes32 doHash) public constant returns (bool valid) {
+ return doDB[doHash].length > 0;
+ }
+ /*
+ Internals
+ */
+ function insertAndCheckDo(bytes32 doHash) internal returns (bool success) {
+ require( owners[msg.sender] );
+ if (doDB[doHash].length >= ownersForChange()) {
+ delete doDB[doHash];
+ return true;
+ }
+ for ( uint256 a=0 ; a<doDB[doHash].length ; a++ ) {
+ require( doDB[doHash][a] != msg.sender );
+ }
+ if ( doDB[doHash].length+1 >= ownersForChange() ) {
+ delete doDB[doHash];
+ return true;
+ } else {
+ doDB[doHash].push(msg.sender);
+ return false;
+ }
+ }
+ /*
+ Privates
+ */
+ function _addOwner(address addr) private {
+ if ( owners[addr] ) { return; }
+ owners[addr] = true;
+ ownerCount = safeAdd(ownerCount, 1);
+ }
+ function _delOwner(address addr) private {
+ if ( ! owners[addr] ) { return; }
+ delete owners[addr];
+ ownerCount = safeSub(ownerCount, 1);
+ }
+}
diff --git a/test/compilationTests/corion/owned.sol b/test/compilationTests/corion/owned.sol
new file mode 100644
index 00000000..bd187775
--- /dev/null
+++ b/test/compilationTests/corion/owned.sol
@@ -0,0 +1,28 @@
+pragma solidity ^0.4.11;
+
+contract ownedDB {
+ address private owner;
+
+ function replaceOwner(address newOwner) external returns(bool) {
+ /*
+ Owner replace.
+
+ @newOwner Address of new owner.
+ */
+ require( isOwner() );
+ owner = newOwner;
+ return true;
+ }
+
+ function isOwner() internal returns(bool) {
+ /*
+ Check of owner address.
+
+ @bool Owner has called the contract or not
+ */
+ if ( owner == 0x00 ) {
+ return true;
+ }
+ return owner == msg.sender;
+ }
+}
diff --git a/test/compilationTests/corion/premium.sol b/test/compilationTests/corion/premium.sol
new file mode 100644
index 00000000..be2c5de0
--- /dev/null
+++ b/test/compilationTests/corion/premium.sol
@@ -0,0 +1,346 @@
+pragma solidity ^0.4.11;
+
+import "./safeMath.sol";
+import "./tokenDB.sol";
+import "./module.sol";
+
+contract thirdPartyPContractAbstract {
+ function receiveCorionPremiumToken(address, uint256, bytes) external returns (bool, uint256) {}
+ function approvedCorionPremiumToken(address, uint256, bytes) external returns (bool) {}
+}
+
+contract ptokenDB is tokenDB {}
+
+contract premium is module, safeMath {
+ function replaceModule(address addr) external returns (bool success) {
+ require( super.isModuleHandler(msg.sender) );
+ require( db.replaceOwner(addr) );
+ super._replaceModule(addr);
+ return true;
+ }
+ modifier isReady {
+ var (_success, _active) = super.isActive();
+ require( _success && _active );
+ _;
+ }
+ /**
+ *
+ * @title Corion Platform Premium Token
+ * @author iFA @ Corion Platform
+ *
+ */
+
+ string public name = "Corion Premium";
+ string public symbol = "CORP";
+ uint8 public decimals = 0;
+
+ address public icoAddr;
+ tokenDB public db;
+ bool public isICO;
+
+ mapping(address => bool) public genesis;
+
+ function premium(bool forReplace, address moduleHandler, address dbAddress, address icoContractAddr, address[] genesisAddr, uint256[] genesisValue) {
+ /*
+ Setup function.
+ If an ICOaddress is defined then the balance of the genesis addresses will be set as well.
+
+ @forReplace This address will be replaced with the old one or not.
+ @moduleHandler Modulhandler’s address
+ @dbAddress Address of database
+ @icoContractAddr Address of ico contract.
+ @genesisAddr Array of the genesis addresses.
+ @genesisValue Array of the balance of the genesis addresses
+ */
+ super.registerModuleHandler(moduleHandler);
+ require( dbAddress != 0x00 );
+ db = ptokenDB(dbAddress);
+ if ( ! forReplace ) {
+ require( db.replaceOwner(this) );
+ isICO = true;
+ icoAddr = icoContractAddr;
+ assert( genesisAddr.length == genesisValue.length );
+ for ( uint256 a=0 ; a<genesisAddr.length ; a++ ) {
+ genesis[genesisAddr[a]] = true;
+ require( db.increase(genesisAddr[a], genesisValue[a]) );
+ Mint(genesisAddr[a], genesisValue[a]);
+ }
+ }
+ }
+
+ function closeIco() external returns (bool success) {
+ /*
+ Finishing the ICO. Can be invited only by an ICO contract.
+
+ @success If the function was successful.
+ */
+ require( isICO );
+ isICO = false;
+ return true;
+ }
+
+ /**
+ * @notice `msg.sender` approves `spender` to spend `amount` tokens on its behalf.
+ * @param spender The address of the account able to transfer the tokens
+ * @param amount The amount of tokens to be approved for transfer
+ * @param nonce The transaction count of the authorised address
+ * @return True if the approval was successful
+ */
+ function approve(address spender, uint256 amount, uint256 nonce) isReady external returns (bool success) {
+ /*
+ Authorize another address to use an exact amount of the principal’s balance.
+
+ @spender Address of authorised party
+ @amount Token quantity
+ @nonce Transaction count
+
+ @success Was the Function successful?
+ */
+ _approve(spender, amount, nonce);
+ return true;
+ }
+
+ /**
+ * @notice `msg.sender` approves `spender` to spend `amount` tokens on its behalf and notify the spender from your approve with your `extraData` data.
+ * @param spender The address of the account able to transfer the tokens
+ * @param amount The amount of tokens to be approved for transfer
+ * @param nonce The transaction count of the authorised address
+ * @param extraData Data to give forward to the receiver
+ * @return True if the approval was successful
+ */
+ function approveAndCall(address spender, uint256 amount, uint256 nonce, bytes extraData) isReady external returns (bool success) {
+ /*
+ Authorize another address to use an exact amount of the principal’s balance.
+ After the transaction the approvedCorionPremiumToken function of the address will be called with the given data.
+
+ @spender Authorized address
+ @amount Token quantity
+ @extraData Extra data to be received by the receiver
+ @nonce Transaction count
+
+ @sucess Was the Function successful?
+ */
+ _approve(spender, amount, nonce);
+ require( thirdPartyPContractAbstract(spender).approvedCorionPremiumToken(msg.sender, amount, extraData) );
+ return true;
+ }
+
+ function _approve(address spender, uint256 amount, uint256 nonce) isReady internal {
+ /*
+ Inner function to authorize another address to use an exact amount of the principal’s balance.
+ If the transaction count not match the authorise fails.
+
+ @spender Address of authorised party
+ @amount Token quantity
+ @nonce Transaction count
+ */
+ require( msg.sender != spender );
+ require( db.balanceOf(msg.sender) >= amount );
+ require( db.setAllowance(msg.sender, spender, amount, nonce) );
+ Approval(msg.sender, spender, amount);
+ }
+
+ function allowance(address owner, address spender) constant returns (uint256 remaining, uint256 nonce) {
+ /*
+ Get the quantity of tokens given to be used
+
+ @owner Authorising address
+ @spender Authorised address
+
+ @remaining Tokens to be spent
+ @nonce Transaction count
+ */
+ var (_success, _remaining, _nonce) = db.getAllowance(owner, spender);
+ require( _success );
+ return (_remaining, _nonce);
+ }
+
+ /**
+ * @notice Send `amount` Corion tokens to `to` from `msg.sender`
+ * @param to The address of the recipient
+ * @param amount The amount of tokens to be transferred
+ * @return Whether the transfer was successful or not
+ */
+ function transfer(address to, uint256 amount) isReady external returns (bool success) {
+ /*
+ Launch a transaction where the token is sent from the sender’s address to the receiver’s address.
+ Transaction fee is going to be added as well.
+ If the receiver is not a natural address but also a person then she/he will be invited as well.
+
+ @to For who
+ @amount Amount
+
+ @success Was the function successful?
+ */
+ bytes memory _data;
+ if ( isContract(to) ) {
+ transferToContract(msg.sender, to, amount, _data);
+ } else {
+ _transfer(msg.sender, to, amount);
+ }
+ Transfer(msg.sender, to, amount, _data);
+ return true;
+ }
+
+ /**
+ * @notice Send `amount` tokens to `to` from `from` on the condition it is approved by `from`
+ * @param from The address holding the tokens being transferred
+ * @param to The address of the recipient
+ * @param amount The amount of tokens to be transferred
+ * @return True if the transfer was successful
+ */
+ function transferFrom(address from, address to, uint256 amount) isReady external returns (bool success) {
+ /*
+ Launch a transaction where we transfer from a given address to another one. It can only be called by an address which was allowed before.
+ Transaction fee will be charged too.
+ If the receiver is not a natural address but also a person then she/he will be invited as well
+
+ @from From who?
+ @to For who?
+ @amount Amount
+
+ @success If the function was successful.
+ */
+ if ( from != msg.sender ) {
+ var (_success, _reamining, _nonce) = db.getAllowance(from, msg.sender);
+ require( _success );
+ _reamining = safeSub(_reamining, amount);
+ _nonce = safeAdd(_nonce, 1);
+ require( db.setAllowance(from, msg.sender, _reamining, _nonce) );
+ AllowanceUsed(msg.sender, from, amount);
+ }
+ bytes memory _data;
+ if ( isContract(to) ) {
+ transferToContract(from, to, amount, _data);
+ } else {
+ _transfer( from, to, amount);
+ }
+ Transfer(from, to, amount, _data);
+ return true;
+ }
+
+ /**
+ * @notice Send `amount` Corion tokens to `to` from `msg.sender` and notify the receiver from your transaction with your `extraData` data
+ * @param to The contract address of the recipient
+ * @param amount The amount of tokens to be transferred
+ * @param extraData Data to give forward to the receiver
+ * @return Whether the transfer was successful or not
+ */
+ function transfer(address to, uint256 amount, bytes extraData) isReady external returns (bool success) {
+ /*
+ Launch a transaction where we transfer from a given address to another one.
+ After thetransaction the approvedCorionPremiumToken function of the receiver’s address is going to be called with the given data.
+
+ @to For who?
+ @amount Amount
+ @extraData Extra data that will be given to the receiver
+
+ @success If the function was successful.
+ */
+ if ( isContract(to) ) {
+ transferToContract(msg.sender, to, amount, extraData);
+ } else {
+ _transfer( msg.sender, to, amount);
+ }
+ Transfer(msg.sender, to, amount, extraData);
+ return true;
+ }
+
+ function transferToContract(address from, address to, uint256 amount, bytes extraData) internal {
+ /*
+ Inner function in order to transact a contract.
+
+ @to For who?
+ @amount Amount
+ @extraData Extra data that will be given to the receiver
+ */
+ _transfer(from, to, amount);
+ var (_success, _back) = thirdPartyPContractAbstract(to).receiveCorionPremiumToken(from, amount, extraData);
+ require( _success );
+ require( amount > _back );
+ if ( _back > 0 ) {
+ _transfer(to, from, _back);
+ }
+ }
+
+ function _transfer(address from, address to, uint256 amount) isReady internal {
+ /*
+ Inner function to launch a transaction.
+ During the ICO transactions are only possible from the genesis address.
+ 0xa636a97578d26a3b76b060bbc18226d954cf3757 address is blacklisted.
+
+ @from From how?
+ @to For who?
+ @amount Amount
+ */
+ require( from != 0x00 && to != 0x00 && to != 0xa636a97578d26a3b76b060bbc18226d954cf3757 );
+ require( ( ! isICO) || genesis[from] );
+ require( db.decrease(from, amount) );
+ require( db.increase(to, amount) );
+ }
+
+ function mint(address owner, uint256 value) external returns (bool success) {
+ /*
+ Generating tokens. It can be called only by ICO contract.
+
+ @owner Address
+ @value Amount.
+
+ @success Was the Function successful?
+ */
+ require( msg.sender == icoAddr || isICO );
+ _mint(owner, value);
+ return true;
+ }
+
+ function _mint(address owner, uint256 value) isReady internal {
+ /*
+ Inner function to create a token.
+
+ @owner Address of crediting the token.
+ @value Amount
+ */
+ require( db.increase(owner, value) );
+ Mint(owner, value);
+ }
+
+ function isContract(address addr) internal returns (bool success) {
+ /*
+ Inner function in order to check if the given address is a natural address or a contract.
+
+ @addr The address which is needed to be checked.
+
+ @success Is the address crontact or not
+ */
+ uint256 _codeLength;
+ assembly {
+ _codeLength := extcodesize(addr)
+ }
+ return _codeLength > 0;
+ }
+
+ function balanceOf(address owner) constant returns (uint256 value) {
+ /*
+ Token balance query
+
+ @owner Address
+ @value Balance of address
+ */
+ return db.balanceOf(owner);
+ }
+
+ function totalSupply() constant returns (uint256 value) {
+ /*
+ Total token quantity query
+
+ @value Total token quantity
+ */
+ return db.totalSupply();
+ }
+
+ event AllowanceUsed(address indexed spender, address indexed owner, uint256 indexed value);
+ event Mint(address indexed addr, uint256 indexed value);
+ event Burn(address indexed addr, uint256 indexed value);
+ event Approval(address indexed _owner, address indexed _spender, uint256 _value);
+ event Transfer(address indexed _from, address indexed _to, uint256 _value, bytes _extraData);
+}
diff --git a/test/compilationTests/corion/provider.sol b/test/compilationTests/corion/provider.sol
new file mode 100644
index 00000000..5fa90fcd
--- /dev/null
+++ b/test/compilationTests/corion/provider.sol
@@ -0,0 +1,797 @@
+pragma solidity ^0.4.11;
+
+import "./module.sol";
+import "./moduleHandler.sol";
+import "./safeMath.sol";
+import "./announcementTypes.sol";
+
+contract provider is module, safeMath, announcementTypes {
+ /*
+ module callbacks
+ */
+ function connectModule() external returns (bool success) {
+ require( super.isModuleHandler(msg.sender) );
+ super._connectModule();
+ var (_success, currentSchellingRound) = moduleHandler(moduleHandlerAddress).getCurrentSchellingRoundID();
+ require( _success );
+ return true;
+ }
+ function transferEvent(address from, address to, uint256 value) external returns (bool success) {
+ /*
+ Transaction completed. This function is ony available for the modulehandler.
+ It should be checked if the sender or the acceptor does not connect to the provider or it is not a provider itself if so than the change should be recorded.
+
+ @from From whom?
+ @to For who?
+ @value amount
+ @bool Was the function successful?
+ */
+ require( super.isModuleHandler(msg.sender) );
+ transferEvent_(from, value, true);
+ transferEvent_(to, value, false);
+ return true;
+ }
+ function newSchellingRoundEvent(uint256 roundID, uint256 reward) external returns (bool success) {
+ /*
+ New schelling round. This function is only available for the moduleHandler.
+ We are recording the new schelling round and we are storing the whole current quantity of the tokens.
+ We generate a reward quantity of tokens directed to the providers address. The collected interest will be tranfered from this contract.
+
+ @roundID Number of the schelling round.
+ @reward token emission
+ @bool Was the function successful?
+ */
+ require( super.isModuleHandler(msg.sender) );
+ globalFunds[roundID].reward = reward;
+ globalFunds[roundID].supply = globalFunds[roundID-1].supply;
+ currentSchellingRound = roundID;
+ require( moduleHandler(moduleHandlerAddress).mint(address(this), reward) );
+ return true;
+ }
+ modifier isReady {
+ var (_success, _active) = super.isActive();
+ require( _success && _active );
+ _;
+ }
+ /*
+ Provider module
+ */
+ uint256 private minFundsForPublic = 3000;
+ uint256 private minFundsForPrivate = 8000;
+ uint256 private privateProviderLimit = 250;
+ uint8 private publicMinRate = 30;
+ uint8 private privateMinRate = 0;
+ uint8 private publicMaxRate = 70;
+ uint8 private privateMaxRate = 100;
+ uint256 private gasProtectMaxRounds = 630;
+ uint256 private interestMinFunds = 25000;
+ uint256 private rentRate = 20;
+
+ struct _rate {
+ uint8 value;
+ bool valid;
+ }
+ struct __providers {
+ address admin;
+ string name;
+ string website;
+ string country;
+ string info;
+ bool isForRent;
+ mapping(uint256 => _rate) rateHistory;
+ uint8 currentRate;
+ bool priv;
+ uint256 clientsCount;
+ mapping(address => bool) allowedUsers;
+ mapping(uint256 => uint256) supply;
+ uint256 lastSupplyID;
+ mapping(uint256 => uint256) ownSupply;
+ uint256 lastOwnSupplyID;
+ uint256 paidUpTo;
+ uint8 lastPaidRate;
+ uint256 create;
+ uint256 close;
+ bool valid;
+ }
+ struct _providers {
+ mapping(uint256 => __providers) data;
+ uint256 currentHeight;
+ }
+ mapping(address => _providers) private providers;
+
+ struct _globalFunds {
+ uint256 reward;
+ uint256 supply;
+ }
+ mapping(uint256 => _globalFunds) private globalFunds;
+
+ struct _client{
+ address providerAddress;
+ uint256 providerHeight;
+ uint256 providerConnected;
+ uint8 lastRate;
+ mapping(uint256 => uint256) supply;
+ uint256 lastSupplyID;
+ uint256 paidUpTo;
+ }
+ mapping(address => _client) private clients;
+
+ uint256 private currentSchellingRound = 1;
+
+ function provider(address _moduleHandler) {
+ /*
+ Install function.
+
+ @_moduleHandler Address of the moduleHandler.
+ */
+ super.registerModuleHandler(_moduleHandler);
+ }
+ function configure(announcementType a, uint256 b) external returns(bool) {
+ /*
+ Configuration of the provider. Can be invited just by the moduleHandler.
+
+ @a Type of the setting
+ @b value
+ */
+ require( super.isModuleHandler(msg.sender) );
+ if ( a == announcementType.providerPublicFunds ) { minFundsForPublic = b; }
+ else if ( a == announcementType.providerPrivateFunds ) { minFundsForPrivate = b; }
+ else if ( a == announcementType.providerPrivateClientLimit ) { privateProviderLimit = b; }
+ else if ( a == announcementType.providerPublicMinRate ) { publicMinRate = uint8(b); }
+ else if ( a == announcementType.providerPublicMaxRate ) { publicMaxRate = uint8(b); }
+ else if ( a == announcementType.providerPrivateMinRate ) { privateMinRate = uint8(b); }
+ else if ( a == announcementType.providerPrivateMaxRate ) { privateMaxRate = uint8(b); }
+ else if ( a == announcementType.providerGasProtect ) { gasProtectMaxRounds = b; }
+ else if ( a == announcementType.providerInterestMinFunds ) { interestMinFunds = b; }
+ else if ( a == announcementType.providerRentRate ) { rentRate = b; }
+ else { return false; }
+ return true;
+ }
+ function getUserDetails(address addr, uint256 schellingRound) public constant returns (address ProviderAddress, uint256 ProviderHeight, uint256 ConnectedOn, uint256 value) {
+ /*
+ Collecting the datas of the client.
+
+ @addr Address of the client.
+ @schellingRound Number of the schelling round. If it is not defined then the current one.
+ @ProviderAddress Address of the provider the one where connected to
+ @ProviderHeight The height (level) of the provider where is connected.
+ @ConnectedOn Time of connection
+ @value Quantity of the client’s token
+ */
+ if ( schellingRound == 0 ) {
+ schellingRound = currentSchellingRound;
+ }
+ if ( clients[addr].providerAddress != 0 ) {
+ ProviderAddress = clients[addr].providerAddress;
+ ProviderHeight = clients[addr].providerHeight;
+ ConnectedOn = clients[addr].providerConnected;
+ value = clients[addr].supply[schellingRound];
+ }
+ }
+ function rightForInterest(uint256 value, bool priv) internal returns (bool) {
+ /*
+ the share from the token emission.
+ In case is a private provider it has to be checked if it has enough connected capital to be able to accept share from the token emission.
+ The provider’s account counts as a capital for the emission as well.
+
+ @value amount of the connected capital
+ @priv Is the provider private or not?
+ @bool Gets the share from the token emission.
+ */
+ if ( priv ) {
+ return ( value >= interestMinFunds );
+ }
+ return true;
+ }
+ function setRightForInterest(uint256 oldValue, uint256 newValue, bool priv) internal {
+ /*
+ It checks if the provider has enough connected captital to be able to get from the token emission.
+ In case the provider is not able to get the share from the token emission then the connected capital will not count to the value of the globalFunds, to the current schelling round.
+
+ @oldValue old
+ @newValue new
+ @priv Is the provider private?
+ */
+ var a = rightForInterest(oldValue, priv);
+ var b = rightForInterest(newValue, priv);
+ if ( a && b ) {
+ globalFunds[currentSchellingRound].supply = globalFunds[currentSchellingRound].supply - oldValue + newValue;
+ } else if ( a && ! b ) {
+ globalFunds[currentSchellingRound].supply -= oldValue;
+ } else if ( ! a && b ) {
+ globalFunds[currentSchellingRound].supply += newValue;
+ }
+ }
+ function checkCorrectRate(bool priv, uint8 rate) internal returns(bool) {
+ /*
+ Inner function which checks if the amount of interest what is given by the provider is fits to the criteria.
+
+ @priv Is the provider private or not?
+ @rate Percentage/rate of the interest
+ @bool Correct or not?
+ */
+ return ( ! priv && ( rate >= publicMinRate && rate <= publicMaxRate ) ) ||
+ ( priv && ( rate >= privateMinRate && rate <= privateMaxRate ) );
+ }
+ function createProvider(bool priv, string name, string website, string country, string info, uint8 rate, bool isForRent, address admin) isReady external {
+ /*
+ Creating a provider.
+ During the ICO its not allowed to create provider.
+ To one address only one provider can belong to.
+ Address, how is connected to the provider can not create a provider.
+ For opening, has to have enough capital.
+ All the functions of the provider except of the closing are going to be handled by the admin.
+ The provider can be start as a rent as well, in this case the isForRent has to be true/correct. In case it runs as a rent the 20% of the profit will belong to the leser and the rest goes to the admin.
+
+ @priv Privat szolgaltato e. Is private provider?
+ @name Provider’s name.
+ @website Provider’s website
+ @country Provider’s country
+ @info Provider’s short introduction.
+ @rate Rate of the emission what is going to be transfered to the client by the provider.
+ @isForRent is for Rent or not?
+ @admin The admin’s address
+ */
+ require( ! providers[msg.sender].data[providers[msg.sender].currentHeight].valid );
+ require( clients[msg.sender].providerAddress == 0x00 );
+ require( ! checkICO() );
+ if ( priv ) {
+ require( getTokenBalance(msg.sender) >= minFundsForPrivate );
+ } else {
+ require( getTokenBalance(msg.sender) >= minFundsForPublic );
+ }
+ require( checkCorrectRate(priv, rate) );
+
+ providers[msg.sender].currentHeight++;
+ var currHeight = providers[msg.sender].currentHeight;
+ providers[msg.sender].data[currHeight].valid = true;
+ if ( admin == 0x00 ) {
+ providers[msg.sender].data[currHeight].admin = msg.sender;
+ } else {
+ providers[msg.sender].data[currHeight].admin = admin;
+ }
+ providers[msg.sender].data[currHeight].name = name;
+ providers[msg.sender].data[currHeight].website = website;
+ providers[msg.sender].data[currHeight].isForRent = isForRent;
+ providers[msg.sender].data[currHeight].country = country;
+ providers[msg.sender].data[currHeight].info = info;
+ providers[msg.sender].data[currHeight].currentRate = rate;
+ providers[msg.sender].data[currHeight].create = now;
+ providers[msg.sender].data[currHeight].lastPaidRate = rate;
+ providers[msg.sender].data[currHeight].priv = priv;
+ providers[msg.sender].data[currHeight].lastSupplyID = currentSchellingRound;
+ providers[msg.sender].data[currHeight].paidUpTo = currentSchellingRound;
+ if ( priv ) {
+ providers[msg.sender].data[currHeight].supply[currentSchellingRound] = getTokenBalance(msg.sender);
+ providers[msg.sender].data[currHeight].ownSupply[currentSchellingRound] = getTokenBalance(msg.sender);
+ providers[msg.sender].data[currHeight].lastOwnSupplyID = currentSchellingRound;
+ } else {
+ delete providers[msg.sender].data[currHeight].supply[currentSchellingRound];
+ }
+ EProviderOpen(msg.sender, currHeight);
+ }
+ function setProviderDetails(address addr, string website, string country, string info, uint8 rate, address admin) isReady external {
+ /*
+ Modifying the datas of the provider.
+ This can only be invited by the provider’s admin.
+ The emission rate is only valid for the next schelling round for this one it is not.
+ The admin can only be changed by the address of the provider.
+
+ @addr Address of the provider.
+ @website Website.
+ @admin The new address of the admin. If we do not want to set it then we should enter 0X00.
+ @country Country
+ @info Short intro.
+ @rate Rate of the emission what will be given to the client.
+ */
+ var currHeight = providers[addr].currentHeight;
+ require( providers[addr].data[currHeight].valid );
+ require( checkCorrectRate(providers[addr].data[currHeight].priv, rate) );
+ require( providers[addr].data[currHeight].admin == msg.sender || msg.sender == addr );
+ if ( admin != 0x00 ) {
+ require( msg.sender == addr );
+ providers[addr].data[currHeight].admin = admin;
+ }
+ providers[addr].data[currHeight].rateHistory[currentSchellingRound] = _rate( rate, true );
+ providers[addr].data[currHeight].website = website;
+ providers[addr].data[currHeight].country = country;
+ providers[addr].data[currHeight].info = info;
+ providers[addr].data[currHeight].currentRate = rate;
+ EProviderDetailsChanged(addr, currHeight, website, country, info, rate, admin);
+ }
+ function getProviderInfo(address addr, uint256 height) public constant returns (string name, string website, string country, string info, uint256 create) {
+ /*
+ for the infos of the provider.
+ In case the height is unknown then the system will use the last known height.
+
+ @addr Addr of the provider
+ @height Height
+ @name Name of the provider.
+ @website Website of the provider.
+ @country Country of the provider.
+ @info Short intro of the provider.
+ @create Timestamp of creating the provider
+ */
+ if ( height == 0 ) {
+ height = providers[addr].currentHeight;
+ }
+ name = providers[addr].data[height].name;
+ website = providers[addr].data[height].website;
+ country = providers[addr].data[height].country;
+ info = providers[addr].data[height].info;
+ create = providers[addr].data[height].create;
+ }
+ function getProviderDetails(address addr, uint256 height) public constant returns (uint8 rate, bool isForRent, uint256 clientsCount, bool priv, bool getInterest, bool valid) {
+ /*
+ Asking for the datas of the provider.
+ In case the height is unknown then the system will use the last known height.
+
+ @addr Address of the provider
+ @height Height
+ @rate The rate of the emission which will be transfered to the client.
+ @isForRent Rent or not.
+ @clientsCount Number of the clients.
+ @priv Private or not?
+ @getInterest Does get from the token emission?
+ @valid Is an active provider?
+ */
+ if ( height == 0 ) {
+ height = providers[addr].currentHeight;
+ }
+ rate = providers[addr].data[height].currentRate;
+ isForRent = providers[addr].data[height].isForRent;
+ clientsCount = providers[addr].data[height].clientsCount;
+ priv = providers[addr].data[height].priv;
+ getInterest = rightForInterest(getProviderCurrentSupply(addr), providers[addr].data[height].priv );
+ valid = providers[addr].data[height].valid;
+ }
+ function getProviderCurrentSupply(address addr) internal returns (uint256) {
+ /*
+ Inner function for polling the current height and the current quantity of the connected capital of the schelling round.
+
+ @addr Provider’s address.
+ @uint256 Amount of the connected capital
+ */
+ return providers[addr].data[providers[addr].currentHeight].supply[currentSchellingRound];
+ }
+ function closeProvider() isReady external {
+ /*
+ Closing and inactivate the provider.
+ It is only possible to close that active provider which is owned by the sender itself after calling the whole share of the emission.
+ Whom were connected to the provider those clients will have to disconnect after they’ve called their share of emission which was not called before.
+ */
+ var currHeight = providers[msg.sender].currentHeight;
+ require( providers[msg.sender].data[currHeight].valid );
+ require( providers[msg.sender].data[currHeight].paidUpTo == currentSchellingRound );
+
+ providers[msg.sender].data[currHeight].valid = false;
+ providers[msg.sender].data[currHeight].close = currentSchellingRound;
+ setRightForInterest(getProviderCurrentSupply(msg.sender), 0, providers[msg.sender].data[currHeight].priv);
+ EProviderClose(msg.sender, currHeight);
+ }
+ function allowUsers(address provider, address[] addr) isReady external {
+ /*
+ Permition of the user to be able to connect to the provider.
+ This can only be invited by the provider’s admin.
+ With this kind of call only 100 address can be permited.
+
+ @addr Array of the addresses for whom the connection is allowed.
+ */
+ var currHeight = providers[provider].currentHeight;
+ require( providers[provider].data[currHeight].valid );
+ require( providers[provider].data[currHeight].priv );
+ require( providers[provider].data[currHeight].admin == msg.sender );
+ require( addr.length <= 100 );
+
+ for ( uint256 a=0 ; a<addr.length ; a++ ) {
+ providers[provider].data[currHeight].allowedUsers[addr[a]] = true;
+ }
+ }
+ function disallowUsers(address provider, address[] addr) isReady external {
+ /*
+ Disable of the user not to be able to connect to the provider.
+ It is can called only for the admin of the provider.
+ With this kind of call only 100 address can be permited.
+
+ @addr Array of the addresses for whom the connection is allowed.
+ */
+ var currHeight = providers[provider].currentHeight;
+ require( providers[provider].data[currHeight].valid );
+ require( providers[provider].data[currHeight].priv );
+ require( providers[provider].data[currHeight].admin == msg.sender );
+ require( addr.length <= 100 );
+
+ for ( uint256 a=0 ; a<addr.length ; a++ ) {
+ delete providers[provider].data[currHeight].allowedUsers[addr[a]];
+ }
+ }
+ function joinProvider(address provider) isReady external {
+ /*
+ Connection to the provider.
+ Providers can not connect to other providers.
+ If is a client at any provider, then it is not possible to connect to other provider one.
+ It is only possible to connect to valid and active providers.
+ If is an active provider then the client can only connect, if address is permited at the provider (Whitelist).
+ At private providers, the number of the client is restricted. If it reaches the limit no further clients are allowed to connect.
+ This process has a transaction fee based on the senders whole token quantity.
+
+ @provider Address of the provider.
+ */
+ var currHeight = providers[provider].currentHeight;
+ require( ! providers[msg.sender].data[currHeight].valid );
+ require( clients[msg.sender].providerAddress == 0x00 );
+ require( providers[provider].data[currHeight].valid );
+ if ( providers[provider].data[currHeight].priv ) {
+ require( providers[provider].data[currHeight].allowedUsers[msg.sender] &&
+ providers[provider].data[currHeight].clientsCount < privateProviderLimit );
+ }
+ var bal = getTokenBalance(msg.sender);
+ require( moduleHandler(moduleHandlerAddress).processTransactionFee(msg.sender, bal) );
+
+ checkFloatingSupply(provider, currHeight, false, bal);
+ providers[provider].data[currHeight].clientsCount++;
+ clients[msg.sender].providerAddress = provider;
+ clients[msg.sender].providerHeight = currHeight;
+ clients[msg.sender].supply[currentSchellingRound] = bal;
+ clients[msg.sender].lastSupplyID = currentSchellingRound;
+ clients[msg.sender].paidUpTo = currentSchellingRound;
+ clients[msg.sender].lastRate = providers[provider].data[currHeight].currentRate;
+ clients[msg.sender].providerConnected = now;
+ ENewClient(msg.sender, provider, currHeight, bal);
+ }
+ function partProvider() isReady external {
+ /*
+ Disconnecting from the provider.
+ Before disconnecting we should poll our share from the token emission even if there was nothing factually.
+ It is only possible to disconnect those providers who were connected by us before.
+ */
+ var provider = clients[msg.sender].providerAddress;
+ require( provider != 0x0 );
+ var currHeight = clients[msg.sender].providerHeight;
+ bool providerHasClosed = false;
+ if ( providers[provider].data[currHeight].close > 0 ) {
+ providerHasClosed = true;
+ require( clients[msg.sender].paidUpTo == providers[provider].data[currHeight].close );
+ } else {
+ require( clients[msg.sender].paidUpTo == currentSchellingRound );
+ }
+
+ var bal = getTokenBalance(msg.sender);
+ if ( ! providerHasClosed ) {
+ providers[provider].data[currHeight].clientsCount--;
+ checkFloatingSupply(provider, currHeight, true, bal);
+ }
+ delete clients[msg.sender].providerAddress;
+ delete clients[msg.sender].providerHeight;
+ delete clients[msg.sender].lastSupplyID;
+ delete clients[msg.sender].paidUpTo;
+ delete clients[msg.sender].lastRate;
+ delete clients[msg.sender].providerConnected;
+ EClientLost(msg.sender, provider, currHeight, bal);
+ }
+ function checkReward(address addr) public constant returns (uint256 reward) {
+ /*
+ Polling the share from the token emission for clients and for providers.
+
+ @addr The address want to check.
+ @reward Accumulated amount.
+ */
+ if ( providers[addr].data[providers[addr].currentHeight].valid ) {
+ uint256 a;
+ (reward, a) = getProviderReward(addr, 0);
+ } else if ( clients[addr].providerAddress != 0x0 ) {
+ reward = getClientReward(0);
+ }
+ }
+ function getReward(address beneficiary, uint256 limit, address provider) isReady external returns (uint256 reward) {
+ /*
+ Polling the share from the token emission token emission for clients and for providers.
+
+ It is optionaly possible to give an address of a beneficiary for whom we can transfer the accumulated amount. In case we don’t enter any address then the amount will be transfered to the caller’s address.
+ As the interest should be checked at each schelling round in order to get the share from that so to avoid the overflow of the gas the number of the check-rounds should be limited.
+ Opcionalisan megadhato az ellenorzes koreinek szama. It is possible to enter optionaly the number of the check-rounds. If it is 0 then it is automatic.
+ Provider variable should only be entered if the real owner of the provider is not the caller’s address.
+ In case the client/provider was far behind then it is possible that this function should be called several times to check the total generated schelling rounds and to collect the share.
+ If is neighter a client nor a provider then the function is not available.
+ The tokens will be sent to the beneficiary from the address of the provider without any transaction fees.
+
+ @beneficiary Address of the beneficiary
+ @limit Quota of the check-rounds.
+ @provider Address of the provider
+ @reward Accumulated amount from the previous rounds.
+ */
+ var _limit = limit;
+ var _beneficiary = beneficiary;
+ var _provider = provider;
+ if ( _limit == 0 ) { _limit = gasProtectMaxRounds; }
+ if ( _beneficiary == 0x00 ) { _beneficiary = msg.sender; }
+ if ( _provider == 0x00 ) { _provider = msg.sender; }
+ uint256 clientReward;
+ uint256 providerReward;
+ if ( providers[_provider].data[providers[_provider].currentHeight].valid ) {
+ require( providers[_provider].data[providers[_provider].currentHeight].admin == msg.sender || msg.sender == _provider );
+ (providerReward, clientReward) = getProviderReward(_provider, _limit);
+ } else if ( clients[msg.sender].providerAddress != 0x00 ) {
+ clientReward = getClientReward(_limit);
+ } else {
+ throw;
+ }
+ if ( clientReward > 0 ) {
+ require( moduleHandler(moduleHandlerAddress).transfer(address(this), _beneficiary, clientReward, false) );
+ }
+ if ( providerReward > 0 ) {
+ require( moduleHandler(moduleHandlerAddress).transfer(address(this), provider, providerReward, false) );
+ }
+ EReward(msg.sender, provider, clientReward, providerReward);
+ }
+ function getClientReward(uint256 limit) internal returns (uint256 reward) {
+ /*
+ Inner function for the client in order to collect the share from the token emission
+
+ @limit Quota of checking the schelling-rounds.
+ @reward Collected token amount from the checked rounds.
+ */
+ uint256 value;
+ uint256 steps;
+ address provAddr;
+ uint256 provHeight;
+ bool interest = false;
+ var rate = clients[msg.sender].lastRate;
+ for ( uint256 a = (clients[msg.sender].paidUpTo + 1) ; a <= currentSchellingRound ; a++ ) {
+ if (globalFunds[a].reward > 0 && globalFunds[a].supply > 0) {
+ provAddr = clients[msg.sender].providerAddress;
+ provHeight = clients[msg.sender].providerHeight;
+ if ( providers[provAddr].data[provHeight].rateHistory[a].valid ) {
+ rate = providers[provAddr].data[provHeight].rateHistory[a].value;
+ }
+ if ( rate > 0 ) {
+ if ( a > providers[provAddr].data[provHeight].lastSupplyID ) {
+ interest = rightForInterest(providers[provAddr].data[provHeight].supply[providers[provAddr].data[provHeight].lastSupplyID], providers[provAddr].data[provHeight].priv);
+ } else {
+ interest = rightForInterest(providers[provAddr].data[provHeight].supply[a], providers[provAddr].data[provHeight].priv);
+ }
+ if ( interest ) {
+ if ( limit > 0 && steps > limit ) {
+ a--;
+ break;
+ }
+ if (clients[msg.sender].lastSupplyID < a) {
+ value = clients[msg.sender].supply[clients[msg.sender].lastSupplyID];
+ } else {
+ value = clients[msg.sender].supply[a];
+ }
+ if ( globalFunds[a].supply > 0) {
+ reward += value * globalFunds[a].reward / globalFunds[a].supply * uint256(rate) / 100;
+ }
+ steps++;
+ }
+ }
+ }
+ }
+ clients[msg.sender].lastRate = rate;
+ clients[msg.sender].paidUpTo = a-1;
+ }
+ function getProviderReward(address addr, uint256 limit) internal returns (uint256 providerReward, uint256 adminReward) {
+ /*
+ Inner function for the provider in order to collect the share from the token emission
+ @addr Address of the provider.
+ @limit Quota of the check-rounds.
+ @providerReward The reward of the provider’s address from the checked rounds.
+ @adminReward Admin’s reward from the checked rounds.
+ */
+ uint256 reward;
+ uint256 ownReward;
+ uint256 value;
+ uint256 steps;
+ uint256 currHeight = providers[addr].currentHeight;
+ uint256 LTSID = providers[addr].data[currHeight].lastSupplyID;
+ var rate = providers[addr].data[currHeight].lastPaidRate;
+ for ( uint256 a = (providers[addr].data[currHeight].paidUpTo + 1) ; a <= currentSchellingRound ; a++ ) {
+ if (globalFunds[a].reward > 0 && globalFunds[a].supply > 0) {
+ if ( providers[addr].data[currHeight].rateHistory[a].valid ) {
+ rate = providers[addr].data[currHeight].rateHistory[a].value;
+ }
+ if ( rate > 0 ) {
+ if ( ( a > LTSID && rightForInterest(providers[addr].data[currHeight].supply[LTSID], providers[addr].data[currHeight].priv) ||
+ rightForInterest(providers[addr].data[currHeight].supply[a], providers[addr].data[currHeight].priv) ) ) {
+ if ( limit > 0 && steps > limit ) {
+ a--;
+ break;
+ }
+ if ( LTSID < a ) {
+ value = providers[addr].data[currHeight].supply[LTSID];
+ } else {
+ value = providers[addr].data[currHeight].supply[a];
+ }
+ if ( globalFunds[a].supply > 0) {
+ reward += value * globalFunds[a].reward / globalFunds[a].supply * ( 100 - uint256(rate) ) / 100;
+ if ( providers[addr].data[currHeight].priv ) {
+ LTSID = providers[addr].data[currHeight].lastOwnSupplyID;
+ if ( LTSID < a ) {
+ value = providers[addr].data[currHeight].ownSupply[LTSID];
+ } else {
+ value = providers[addr].data[currHeight].ownSupply[a];
+ }
+ ownReward += value * globalFunds[a].reward / globalFunds[a].supply;
+ }
+ }
+ steps++;
+ }
+ }
+ }
+ }
+ providers[addr].data[currHeight].lastPaidRate = uint8(rate);
+ providers[addr].data[currHeight].paidUpTo = a-1;
+ if ( providers[addr].data[currHeight].isForRent ) {
+ providerReward = reward * rentRate / 100;
+ adminReward = reward - providerReward;
+ if ( providers[addr].data[currHeight].priv ) { providerReward += ownReward; }
+ } else {
+ providerReward = reward + ownReward;
+ }
+ }
+ function checkFloatingSupply(address providerAddress, uint256 providerHeight, bool neg, uint256 value) internal {
+ /*
+ Inner function for updating the database when some token change has happened.
+ In this case we are checking if despite the changes the provider is still entitled to the token emission. In case the legitimacy changes then the global supply should be set as well.
+
+ @providerAddress Provider address.
+ @providerHeight Provider height.
+ @neg the change was negative or not
+ @value Rate of the change
+ */
+ uint256 LSID = providers[providerAddress].data[providerHeight].lastSupplyID;
+ if ( currentSchellingRound != LSID ) {
+ if ( neg ) {
+ setRightForInterest(
+ providers[providerAddress].data[providerHeight].supply[LSID],
+ providers[providerAddress].data[providerHeight].supply[LSID] - value,
+ providers[providerAddress].data[providerHeight].priv
+ );
+ providers[providerAddress].data[providerHeight].supply[currentSchellingRound] = providers[providerAddress].data[providerHeight].supply[LSID] - value;
+ } else {
+ setRightForInterest(
+ providers[providerAddress].data[providerHeight].supply[LSID],
+ providers[providerAddress].data[providerHeight].supply[LSID] + value,
+ providers[providerAddress].data[providerHeight].priv
+ );
+ providers[providerAddress].data[providerHeight].supply[currentSchellingRound] = providers[providerAddress].data[providerHeight].supply[LSID] + value;
+ }
+ providers[providerAddress].data[providerHeight].lastSupplyID = currentSchellingRound;
+ } else {
+ if ( neg ) {
+ setRightForInterest(
+ getProviderCurrentSupply(providerAddress),
+ getProviderCurrentSupply(providerAddress) - value,
+ providers[providerAddress].data[providerHeight].priv
+ );
+ providers[providerAddress].data[providerHeight].supply[currentSchellingRound] -= value;
+ } else {
+ setRightForInterest(
+ getProviderCurrentSupply(providerAddress),
+ getProviderCurrentSupply(providerAddress) + value,
+ providers[providerAddress].data[providerHeight].priv
+ );
+ providers[providerAddress].data[providerHeight].supply[currentSchellingRound] += value;
+ }
+ }
+ }
+ function checkFloatingOwnSupply(address providerAddress, uint256 providerHeight, bool neg, uint256 value) internal {
+ /*
+ Inner function for updating the database in case token change has happened.
+ In this case we check if the provider despite the changes is still entitled to the token emission.
+ We just call this only if the private provider and it’s own capital bears emission.
+
+ @providerAddress Provider address.
+ @providerHeight Provider height.
+ @neg Was the change negative?
+ @value Rate of the change.
+ */
+ uint256 LSID = providers[providerAddress].data[providerHeight].lastOwnSupplyID;
+ if ( currentSchellingRound != LSID ) {
+ if ( neg ) {
+ setRightForInterest(
+ providers[providerAddress].data[providerHeight].ownSupply[LSID],
+ providers[providerAddress].data[providerHeight].ownSupply[LSID] - value,
+ true
+ );
+ providers[providerAddress].data[providerHeight].ownSupply[currentSchellingRound] = providers[providerAddress].data[providerHeight].ownSupply[LSID] - value;
+ } else {
+ setRightForInterest(
+ providers[providerAddress].data[providerHeight].ownSupply[LSID],
+ providers[providerAddress].data[providerHeight].ownSupply[LSID] + value,
+ true
+ );
+ providers[providerAddress].data[providerHeight].ownSupply[currentSchellingRound] = providers[providerAddress].data[providerHeight].ownSupply[LSID] + value;
+ }
+ providers[providerAddress].data[providerHeight].lastOwnSupplyID = currentSchellingRound;
+ } else {
+ if ( neg ) {
+ setRightForInterest(
+ getProviderCurrentSupply(providerAddress),
+ getProviderCurrentSupply(providerAddress) - value,
+ true
+ );
+ providers[providerAddress].data[providerHeight].ownSupply[currentSchellingRound] -= value;
+ } else {
+ setRightForInterest(
+ getProviderCurrentSupply(providerAddress),
+ getProviderCurrentSupply(providerAddress) + value,
+ true
+ );
+ providers[providerAddress].data[providerHeight].ownSupply[currentSchellingRound] += value;
+ }
+ }
+ }
+ function TEMath(uint256 a, uint256 b, bool neg) internal returns (uint256) {
+ /*
+ Inner function for the changes of the numbers
+
+ @a First number
+ @b 2nd number
+ @neg Operation with numbers. If it is TRUE then subtraction, if it is FALSE then addition.
+ */
+ if ( neg ) { return a-b; }
+ else { return a+b; }
+ }
+ function transferEvent_(address addr, uint256 value, bool neg) internal {
+ /*
+ Inner function for perceiving the changes of the balance and updating the database.
+ If the address is a provider and the balance is decreasing than can not let it go under the minimum level.
+
+ @addr The address where the change happened.
+ @value Rate of the change.
+ @neg ype of the change. If it is TRUE then the balance has been decreased if it is FALSE then it has been increased.
+ */
+ if ( clients[addr].providerAddress != 0 ) {
+ checkFloatingSupply(clients[addr].providerAddress, providers[clients[addr].providerAddress].currentHeight, ! neg, value);
+ if (clients[addr].lastSupplyID != currentSchellingRound) {
+ clients[addr].supply[currentSchellingRound] = TEMath(clients[addr].supply[clients[addr].lastSupplyID], value, neg);
+ clients[addr].lastSupplyID = currentSchellingRound;
+ } else {
+ clients[addr].supply[currentSchellingRound] = TEMath(clients[addr].supply[currentSchellingRound], value, neg);
+ }
+ } else if ( providers[addr].data[providers[addr].currentHeight].valid ) {
+ var currentHeight = providers[addr].currentHeight;
+ if ( neg ) {
+ uint256 balance = getTokenBalance(addr);
+ if ( providers[addr].data[currentHeight].priv ) {
+ require( balance-value >= minFundsForPrivate );
+ } else {
+ require( balance-value >= minFundsForPublic );
+ }
+ }
+ if ( providers[addr].data[currentHeight].priv ) {
+ checkFloatingOwnSupply(addr, currentHeight, ! neg, value);
+ }
+ }
+ }
+ function getTokenBalance(address addr) internal returns (uint256 balance) {
+ /*
+ Inner function in order to poll the token balance of the address.
+
+ @addr Address
+
+ @balance Balance of the address.
+ */
+ var (_success, _balance) = moduleHandler(moduleHandlerAddress).balanceOf(addr);
+ require( _success );
+ return _balance;
+ }
+ function checkICO() internal returns (bool isICO) {
+ /*
+ Inner function to check the ICO status.
+
+ @isICO Is the ICO in proccess or not?
+ */
+ var (_success, _isICO) = moduleHandler(moduleHandlerAddress).isICO();
+ require( _success );
+ return _isICO;
+ }
+ event EProviderOpen(address addr, uint256 height);
+ event EClientLost(address indexed client, address indexed provider, uint256 height, uint256 indexed value);
+ event ENewClient(address indexed client, address indexed provider, uint256 height, uint256 indexed value);
+ event EProviderClose(address indexed addr, uint256 height);
+ event EProviderDetailsChanged(address indexed addr, uint256 height, string website, string country, string info, uint8 rate, address admin);
+ event EReward(address indexed client, address indexed provider, uint256 clientreward, uint256 providerReward);
+}
diff --git a/test/compilationTests/corion/publisher.sol b/test/compilationTests/corion/publisher.sol
new file mode 100644
index 00000000..e94b9a92
--- /dev/null
+++ b/test/compilationTests/corion/publisher.sol
@@ -0,0 +1,278 @@
+pragma solidity ^0.4.11;
+
+import "./announcementTypes.sol";
+import "./module.sol";
+import "./moduleHandler.sol";
+import "./safeMath.sol";
+
+contract publisher is announcementTypes, module, safeMath {
+ /*
+ module callbacks
+ */
+ function transferEvent(address from, address to, uint256 value) external returns (bool success) {
+ /*
+ Transaction completed. This function is available only for moduleHandler
+ If a transaction is carried out from or to an address which participated in the objection of an announcement, its objection purport is automatically set
+ */
+ require( super.isModuleHandler(msg.sender) );
+ uint256 announcementID;
+ uint256 a;
+ // need reverse lookup
+ for ( a=0 ; a<opponents[from].length ; a++ ) {
+ announcementID = opponents[msg.sender][a];
+ if ( announcements[announcementID].end < block.number && announcements[announcementID].open ) {
+ announcements[announcementID].oppositionWeight = safeSub(announcements[a].oppositionWeight, value);
+ }
+ }
+ for ( a=0 ; a<opponents[to].length ; a++ ) {
+ announcementID = opponents[msg.sender][a];
+ if ( announcements[announcementID].end < block.number && announcements[announcementID].open ) {
+ announcements[announcementID].oppositionWeight = safeAdd(announcements[a].oppositionWeight, value);
+ }
+ }
+ return true;
+ }
+
+ /*
+ Pool
+ */
+
+ uint256 public minAnnouncementDelay = 40320;
+ uint256 public minAnnouncementDelayOnICO = 17280;
+ uint8 public oppositeRate = 33;
+
+ struct announcements_s {
+ announcementType Type;
+ uint256 start;
+ uint256 end;
+ bool open;
+ string announcement;
+ string link;
+ bool oppositable;
+ uint256 oppositionWeight;
+ bool result;
+
+ string _str;
+ uint256 _uint;
+ address _addr;
+ }
+ mapping(uint256 => announcements_s) public announcements;
+ uint256 announcementsLength = 1;
+
+ mapping (address => uint256[]) public opponents;
+
+ function publisher(address moduleHandler) {
+ /*
+ Installation function. The installer will be registered in the admin list automatically
+
+ @moduleHandler Address of moduleHandler
+ */
+ super.registerModuleHandler(moduleHandler);
+ }
+
+ function Announcements(uint256 id) public constant returns (uint256 Type, uint256 Start, uint256 End, bool Closed, string Announcement, string Link, bool Opposited, string _str, uint256 _uint, address _addr) {
+ /*
+ Announcement data query
+
+ @id Its identification
+
+ @Type Subject of announcement
+ @Start Height of announcement block
+ @End Planned completion of announcement
+ @Closed Closed or not
+ @Announcement Announcement text
+ @Link Link perhaps to a Forum
+ @Opposited Objected or not
+ @_str Text value
+ @_uint Number value
+ @_addr Address value
+ */
+ Type = uint256(announcements[id].Type);
+ Start = announcements[id].start;
+ End = announcements[id].end;
+ Closed = ! announcements[id].open;
+ Announcement = announcements[id].announcement;
+ Link = announcements[id].link;
+ if ( checkOpposited(announcements[id].oppositionWeight, announcements[id].oppositable) ) {
+ Opposited = true;
+ }
+ _str = announcements[id]._str;
+ _uint = announcements[id]._uint;
+ _addr = announcements[id]._addr;
+ }
+
+ function checkOpposited(uint256 weight, bool oppositable) public constant returns (bool success) {
+ /*
+ Veto check
+
+ @weight Purport of objections so far
+ @oppositable Opposable at all
+
+ @success Opposed or not
+ */
+ if ( ! oppositable ) { return false; }
+ var (_success, _amount) = moduleHandler(moduleHandlerAddress).totalSupply();
+ require( _success );
+ return _amount * oppositeRate / 100 > weight;
+ }
+
+ function newAnnouncement(announcementType Type, string Announcement, string Link, bool Oppositable, string _str, uint256 _uint, address _addr) onlyOwner external {
+ /*
+ New announcement. Can be called only by those in the admin list
+
+ @Type Topic of announcement
+ @Start height of announcement block
+ @End planned completion of announcement
+ @Closed Completed or not
+ @Announcement Announcement text
+ @Link link to a Forum
+ @Opposition opposed or not
+ @_str text box
+ @_uint number box
+ @_addr address box
+ */
+ announcementsLength++;
+ announcements[announcementsLength].Type = Type;
+ announcements[announcementsLength].start = block.number;
+ if ( checkICO() ) {
+ announcements[announcementsLength].end = block.number + minAnnouncementDelayOnICO;
+ } else {
+ announcements[announcementsLength].end = block.number + minAnnouncementDelay;
+ }
+ announcements[announcementsLength].open = true;
+ announcements[announcementsLength].announcement = Announcement;
+ announcements[announcementsLength].link = Link;
+ announcements[announcementsLength].oppositable = Oppositable;
+ announcements[announcementsLength].oppositionWeight = 0;
+ announcements[announcementsLength].result = false;
+ announcements[announcementsLength]._str = _str;
+ announcements[announcementsLength]._uint = _uint;
+ announcements[announcementsLength]._addr = _addr;
+ ENewAnnouncement(announcementsLength, Type);
+ }
+
+ function closeAnnouncement(uint256 id) onlyOwner external {
+ /*
+ Close announcement. It can be closed only by those in the admin list. Windup is allowed only after the announcement is completed.
+
+ @id Announcement identification
+ */
+ require( announcements[id].open && announcements[id].end < block.number );
+ if ( ! checkOpposited(announcements[id].oppositionWeight, announcements[id].oppositable) ) {
+ announcements[id].result = true;
+ if ( announcements[id].Type == announcementType.newModule ) {
+ require( moduleHandler(moduleHandlerAddress).newModule(announcements[id]._str, announcements[id]._addr, true, true) );
+ } else if ( announcements[id].Type == announcementType.dropModule ) {
+ require( moduleHandler(moduleHandlerAddress).dropModule(announcements[id]._str, true) );
+ } else if ( announcements[id].Type == announcementType.replaceModule ) {
+ require( moduleHandler(moduleHandlerAddress).replaceModule(announcements[id]._str, announcements[id]._addr, true) );
+ } else if ( announcements[id].Type == announcementType.replaceModuleHandler) {
+ require( moduleHandler(moduleHandlerAddress).replaceModuleHandler(announcements[id]._addr) );
+ } else if ( announcements[id].Type == announcementType.transactionFeeRate ||
+ announcements[id].Type == announcementType.transactionFeeMin ||
+ announcements[id].Type == announcementType.transactionFeeMax ||
+ announcements[id].Type == announcementType.transactionFeeBurn ) {
+ require( moduleHandler(moduleHandlerAddress).configureModule("token", announcements[id].Type, announcements[id]._uint) );
+ } else if ( announcements[id].Type == announcementType.providerPublicFunds ||
+ announcements[id].Type == announcementType.providerPrivateFunds ||
+ announcements[id].Type == announcementType.providerPrivateClientLimit ||
+ announcements[id].Type == announcementType.providerPublicMinRate ||
+ announcements[id].Type == announcementType.providerPublicMaxRate ||
+ announcements[id].Type == announcementType.providerPrivateMinRate ||
+ announcements[id].Type == announcementType.providerPrivateMaxRate ||
+ announcements[id].Type == announcementType.providerGasProtect ||
+ announcements[id].Type == announcementType.providerInterestMinFunds ||
+ announcements[id].Type == announcementType.providerRentRate ) {
+ require( moduleHandler(moduleHandlerAddress).configureModule("provider", announcements[id].Type, announcements[id]._uint) );
+ } else if ( announcements[id].Type == announcementType.schellingRoundBlockDelay ||
+ announcements[id].Type == announcementType.schellingCheckRounds ||
+ announcements[id].Type == announcementType.schellingCheckAboves ||
+ announcements[id].Type == announcementType.schellingRate ) {
+ require( moduleHandler(moduleHandlerAddress).configureModule("schelling", announcements[id].Type, announcements[id]._uint) );
+ } else if ( announcements[id].Type == announcementType.publisherMinAnnouncementDelay) {
+ minAnnouncementDelay = announcements[id]._uint;
+ } else if ( announcements[id].Type == announcementType.publisherOppositeRate) {
+ oppositeRate = uint8(announcements[id]._uint);
+ }
+ }
+ announcements[id].end = block.number;
+ announcements[id].open = false;
+ }
+
+ function oppositeAnnouncement(uint256 id) external {
+ /*
+ Opposition of announcement
+ If announcement is opposable, anyone owning a token can oppose it
+ Opposition is automatically with the total amount of tokens
+ If the quantity of his tokens changes, the purport of his opposition changes automatically
+ The prime time is the windup of the announcement, because this is the moment when the number of tokens in opposition are counted.
+ One address is entitled to be in oppositon only once. An opposition cannot be withdrawn.
+ Running announcements can be opposed only.
+
+ @id Announcement identification
+ */
+ uint256 newArrayID = 0;
+ bool foundEmptyArrayID = false;
+ require( announcements[id].open );
+ require( announcements[id].oppositable );
+ for ( uint256 a=0 ; a<opponents[msg.sender].length ; a++ ) {
+ require( opponents[msg.sender][a] != id );
+ if ( ! announcements[opponents[msg.sender][a]].open) {
+ delete opponents[msg.sender][a];
+ if ( ! foundEmptyArrayID ) {
+ foundEmptyArrayID = true;
+ newArrayID = a;
+ }
+ }
+ if ( ! foundEmptyArrayID ) {
+ foundEmptyArrayID = true;
+ newArrayID = a;
+ }
+ }
+ var (_success, _balance) = moduleHandler(moduleHandlerAddress).balanceOf(msg.sender);
+ require( _success );
+ require( _balance > 0);
+ if ( foundEmptyArrayID ) {
+ opponents[msg.sender][newArrayID] = id;
+ } else {
+ opponents[msg.sender].push(id);
+ }
+ announcements[id].oppositionWeight += _balance;
+ EOppositeAnnouncement(id, msg.sender, _balance);
+ }
+
+ function invalidateAnnouncement(uint256 id) onlyOwner external {
+ /*
+ Withdraw announcement. Only those in the admin list can withdraw it.
+
+ @id Announcement identification
+ */
+ require( announcements[id].open );
+ announcements[id].end = block.number;
+ announcements[id].open = false;
+ EInvalidateAnnouncement(id);
+ }
+
+ modifier onlyOwner() {
+ /*
+ Only the owner is allowed to call it.
+ */
+ require( moduleHandler(moduleHandlerAddress).owners(msg.sender) );
+ _;
+ }
+
+ function checkICO() internal returns (bool isICO) {
+ /*
+ Inner function to check the ICO status.
+ @bool Is the ICO in proccess or not?
+ */
+ var (_success, _isICO) = moduleHandler(moduleHandlerAddress).isICO();
+ require( _success );
+ return _isICO;
+ }
+
+ event ENewAnnouncement(uint256 id, announcementType typ);
+ event EOppositeAnnouncement(uint256 id, address addr, uint256 value);
+ event EInvalidateAnnouncement(uint256 id);
+ event ECloseAnnouncement(uint256 id);
+}
diff --git a/test/compilationTests/corion/safeMath.sol b/test/compilationTests/corion/safeMath.sol
new file mode 100644
index 00000000..9e27d379
--- /dev/null
+++ b/test/compilationTests/corion/safeMath.sol
@@ -0,0 +1,33 @@
+pragma solidity ^0.4.11;
+
+contract safeMath {
+ function safeAdd(uint256 a, uint256 b) internal returns(uint256) {
+ /*
+ Biztonsagos hozzadas. Tulcsordulas elleni vedelem.
+ A vegeredmeny nem lehet kevesebb mint az @a, ha igen megall a kod.
+
+ @a Amihez hozzaadni kell
+ @b Amennyit hozzaadni kell.
+ @uint256 Vegeredmeny.
+ */
+ if ( b > 0 ) {
+ assert( a + b > a );
+ }
+ return a + b;
+ }
+
+ function safeSub(uint256 a, uint256 b) internal returns(uint256) {
+ /*
+ Biztonsagos kivonas. Tulcsordulas elleni vedelem.
+ A vegeredmeny nem lehet tobb mint az @a, ha igen megall a kod.
+
+ @a Amibol kivonni kell.
+ @b Amennyit kivonni kell.
+ @uint256 Vegeredmeny.
+ */
+ if ( b > 0 ) {
+ assert( a - b < a );
+ }
+ return a - b;
+ }
+} \ No newline at end of file
diff --git a/test/compilationTests/corion/schelling.sol b/test/compilationTests/corion/schelling.sol
new file mode 100644
index 00000000..8c8e093c
--- /dev/null
+++ b/test/compilationTests/corion/schelling.sol
@@ -0,0 +1,577 @@
+pragma solidity ^0.4.11;
+
+import "./announcementTypes.sol";
+import "./module.sol";
+import "./moduleHandler.sol";
+import "./safeMath.sol";
+
+contract schellingVars {
+ /*
+ Common enumerations and structures of the Schelling and Database contract.
+ */
+ enum voterStatus {
+ base,
+ afterPrepareVote,
+ afterSendVoteOk,
+ afterSendVoteBad
+ }
+ struct _rounds {
+ uint256 totalAboveWeight;
+ uint256 totalBelowWeight;
+ uint256 reward;
+ uint256 blockHeight;
+ bool voted;
+ }
+ struct _voter {
+ uint256 roundID;
+ bytes32 hash;
+ voterStatus status;
+ bool voteResult;
+ uint256 rewards;
+ }
+}
+
+contract schellingDB is safeMath, schellingVars {
+ /*
+ Schelling database contract.
+ */
+ address private owner;
+ function replaceOwner(address newOwner) external returns(bool) {
+ require( owner == 0x00 || msg.sender == owner );
+ owner = newOwner;
+ return true;
+ }
+ modifier isOwner { require( msg.sender == owner ); _; }
+ /*
+ Constructor
+ */
+ function schellingDB() {
+ rounds.length = 2;
+ rounds[0].blockHeight = block.number;
+ currentSchellingRound = 1;
+ }
+ /*
+ Funds
+ */
+ mapping(address => uint256) private funds;
+ function getFunds(address _owner) constant returns(bool, uint256) {
+ return (true, funds[_owner]);
+ }
+ function setFunds(address _owner, uint256 _amount) isOwner external returns(bool) {
+ funds[_owner] = _amount;
+ return true;
+ }
+ /*
+ Rounds
+ */
+ _rounds[] private rounds;
+ function getRound(uint256 _id) constant returns(bool, uint256, uint256, uint256, uint256, bool) {
+ if ( rounds.length <= _id ) { return (false, 0, 0, 0, 0, false); }
+ else { return (true, rounds[_id].totalAboveWeight, rounds[_id].totalBelowWeight, rounds[_id].reward, rounds[_id].blockHeight, rounds[_id].voted); }
+ }
+ function pushRound(uint256 _totalAboveWeight, uint256 _totalBelowWeight, uint256 _reward, uint256 _blockHeight, bool _voted) isOwner external returns(bool, uint256) {
+ return (true, rounds.push(_rounds(_totalAboveWeight, _totalBelowWeight, _reward, _blockHeight, _voted)));
+ }
+ function setRound(uint256 _id, uint256 _totalAboveWeight, uint256 _totalBelowWeight, uint256 _reward, uint256 _blockHeight, bool _voted) isOwner external returns(bool) {
+ rounds[_id] = _rounds(_totalAboveWeight, _totalBelowWeight, _reward, _blockHeight, _voted);
+ return true;
+ }
+ function getCurrentRound() constant returns(bool, uint256) {
+ return (true, rounds.length-1);
+ }
+ /*
+ Voter
+ */
+ mapping(address => _voter) private voter;
+ function getVoter(address _owner) constant returns(bool success, uint256 roundID,
+ bytes32 hash, voterStatus status, bool voteResult, uint256 rewards) {
+ roundID = voter[_owner].roundID;
+ hash = voter[_owner].hash;
+ status = voter[_owner].status;
+ voteResult = voter[_owner].voteResult;
+ rewards = voter[_owner].rewards;
+ success = true;
+ }
+ function setVoter(address _owner, uint256 _roundID, bytes32 _hash, voterStatus _status, bool _voteResult, uint256 _rewards) isOwner external returns(bool) {
+ voter[_owner] = _voter(
+ _roundID,
+ _hash,
+ _status,
+ _voteResult,
+ _rewards
+ );
+ return true;
+ }
+ /*
+ Schelling Token emission
+ */
+ mapping(uint256 => uint256) private schellingExpansion;
+ function getSchellingExpansion(uint256 _id) constant returns(bool, uint256) {
+ return (true, schellingExpansion[_id]);
+ }
+ function setSchellingExpansion(uint256 _id, uint256 _expansion) isOwner external returns(bool) {
+ schellingExpansion[_id] = _expansion;
+ return true;
+ }
+ /*
+ Current Schelling Round
+ */
+ uint256 private currentSchellingRound;
+ function setCurrentSchellingRound(uint256 _id) isOwner external returns(bool) {
+ currentSchellingRound = _id;
+ return true;
+ }
+ function getCurrentSchellingRound() constant returns(bool, uint256) {
+ return (true, currentSchellingRound);
+ }
+}
+
+contract schelling is module, announcementTypes, schellingVars {
+ /*
+ Schelling contract
+ */
+ /*
+ module callbacks
+ */
+ function replaceModule(address addr) external returns (bool) {
+ require( super.isModuleHandler(msg.sender) );
+ require( db.replaceOwner(addr) );
+ super._replaceModule(addr);
+ return true;
+ }
+ function transferEvent(address from, address to, uint256 value) external returns (bool) {
+ /*
+ Transaction completed. This function can be called only by the ModuleHandler.
+ If this contract is the receiver, the amount will be added to the prize pool of the current round.
+
+ @from From who
+ @to To who
+ @value Amount
+ @bool Was the transaction succesfull?
+ */
+ require( super.isModuleHandler(msg.sender) );
+ if ( to == address(this) ) {
+ var currentRound = getCurrentRound();
+ var round = getRound(currentRound);
+ round.reward += value;
+ setRound(currentRound, round);
+ }
+ return true;
+ }
+ modifier isReady {
+ var (_success, _active) = super.isActive();
+ require( _success && _active );
+ _;
+ }
+ /*
+ Schelling database functions.
+ */
+ function getFunds(address addr) internal returns (uint256) {
+ var (a, b) = db.getFunds(addr);
+ require( a );
+ return b;
+ }
+ function setFunds(address addr, uint256 amount) internal {
+ require( db.setFunds(addr, amount) );
+ }
+ function setVoter(address owner, _voter voter) internal {
+ require( db.setVoter(owner,
+ voter.roundID,
+ voter.hash,
+ voter.status,
+ voter.voteResult,
+ voter.rewards
+ ) );
+ }
+ function getVoter(address addr) internal returns (_voter) {
+ var (a, b, c, d, e, f) = db.getVoter(addr);
+ require( a );
+ return _voter(b, c, d, e, f);
+ }
+ function setRound(uint256 id, _rounds round) internal {
+ require( db.setRound(id,
+ round.totalAboveWeight,
+ round.totalBelowWeight,
+ round.reward,
+ round.blockHeight,
+ round.voted
+ ) );
+ }
+ function pushRound(_rounds round) internal returns (uint256) {
+ var (a, b) = db.pushRound(
+ round.totalAboveWeight,
+ round.totalBelowWeight,
+ round.reward,
+ round.blockHeight,
+ round.voted
+ );
+ require( a );
+ return b;
+ }
+ function getRound(uint256 id) internal returns (_rounds) {
+ var (a, b, c, d, e, f) = db.getRound(id);
+ require( a );
+ return _rounds(b, c, d, e, f);
+ }
+ function getCurrentRound() internal returns (uint256) {
+ var (a, b) = db.getCurrentRound();
+ require( a );
+ return b;
+ }
+ function setCurrentSchellingRound(uint256 id) internal {
+ require( db.setCurrentSchellingRound(id) );
+ }
+ function getCurrentSchellingRound() internal returns(uint256) {
+ var (a, b) = db.getCurrentSchellingRound();
+ require( a );
+ return b;
+ }
+ function setSchellingExpansion(uint256 id, uint256 amount) internal {
+ require( db.setSchellingExpansion(id, amount) );
+ }
+ function getSchellingExpansion(uint256 id) internal returns(uint256) {
+ var (a, b) = db.getSchellingExpansion(id);
+ require( a );
+ return b;
+ }
+ /*
+ Schelling module
+ */
+ uint256 private roundBlockDelay = 720;
+ uint8 private interestCheckRounds = 7;
+ uint8 private interestCheckAboves = 4;
+ uint256 private interestRate = 300;
+ uint256 private interestRateM = 1e3;
+
+ bytes1 public aboveChar = 0x31;
+ bytes1 public belowChar = 0x30;
+ schellingDB private db;
+
+ function schelling(address _moduleHandler, address _db, bool _forReplace) {
+ /*
+ Installation function.
+
+ @_moduleHandler Address of ModuleHandler.
+ @_db Address of the database.
+ @_forReplace This address will be replaced with the old one or not.
+ @_icoExpansionAddress This address can turn schelling runds during ICO.
+ */
+ db = schellingDB(_db);
+ super.registerModuleHandler(_moduleHandler);
+ if ( ! _forReplace ) {
+ require( db.replaceOwner(this) );
+ }
+ }
+ function configure(announcementType a, uint256 b) external returns(bool) {
+ /*
+ Can be called only by the ModuleHandler.
+
+ @a Sort of configuration
+ @b Value
+ */
+ require( super.isModuleHandler(msg.sender) );
+ if ( a == announcementType.schellingRoundBlockDelay ) { roundBlockDelay = b; }
+ else if ( a == announcementType.schellingCheckRounds ) { interestCheckRounds = uint8(b); }
+ else if ( a == announcementType.schellingCheckAboves ) { interestCheckAboves = uint8(b); }
+ else if ( a == announcementType.schellingRate ) { interestRate = b; }
+ else { return false; }
+ return true;
+ }
+ function prepareVote(bytes32 votehash, uint256 roundID) isReady noContract external {
+ /*
+ Initializing manual vote.
+ Only the hash of vote will be sent. (Envelope sending).
+ The address must be in default state, that is there are no vote in progress.
+ Votes can be sent only on the actually Schelling round.
+
+ @votehash Hash of the vote
+ @roundID Number of Schelling round
+ */
+ nextRound();
+
+ var currentRound = getCurrentRound();
+ var round = getRound(currentRound);
+ _voter memory voter;
+ uint256 funds;
+
+ require( roundID == currentRound );
+
+ voter = getVoter(msg.sender);
+ funds = getFunds(msg.sender);
+
+ require( funds > 0 );
+ require( voter.status == voterStatus.base );
+ voter.roundID = currentRound;
+ voter.hash = votehash;
+ voter.status = voterStatus.afterPrepareVote;
+
+ setVoter(msg.sender, voter);
+ round.voted = true;
+
+ setRound(currentRound, round);
+ }
+ function sendVote(string vote) isReady noContract external {
+ /*
+ Check vote (Envelope opening)
+ Only the sent “envelopes” can be opened.
+ Envelope opening only in the next Schelling round.
+ If the vote invalid, the deposit will be lost.
+ If the “envelope” was opened later than 1,5 Schelling round, the vote is automatically invalid, and deposit can be lost.
+ Lost deposits will be 100% burned.
+
+ @vote Hash of the content of the vote.
+ */
+ nextRound();
+
+ var currentRound = getCurrentRound();
+ _rounds memory round;
+ _voter memory voter;
+ uint256 funds;
+
+ bool lostEverything;
+ voter = getVoter(msg.sender);
+ round = getRound(voter.roundID);
+ funds = getFunds(msg.sender);
+
+ require( voter.status == voterStatus.afterPrepareVote );
+ require( voter.roundID < currentRound );
+ if ( sha3(vote) == voter.hash ) {
+ delete voter.hash;
+ if (round.blockHeight+roundBlockDelay/2 >= block.number) {
+ if ( bytes(vote)[0] == aboveChar ) {
+ voter.status = voterStatus.afterSendVoteOk;
+ round.totalAboveWeight += funds;
+ voter.voteResult = true;
+ } else if ( bytes(vote)[0] == belowChar ) {
+ voter.status = voterStatus.afterSendVoteOk;
+ round.totalBelowWeight += funds;
+ } else { lostEverything = true; }
+ } else {
+ voter.status = voterStatus.afterSendVoteBad;
+ }
+ } else { lostEverything = true; }
+ if ( lostEverything ) {
+ require( moduleHandler(moduleHandlerAddress).burn(address(this), funds) );
+ delete funds;
+ delete voter.status;
+ }
+
+ setVoter(msg.sender, voter);
+ setRound(voter.roundID, round);
+ setFunds(msg.sender, funds);
+ }
+ function checkVote() isReady noContract external {
+ /*
+ Checking votes.
+ Vote checking only after the envelope opening Schelling round.
+ Deposit will be lost, if the vote wrong, or invalid.
+ The right votes take share of deposits.
+ */
+ nextRound();
+
+ var currentRound = getCurrentRound();
+ _rounds memory round;
+ _voter memory voter;
+ uint256 funds;
+
+ voter = getVoter(msg.sender);
+ round = getRound(voter.roundID);
+ funds = getFunds(msg.sender);
+
+ require( voter.status == voterStatus.afterSendVoteOk ||
+ voter.status == voterStatus.afterSendVoteBad );
+ if ( round.blockHeight+roundBlockDelay/2 <= block.number ) {
+ if ( isWinner(round, voter.voteResult) && voter.status == voterStatus.afterSendVoteOk ) {
+ voter.rewards += funds * round.reward / getRoundWeight(round.totalAboveWeight, round.totalBelowWeight);
+ } else {
+ require( moduleHandler(moduleHandlerAddress).burn(address(this), funds) );
+ delete funds;
+ }
+ delete voter.status;
+ delete voter.roundID;
+ } else { throw; }
+
+ setVoter(msg.sender, voter);
+ setFunds(msg.sender, funds);
+ }
+ function getRewards(address beneficiary) isReady noContract external {
+ /*
+ Redeem of prize.
+ The prizes will be collected here, and with this function can be transferred to the account of the user.
+ Optionally there can be an address of a beneficiary added, which address the prize will be sent to. Without beneficiary, the owner is the default address.
+ Prize will be sent from the Schelling address without any transaction fee.
+
+ @beneficiary Address of the beneficiary
+ */
+ var voter = getVoter(msg.sender);
+ var funds = getFunds(msg.sender);
+
+ address _beneficiary = msg.sender;
+ if (beneficiary != 0x0) { _beneficiary = beneficiary; }
+ uint256 reward;
+ require( voter.rewards > 0 );
+ require( voter.status == voterStatus.base );
+ reward = voter.rewards;
+ delete voter.rewards;
+ require( moduleHandler(moduleHandlerAddress).transfer(address(this), _beneficiary, reward, false) );
+
+ setVoter(msg.sender, voter);
+ }
+ function checkReward() public constant returns (uint256 reward) {
+ /*
+ Withdraw of the amount of the prize (it’s only information).
+
+ @reward Prize
+ */
+ var voter = getVoter(msg.sender);
+ return voter.rewards;
+ }
+ function nextRound() internal returns (bool) {
+ /*
+ Inside function, checks the time of the Schelling round and if its needed, creates a new Schelling round.
+ */
+ var currentRound = getCurrentRound();
+ var round = getRound(currentRound);
+ _rounds memory newRound;
+ _rounds memory prevRound;
+ var currentSchellingRound = getCurrentSchellingRound();
+
+ if ( round.blockHeight+roundBlockDelay > block.number) { return false; }
+
+ newRound.blockHeight = block.number;
+ if ( ! round.voted ) {
+ newRound.reward = round.reward;
+ }
+ uint256 aboves;
+ for ( uint256 a=currentRound ; a>=currentRound-interestCheckRounds ; a-- ) {
+ if (a == 0) { break; }
+ prevRound = getRound(a);
+ if ( prevRound.totalAboveWeight > prevRound.totalBelowWeight ) { aboves++; }
+ }
+ uint256 expansion;
+ if ( aboves >= interestCheckAboves ) {
+ expansion = getTotalSupply() * interestRate / interestRateM / 100;
+ }
+
+ currentSchellingRound++;
+
+ pushRound(newRound);
+ setSchellingExpansion(currentSchellingRound, expansion);
+ require( moduleHandler(moduleHandlerAddress).broadcastSchellingRound(currentSchellingRound, expansion) );
+ return true;
+ }
+ function addFunds(uint256 amount) isReady noContract external {
+ /*
+ Deposit taking.
+ Every participant entry with his own deposit.
+ In case of wrong vote only this amount of deposit will be burn.
+ The deposit will be sent to the address of Schelling, charged with transaction fee.
+
+ @amount Amount of deposit.
+ */
+ var voter = getVoter(msg.sender);
+ var funds = getFunds(msg.sender);
+
+ var (a, b) = moduleHandler(moduleHandlerAddress).isICO();
+ require( b && b );
+ require( voter.status == voterStatus.base );
+ require( amount > 0 );
+ require( moduleHandler(moduleHandlerAddress).transfer(msg.sender, address(this), amount, true) );
+ funds += amount;
+
+ setFunds(msg.sender, funds);
+ }
+ function getFunds() isReady noContract external {
+ /*
+ Deposit withdrawn.
+ If the deposit isn’t lost, it can be withdrawn.
+ By withdrawn, the deposit will be sent from Schelling address to the users address, charged with transaction fee..
+ */
+ var voter = getVoter(msg.sender);
+ var funds = getFunds(msg.sender);
+
+ require( funds > 0 );
+ require( voter.status == voterStatus.base );
+ setFunds(msg.sender, 0);
+
+ require( moduleHandler(moduleHandlerAddress).transfer(address(this), msg.sender, funds, true) );
+ }
+ function getCurrentSchellingRoundID() public constant returns (uint256) {
+ /*
+ Number of actual Schelling round.
+
+ @uint256 Schelling round.
+ */
+ return getCurrentSchellingRound();
+ }
+ function getSchellingRound(uint256 id) public constant returns (uint256 expansion) {
+ /*
+ Amount of token emission of the Schelling round.
+
+ @id Number of Schelling round
+ @expansion Amount of token emission
+ */
+ return getSchellingExpansion(id);
+ }
+ function getRoundWeight(uint256 aboveW, uint256 belowW) internal returns (uint256) {
+ /*
+ Inside function for calculating the weights of the votes.
+
+ @aboveW Weight of votes: ABOVE
+ @belowW Weight of votes: BELOW
+ @uint256 Calculatet weight
+ */
+ if ( aboveW == belowW ) {
+ return aboveW + belowW;
+ } else if ( aboveW > belowW ) {
+ return aboveW;
+ } else if ( aboveW < belowW) {
+ return belowW;
+ }
+ }
+ function isWinner(_rounds round, bool aboveVote) internal returns (bool) {
+ /*
+ Inside function for calculating the result of the game.
+
+ @round Structure of Schelling round.
+ @aboveVote Is the vote = ABOVE or not
+ @bool Result
+ */
+ if ( round.totalAboveWeight == round.totalBelowWeight ||
+ ( round.totalAboveWeight > round.totalBelowWeight && aboveVote ) ) {
+ return true;
+ }
+ return false;
+ }
+
+ function getTotalSupply() internal returns (uint256 amount) {
+ /*
+ Inside function for querying the whole amount of the tokens.
+
+ @uint256 Whole token amount
+ */
+ var (_success, _amount) = moduleHandler(moduleHandlerAddress).totalSupply();
+ require( _success );
+ return _amount;
+ }
+
+ function getTokenBalance(address addr) internal returns (uint256 balance) {
+ /*
+ Inner function in order to poll the token balance of the address.
+
+ @addr Address
+
+ @balance Balance of the address.
+ */
+ var (_success, _balance) = moduleHandler(moduleHandlerAddress).balanceOf(addr);
+ require( _success );
+ return _balance;
+ }
+
+ modifier noContract {
+ /*
+ Contract can’t call this function, only a natural address.
+ */
+ require( msg.sender == tx.origin ); _;
+ }
+}
diff --git a/test/compilationTests/corion/token.sol b/test/compilationTests/corion/token.sol
new file mode 100644
index 00000000..3aa0bf23
--- /dev/null
+++ b/test/compilationTests/corion/token.sol
@@ -0,0 +1,518 @@
+pragma solidity ^0.4.11;
+
+import "./announcementTypes.sol";
+import "./safeMath.sol";
+import "./module.sol";
+import "./moduleHandler.sol";
+import "./tokenDB.sol";
+
+contract thirdPartyContractAbstract {
+ function receiveCorionToken(address, uint256, bytes) external returns (bool, uint256) {}
+ function approvedCorionToken(address, uint256, bytes) external returns (bool) {}
+}
+
+contract token is safeMath, module, announcementTypes {
+ /*
+ module callbacks
+ */
+ function replaceModule(address addr) external returns (bool success) {
+ require( super.isModuleHandler(msg.sender) );
+ require( db.replaceOwner(addr) );
+ super._replaceModule(addr);
+ return true;
+ }
+ modifier isReady {
+ var (_success, _active) = super.isActive();
+ require( _success && _active );
+ _;
+ }
+ /**
+ *
+ * @title Corion Platform Token
+ * @author iFA @ Corion Platform
+ *
+ */
+ string public name = "Corion";
+ string public symbol = "COR";
+ uint8 public decimals = 6;
+
+ tokenDB public db;
+ address public icoAddr;
+ uint256 public transactionFeeRate = 20;
+ uint256 public transactionFeeRateM = 1e3;
+ uint256 public transactionFeeMin = 20000;
+ uint256 public transactionFeeMax = 5000000;
+ uint256 public transactionFeeBurn = 80;
+ address public exchangeAddress;
+ bool public isICO = true;
+
+ mapping(address => bool) public genesis;
+
+ function token(bool forReplace, address moduleHandler, address dbAddr, address icoContractAddr, address exchangeContractAddress, address[] genesisAddr, uint256[] genesisValue) payable {
+ /*
+ Installation function
+
+ When _icoAddr is defined, 0.2 ether has to be attached as many times as many genesis addresses are given
+
+ @forReplace This address will be replaced with the old one or not.
+ @moduleHandler Modulhandler's address
+ @dbAddr Address of database
+ @icoContractAddr Address of ICO contract
+ @exchangeContractAddress Address of Market in order to buy gas during ICO
+ @genesisAddr Array of Genesis addresses
+ @genesisValue Array of balance of genesis addresses
+ */
+ super.registerModuleHandler(moduleHandler);
+ require( dbAddr != 0x00 );
+ require( icoContractAddr != 0x00 );
+ require( exchangeContractAddress != 0x00 );
+ db = tokenDB(dbAddr);
+ icoAddr = icoContractAddr;
+ exchangeAddress = exchangeContractAddress;
+ isICO = ! forReplace;
+ if ( ! forReplace ) {
+ require( db.replaceOwner(this) );
+ assert( genesisAddr.length == genesisValue.length );
+ require( this.balance >= genesisAddr.length * 0.2 ether );
+ for ( uint256 a=0 ; a<genesisAddr.length ; a++ ) {
+ genesis[genesisAddr[a]] = true;
+ require( db.increase(genesisAddr[a], genesisValue[a]) );
+ if ( ! genesisAddr[a].send(0.2 ether) ) {}
+ Mint(genesisAddr[a], genesisValue[a]);
+ }
+ }
+ }
+
+ function closeIco() external returns (bool success) {
+ /*
+ ICO finished. It can be called only by ICO contract
+
+ @success Was the Function successful?
+ */
+ require( msg.sender == icoAddr );
+ isICO = false;
+ return true;
+ }
+
+ /**
+ * @notice `msg.sender` approves `spender` to spend `amount` tokens on its behalf.
+ * @param spender The address of the account able to transfer the tokens
+ * @param amount The amount of tokens to be approved for transfer
+ * @param nonce The transaction count of the authorised address
+ * @return True if the approval was successful
+ */
+ function approve(address spender, uint256 amount, uint256 nonce) isReady external returns (bool success) {
+ /*
+ Authorise another address to use a certain quantity of the authorising owner’s balance
+
+ @spender Address of authorised party
+ @amount Token quantity
+ @nonce Transaction count
+
+ @success Was the Function successful?
+ */
+ _approve(spender, amount, nonce);
+ return true;
+ }
+
+ /**
+ * @notice `msg.sender` approves `spender` to spend `amount` tokens on its behalf and notify the spender from your approve with your `extraData` data.
+ * @param spender The address of the account able to transfer the tokens
+ * @param amount The amount of tokens to be approved for transfer
+ * @param nonce The transaction count of the authorised address
+ * @param extraData Data to give forward to the receiver
+ * @return True if the approval was successful
+ */
+ function approveAndCall(address spender, uint256 amount, uint256 nonce, bytes extraData) isReady external returns (bool success) {
+ /*
+ Authorise another address to use a certain quantity of the authorising owner’s balance
+ Following the transaction the receiver address `approvedCorionToken` function is called by the given data
+
+ @spender Authorized address
+ @amount Token quantity
+ @extraData Extra data to be received by the receiver
+ @nonce Transaction count
+
+ @success Was the Function successful?
+ */
+ _approve(spender, amount, nonce);
+ require( thirdPartyContractAbstract(spender).approvedCorionToken(msg.sender, amount, extraData) );
+ return true;
+ }
+
+ function _approve(address spender, uint256 amount, uint256 nonce) internal {
+ /*
+ Internal Function to authorise another address to use a certain quantity of the authorising owner’s balance.
+ If the transaction count not match the authorise fails.
+
+ @spender Address of authorised party
+ @amount Token quantity
+ @nonce Transaction count
+ */
+ require( msg.sender != spender );
+ require( db.balanceOf(msg.sender) >= amount );
+ require( db.setAllowance(msg.sender, spender, amount, nonce) );
+ Approval(msg.sender, spender, amount);
+ }
+
+ function allowance(address owner, address spender) constant returns (uint256 remaining, uint256 nonce) {
+ /*
+ Get the quantity of tokens given to be used
+
+ @owner Authorising address
+ @spender Authorised address
+
+ @remaining Tokens to be spent
+ @nonce Transaction count
+ */
+ var (_success, _remaining, _nonce) = db.getAllowance(owner, spender);
+ require( _success );
+ return (_remaining, _nonce);
+ }
+
+ /**
+ * @notice Send `amount` Corion tokens to `to` from `msg.sender`
+ * @param to The address of the recipient
+ * @param amount The amount of tokens to be transferred
+ * @return Whether the transfer was successful or not
+ */
+ function transfer(address to, uint256 amount) isReady external returns (bool success) {
+ /*
+ Start transaction, token is sent from caller’s address to receiver’s address
+ Transaction fee is to be deducted.
+ If receiver is not a natural address but a person, he will be called
+
+ @to To who
+ @amount Quantity
+
+ @success Was the Function successful?
+ */
+ bytes memory _data;
+ if ( isContract(to) ) {
+ _transferToContract(msg.sender, to, amount, _data);
+ } else {
+ _transfer( msg.sender, to, amount, true);
+ }
+ Transfer(msg.sender, to, amount, _data);
+ return true;
+ }
+
+ /**
+ * @notice Send `amount` tokens to `to` from `from` on the condition it is approved by `from`
+ * @param from The address holding the tokens being transferred
+ * @param to The address of the recipient
+ * @param amount The amount of tokens to be transferred
+ * @return True if the transfer was successful
+ */
+ function transferFrom(address from, address to, uint256 amount) isReady external returns (bool success) {
+ /*
+ Start transaction to send a quantity from a given address to another address. (approve / allowance). This can be called only by the address approved in advance
+ Transaction fee is to be deducted
+ If receiver is not a natural address but a person, he will be called
+
+ @from From who.
+ @to To who
+ @amount Quantity
+
+ @success Was the Function successful?
+ */
+ if ( from != msg.sender ) {
+ var (_success, _reamining, _nonce) = db.getAllowance(from, msg.sender);
+ require( _success );
+ _reamining = safeSub(_reamining, amount);
+ _nonce = safeAdd(_nonce, 1);
+ require( db.setAllowance(from, msg.sender, _reamining, _nonce) );
+ AllowanceUsed(msg.sender, from, amount);
+ }
+ bytes memory _data;
+ if ( isContract(to) ) {
+ _transferToContract(from, to, amount, _data);
+ } else {
+ _transfer( from, to, amount, true);
+ }
+ Transfer(from, to, amount, _data);
+ return true;
+ }
+
+ /**
+ * @notice Send `amount` tokens to `to` from `from` on the condition it is approved by `from`
+ * @param from The address holding the tokens being transferred
+ * @param to The address of the recipient
+ * @param amount The amount of tokens to be transferred
+ * @return True if the transfer was successful
+ */
+ function transferFromByModule(address from, address to, uint256 amount, bool fee) isReady external returns (bool success) {
+ /*
+ Start transaction to send a quantity from a given address to another address
+ Only ModuleHandler can call it
+
+ @from From who
+ @to To who.
+ @amount Quantity
+ @fee Deduct transaction fee - yes or no?
+
+ @success Was the Function successful?
+ */
+ bytes memory _data;
+ require( super.isModuleHandler(msg.sender) );
+ _transfer( from, to, amount, fee);
+ Transfer(from, to, amount, _data);
+ return true;
+ }
+
+ /**
+ * @notice Send `amount` Corion tokens to `to` from `msg.sender` and notify the receiver from your transaction with your `extraData` data
+ * @param to The contract address of the recipient
+ * @param amount The amount of tokens to be transferred
+ * @param extraData Data to give forward to the receiver
+ * @return Whether the transfer was successful or not
+ */
+ function transfer(address to, uint256 amount, bytes extraData) isReady external returns (bool success) {
+ /*
+ Start transaction to send a quantity from a given address to another address
+ After transaction the function `receiveCorionToken`of the receiver is called by the given data
+ When sending an amount, it is possible the total amount cannot be processed, the remaining amount is sent back with no fee charged
+
+ @to To who.
+ @amount Quantity
+ @extraData Extra data the receiver will get
+
+ @success Was the Function successful?
+ */
+ if ( isContract(to) ) {
+ _transferToContract(msg.sender, to, amount, extraData);
+ } else {
+ _transfer( msg.sender, to, amount, true);
+ }
+ Transfer(msg.sender, to, amount, extraData);
+ return true;
+ }
+
+ function _transferToContract(address from, address to, uint256 amount, bytes extraData) internal {
+ /*
+ Internal function to start transactions to a contract
+
+ @from From who
+ @to To who.
+ @amount Quantity
+ @extraData Extra data the receiver will get
+ */
+ _transfer(from, to, amount, exchangeAddress == to);
+ var (_success, _back) = thirdPartyContractAbstract(to).receiveCorionToken(from, amount, extraData);
+ require( _success );
+ require( amount > _back );
+ if ( _back > 0 ) {
+ _transfer(to, from, _back, false);
+ }
+ _processTransactionFee(from, amount - _back);
+ }
+
+ function _transfer(address from, address to, uint256 amount, bool fee) internal {
+ /*
+ Internal function to start transactions. When Tokens are sent, transaction fee is charged
+ During ICO transactions are allowed only from genesis addresses.
+ After sending the tokens, the ModuleHandler is notified and it will broadcast the fact among members
+
+ The 0xa636a97578d26a3b76b060bbc18226d954cf3757 address are blacklisted.
+
+ @from From who
+ @to To who
+ @amount Quantity
+ @fee Deduct transaction fee - yes or no?
+ */
+ if( fee ) {
+ var (success, _fee) = getTransactionFee(amount);
+ require( success );
+ require( db.balanceOf(from) >= amount + _fee );
+ }
+ require( from != 0x00 && to != 0x00 && to != 0xa636a97578d26a3b76b060bbc18226d954cf3757 );
+ require( ( ! isICO) || genesis[from] );
+ require( db.decrease(from, amount) );
+ require( db.increase(to, amount) );
+ if ( fee ) { _processTransactionFee(from, amount); }
+ if ( isICO ) {
+ require( ico(icoAddr).setInterestDB(from, db.balanceOf(from)) );
+ require( ico(icoAddr).setInterestDB(to, db.balanceOf(to)) );
+ }
+ require( moduleHandler(moduleHandlerAddress).broadcastTransfer(from, to, amount) );
+ }
+
+ /**
+ * @notice Transaction fee will be deduced from `owner` for transacting `value`
+ * @param owner The address where will the transaction fee deduced
+ * @param value The base for calculating the fee
+ * @return True if the transfer was successful
+ */
+ function processTransactionFee(address owner, uint256 value) isReady external returns (bool success) {
+ /*
+ Charge transaction fee. It can be called only by moduleHandler
+
+ @owner From who.
+ @value Quantity to calculate the fee
+
+ @success Was the Function successful?
+ */
+ require( super.isModuleHandler(msg.sender) );
+ _processTransactionFee(owner, value);
+ return true;
+ }
+
+ function _processTransactionFee(address owner, uint256 value) internal {
+ /*
+ Internal function to charge the transaction fee. A certain quantity is burnt, the rest is sent to the Schelling game prize pool.
+ No transaction fee during ICO.
+
+ @owner From who
+ @value Quantity to calculate the fee
+ */
+ if ( isICO ) { return; }
+ var (_success, _fee) = getTransactionFee(value);
+ require( _success );
+ uint256 _forBurn = _fee * transactionFeeBurn / 100;
+ uint256 _forSchelling = _fee - _forBurn;
+ bool _found;
+ address _schellingAddr;
+ (_success, _found, _schellingAddr) = moduleHandler(moduleHandlerAddress).getModuleAddressByName('Schelling');
+ require( _success );
+ if ( _schellingAddr != 0x00 && _found) {
+ require( db.decrease(owner, _forSchelling) );
+ require( db.increase(_schellingAddr, _forSchelling) );
+ _burn(owner, _forBurn);
+ bytes memory _data;
+ Transfer(owner, _schellingAddr, _forSchelling, _data);
+ require( moduleHandler(moduleHandlerAddress).broadcastTransfer(owner, _schellingAddr, _forSchelling) );
+ } else {
+ _burn(owner, _fee);
+ }
+ }
+
+ function getTransactionFee(uint256 value) public constant returns (bool success, uint256 fee) {
+ /*
+ Transaction fee query.
+
+ @value Quantity to calculate the fee
+
+ @success Was the Function successful?
+ @fee Amount of Transaction fee
+ */
+ if ( isICO ) { return (true, 0); }
+ fee = value * transactionFeeRate / transactionFeeRateM / 100;
+ if ( fee > transactionFeeMax ) { fee = transactionFeeMax; }
+ else if ( fee < transactionFeeMin ) { fee = transactionFeeMin; }
+ return (true, fee);
+ }
+
+ function mint(address owner, uint256 value) isReady external returns (bool success) {
+ /*
+ Generating tokens. It can be called only by ICO contract or the moduleHandler.
+
+ @owner Address
+ @value Amount.
+
+ @success Was the Function successful?
+ */
+ require( super.isModuleHandler(msg.sender) || msg.sender == icoAddr );
+ _mint(owner, value);
+ return true;
+ }
+
+ function _mint(address owner, uint256 value) internal {
+ /*
+ Internal function to generate tokens
+
+ @owner Token is credited to this address
+ @value Quantity
+ */
+ require( db.increase(owner, value) );
+ require( moduleHandler(moduleHandlerAddress).broadcastTransfer(0x00, owner, value) );
+ if ( isICO ) {
+ require( ico(icoAddr).setInterestDB(owner, db.balanceOf(owner)) );
+ }
+ Mint(owner, value);
+ }
+
+ function burn(address owner, uint256 value) isReady external returns (bool success) {
+ /*
+ Burning the token. Can call only modulehandler
+
+ @owner Burn the token from this address
+ @value Quantity
+
+ @success Was the Function successful?
+ */
+ require( super.isModuleHandler(msg.sender) );
+ _burn(owner, value);
+ return true;
+ }
+
+ function _burn(address owner, uint256 value) internal {
+ /*
+ Internal function to burn the token
+
+ @owner Burn the token from this address
+ @value Quantity
+ */
+ require( db.decrease(owner, value) );
+ require( moduleHandler(moduleHandlerAddress).broadcastTransfer(owner, 0x00, value) );
+ Burn(owner, value);
+ }
+
+ function isContract(address addr) internal returns (bool success) {
+ /*
+ Internal function to check if the given address is natural, or a contract
+
+ @addr Address to be checked
+
+ @success Is the address crontact or not
+ */
+ uint256 _codeLength;
+ assembly {
+ _codeLength := extcodesize(addr)
+ }
+ return _codeLength > 0;
+ }
+
+ function balanceOf(address owner) constant returns (uint256 value) {
+ /*
+ Token balance query
+
+ @owner Address
+
+ @value Balance of address
+ */
+ return db.balanceOf(owner);
+ }
+
+ function totalSupply() constant returns (uint256 value) {
+ /*
+ Total token quantity query
+
+ @value Total token quantity
+ */
+ return db.totalSupply();
+ }
+
+ function configure(announcementType aType, uint256 value) isReady external returns(bool success) {
+ /*
+ Token settings configuration.It can be call only by moduleHandler
+
+ @aType Type of setting
+ @value Value
+
+ @success Was the Function successful?
+ */
+ require( super.isModuleHandler(msg.sender) );
+ if ( aType == announcementType.transactionFeeRate ) { transactionFeeRate = value; }
+ else if ( aType == announcementType.transactionFeeMin ) { transactionFeeMin = value; }
+ else if ( aType == announcementType.transactionFeeMax ) { transactionFeeMax = value; }
+ else if ( aType == announcementType.transactionFeeBurn ) { transactionFeeBurn = value; }
+ else { return false; }
+ return true;
+ }
+
+ event AllowanceUsed(address indexed spender, address indexed owner, uint256 indexed value);
+ event Mint(address indexed addr, uint256 indexed value);
+ event Burn(address indexed addr, uint256 indexed value);
+ event Approval(address indexed _owner, address indexed _spender, uint256 _value);
+ event Transfer(address indexed _from, address indexed _to, uint256 indexed _value, bytes _extraData);
+}
diff --git a/test/compilationTests/corion/tokenDB.sol b/test/compilationTests/corion/tokenDB.sol
new file mode 100644
index 00000000..6de1b6c3
--- /dev/null
+++ b/test/compilationTests/corion/tokenDB.sol
@@ -0,0 +1,77 @@
+pragma solidity ^0.4.11;
+
+import "./safeMath.sol";
+import "./owned.sol";
+
+contract tokenDB is safeMath, ownedDB {
+
+ struct allowance_s {
+ uint256 amount;
+ uint256 nonce;
+ }
+
+ mapping(address => mapping(address => allowance_s)) public allowance;
+ mapping (address => uint256) public balanceOf;
+ uint256 public totalSupply;
+
+ function increase(address owner, uint256 value) external returns(bool success) {
+ /*
+ Increase of balance of the address in database. Only owner can call it.
+
+ @owner Address
+ @value Quantity
+
+ @success Was the Function successful?
+ */
+ require( isOwner() );
+ balanceOf[owner] = safeAdd(balanceOf[owner], value);
+ totalSupply = safeAdd(totalSupply, value);
+ return true;
+ }
+
+ function decrease(address owner, uint256 value) external returns(bool success) {
+ /*
+ Decrease of balance of the address in database. Only owner can call it.
+
+ @owner Address
+ @value Quantity
+
+ @success Was the Function successful?
+ */
+ require( isOwner() );
+ balanceOf[owner] = safeSub(balanceOf[owner], value);
+ totalSupply = safeSub(totalSupply, value);
+ return true;
+ }
+
+ function setAllowance(address owner, address spender, uint256 amount, uint256 nonce) external returns(bool success) {
+ /*
+ Set allowance in the database. Only owner can call it.
+
+ @owner Owner address
+ @spender Spender address
+ @amount Amount to set
+ @nonce Transaction count
+
+ @success Was the Function successful?
+ */
+ require( isOwner() );
+ allowance[owner][spender].amount = amount;
+ allowance[owner][spender].nonce = nonce;
+ return true;
+ }
+
+ function getAllowance(address owner, address spender) constant returns(bool success, uint256 remaining, uint256 nonce) {
+ /*
+ Get allowance from the database.
+
+ @owner Owner address
+ @spender Spender address
+
+ @success Was the Function successful?
+ @remaining Remaining amount of the allowance
+ @nonce Transaction count
+ */
+ return ( true, allowance[owner][spender].amount, allowance[owner][spender].nonce );
+ }
+}
diff --git a/test/compilationTests/milestonetracker/LICENSE b/test/compilationTests/milestonetracker/LICENSE
new file mode 100644
index 00000000..733c0723
--- /dev/null
+++ b/test/compilationTests/milestonetracker/LICENSE
@@ -0,0 +1,675 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users. We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors. You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
+
+ Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+ For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+ Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so. This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software. The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products. If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+ Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary. To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Use with the GNU Affero General Public License.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+ {one line to give the program's name and a brief idea of what it does.}
+ Copyright (C) {year} {name of author}
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+ {project} Copyright (C) {year} {fullname}
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+<http://www.gnu.org/licenses/>.
+
+ The GNU General Public License does not permit incorporating your program
+into proprietary programs. If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License. But first, please read
+<http://www.gnu.org/philosophy/why-not-lgpl.html>.
+
diff --git a/test/compilationTests/milestonetracker/MilestoneTracker.sol b/test/compilationTests/milestonetracker/MilestoneTracker.sol
new file mode 100644
index 00000000..318330df
--- /dev/null
+++ b/test/compilationTests/milestonetracker/MilestoneTracker.sol
@@ -0,0 +1,367 @@
+pragma solidity ^0.4.6;
+
+/*
+ Copyright 2016, Jordi Baylina
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+/// @title MilestoneTracker Contract
+/// @author Jordi Baylina
+/// @dev This contract tracks the
+
+
+/// is rules the relation betwen a donor and a recipient
+/// in order to guaranty to the donor that the job will be done and to guaranty
+/// to the recipient that he will be paid
+
+
+/// @dev We use the RLP library to decode RLP so that the donor can approve one
+/// set of milestone changes at a time.
+/// https://github.com/androlo/standard-contracts/blob/master/contracts/src/codec/RLP.sol
+import "RLP.sol";
+
+
+
+/// @dev This contract allows for `recipient` to set and modify milestones
+contract MilestoneTracker {
+ using RLP for RLP.RLPItem;
+ using RLP for RLP.Iterator;
+ using RLP for bytes;
+
+ struct Milestone {
+ string description; // Description of this milestone
+ string url; // A link to more information (swarm gateway)
+ uint minCompletionDate; // Earliest UNIX time the milestone can be paid
+ uint maxCompletionDate; // Latest UNIX time the milestone can be paid
+ address milestoneLeadLink;
+ // Similar to `recipient`but for this milestone
+ address reviewer; // Can reject the completion of this milestone
+ uint reviewTime; // How many seconds the reviewer has to review
+ address paymentSource; // Where the milestone payment is sent from
+ bytes payData; // Data defining how much ether is sent where
+
+ MilestoneStatus status; // Current status of the milestone
+ // (Completed, AuthorizedForPayment...)
+ uint doneTime; // UNIX time when the milestone was marked DONE
+ }
+
+ // The list of all the milestones.
+ Milestone[] public milestones;
+
+ address public recipient; // Calls functions in the name of the recipient
+ address public donor; // Calls functions in the name of the donor
+ address public arbitrator; // Calls functions in the name of the arbitrator
+
+ enum MilestoneStatus {
+ AcceptedAndInProgress,
+ Completed,
+ AuthorizedForPayment,
+ Canceled
+ }
+
+ // True if the campaign has been canceled
+ bool public campaignCanceled;
+
+ // True if an approval on a change to `milestones` is a pending
+ bool public changingMilestones;
+
+ // The pending change to `milestones` encoded in RLP
+ bytes public proposedMilestones;
+
+
+ /// @dev The following modifiers only allow specific roles to call functions
+ /// with these modifiers
+ modifier onlyRecipient { if (msg.sender != recipient) throw; _; }
+ modifier onlyArbitrator { if (msg.sender != arbitrator) throw; _; }
+ modifier onlyDonor { if (msg.sender != donor) throw; _; }
+
+ /// @dev The following modifiers prevent functions from being called if the
+ /// campaign has been canceled or if new milestones are being proposed
+ modifier campaignNotCanceled { if (campaignCanceled) throw; _; }
+ modifier notChanging { if (changingMilestones) throw; _; }
+
+ // @dev Events to make the payment movements easy to find on the blockchain
+ event NewMilestoneListProposed();
+ event NewMilestoneListUnproposed();
+ event NewMilestoneListAccepted();
+ event ProposalStatusChanged(uint idProposal, MilestoneStatus newProposal);
+ event CampaignCanceled();
+
+
+///////////
+// Constructor
+///////////
+
+ /// @notice The Constructor creates the Milestone contract on the blockchain
+ /// @param _arbitrator Address assigned to be the arbitrator
+ /// @param _donor Address assigned to be the donor
+ /// @param _recipient Address assigned to be the recipient
+ function MilestoneTracker (
+ address _arbitrator,
+ address _donor,
+ address _recipient
+ ) {
+ arbitrator = _arbitrator;
+ donor = _donor;
+ recipient = _recipient;
+ }
+
+
+/////////
+// Helper functions
+/////////
+
+ /// @return The number of milestones ever created even if they were canceled
+ function numberOfMilestones() constant returns (uint) {
+ return milestones.length;
+ }
+
+
+////////
+// Change players
+////////
+
+ /// @notice `onlyArbitrator` Reassigns the arbitrator to a new address
+ /// @param _newArbitrator The new arbitrator
+ function changeArbitrator(address _newArbitrator) onlyArbitrator {
+ arbitrator = _newArbitrator;
+ }
+
+ /// @notice `onlyDonor` Reassigns the `donor` to a new address
+ /// @param _newDonor The new donor
+ function changeDonor(address _newDonor) onlyDonor {
+ donor = _newDonor;
+ }
+
+ /// @notice `onlyRecipient` Reassigns the `recipient` to a new address
+ /// @param _newRecipient The new recipient
+ function changeRecipient(address _newRecipient) onlyRecipient {
+ recipient = _newRecipient;
+ }
+
+
+////////////
+// Creation and modification of Milestones
+////////////
+
+ /// @notice `onlyRecipient` Proposes new milestones or changes old
+ /// milestones, this will require a user interface to be built up to
+ /// support this functionality as asks for RLP encoded bytecode to be
+ /// generated, until this interface is built you can use this script:
+ /// https://github.com/Giveth/milestonetracker/blob/master/js/milestonetracker_helper.js
+ /// the functions milestones2bytes and bytes2milestones will enable the
+ /// recipient to encode and decode a list of milestones, also see
+ /// https://github.com/Giveth/milestonetracker/blob/master/README.md
+ /// @param _newMilestones The RLP encoded list of milestones; each milestone
+ /// has these fields:
+ /// string description,
+ /// string url,
+ /// uint minCompletionDate, // seconds since 1/1/1970 (UNIX time)
+ /// uint maxCompletionDate, // seconds since 1/1/1970 (UNIX time)
+ /// address milestoneLeadLink,
+ /// address reviewer,
+ /// uint reviewTime
+ /// address paymentSource,
+ /// bytes payData,
+ function proposeMilestones(bytes _newMilestones
+ ) onlyRecipient campaignNotCanceled {
+ proposedMilestones = _newMilestones;
+ changingMilestones = true;
+ NewMilestoneListProposed();
+ }
+
+
+////////////
+// Normal actions that will change the state of the milestones
+////////////
+
+ /// @notice `onlyRecipient` Cancels the proposed milestones and reactivates
+ /// the previous set of milestones
+ function unproposeMilestones() onlyRecipient campaignNotCanceled {
+ delete proposedMilestones;
+ changingMilestones = false;
+ NewMilestoneListUnproposed();
+ }
+
+ /// @notice `onlyDonor` Approves the proposed milestone list
+ /// @param _hashProposals The sha3() of the proposed milestone list's
+ /// bytecode; this confirms that the `donor` knows the set of milestones
+ /// they are approving
+ function acceptProposedMilestones(bytes32 _hashProposals
+ ) onlyDonor campaignNotCanceled {
+
+ uint i;
+
+ if (!changingMilestones) throw;
+ if (sha3(proposedMilestones) != _hashProposals) throw;
+
+ // Cancel all the unfinished milestones
+ for (i=0; i<milestones.length; i++) {
+ if (milestones[i].status != MilestoneStatus.AuthorizedForPayment) {
+ milestones[i].status = MilestoneStatus.Canceled;
+ }
+ }
+ // Decode the RLP encoded milestones and add them to the milestones list
+ bytes memory mProposedMilestones = proposedMilestones;
+
+ var itmProposals = mProposedMilestones.toRLPItem(true);
+
+ if (!itmProposals.isList()) throw;
+
+ var itrProposals = itmProposals.iterator();
+
+ while(itrProposals.hasNext()) {
+
+
+ var itmProposal = itrProposals.next();
+
+ Milestone milestone = milestones[milestones.length ++];
+
+ if (!itmProposal.isList()) throw;
+
+ var itrProposal = itmProposal.iterator();
+
+ milestone.description = itrProposal.next().toAscii();
+ milestone.url = itrProposal.next().toAscii();
+ milestone.minCompletionDate = itrProposal.next().toUint();
+ milestone.maxCompletionDate = itrProposal.next().toUint();
+ milestone.milestoneLeadLink = itrProposal.next().toAddress();
+ milestone.reviewer = itrProposal.next().toAddress();
+ milestone.reviewTime = itrProposal.next().toUint();
+ milestone.paymentSource = itrProposal.next().toAddress();
+ milestone.payData = itrProposal.next().toData();
+
+ milestone.status = MilestoneStatus.AcceptedAndInProgress;
+
+ }
+
+ delete proposedMilestones;
+ changingMilestones = false;
+ NewMilestoneListAccepted();
+ }
+
+ /// @notice `onlyRecipientOrLeadLink`Marks a milestone as DONE and
+ /// ready for review
+ /// @param _idMilestone ID of the milestone that has been completed
+ function markMilestoneComplete(uint _idMilestone)
+ campaignNotCanceled notChanging
+ {
+ if (_idMilestone >= milestones.length) throw;
+ Milestone milestone = milestones[_idMilestone];
+ if ( (msg.sender != milestone.milestoneLeadLink)
+ &&(msg.sender != recipient))
+ throw;
+ if (milestone.status != MilestoneStatus.AcceptedAndInProgress) throw;
+ if (now < milestone.minCompletionDate) throw;
+ if (now > milestone.maxCompletionDate) throw;
+ milestone.status = MilestoneStatus.Completed;
+ milestone.doneTime = now;
+ ProposalStatusChanged(_idMilestone, milestone.status);
+ }
+
+ /// @notice `onlyReviewer` Approves a specific milestone
+ /// @param _idMilestone ID of the milestone that is approved
+ function approveCompletedMilestone(uint _idMilestone)
+ campaignNotCanceled notChanging
+ {
+ if (_idMilestone >= milestones.length) throw;
+ Milestone milestone = milestones[_idMilestone];
+ if ((msg.sender != milestone.reviewer) ||
+ (milestone.status != MilestoneStatus.Completed)) throw;
+
+ authorizePayment(_idMilestone);
+ }
+
+ /// @notice `onlyReviewer` Rejects a specific milestone's completion and
+ /// reverts the `milestone.status` back to the `AcceptedAndInProgress`
+ /// state
+ /// @param _idMilestone ID of the milestone that is being rejected
+ function rejectMilestone(uint _idMilestone)
+ campaignNotCanceled notChanging
+ {
+ if (_idMilestone >= milestones.length) throw;
+ Milestone milestone = milestones[_idMilestone];
+ if ((msg.sender != milestone.reviewer) ||
+ (milestone.status != MilestoneStatus.Completed)) throw;
+
+ milestone.status = MilestoneStatus.AcceptedAndInProgress;
+ ProposalStatusChanged(_idMilestone, milestone.status);
+ }
+
+ /// @notice `onlyRecipientOrLeadLink` Sends the milestone payment as
+ /// specified in `payData`; the recipient can only call this after the
+ /// `reviewTime` has elapsed
+ /// @param _idMilestone ID of the milestone to be paid out
+ function requestMilestonePayment(uint _idMilestone
+ ) campaignNotCanceled notChanging {
+ if (_idMilestone >= milestones.length) throw;
+ Milestone milestone = milestones[_idMilestone];
+ if ( (msg.sender != milestone.milestoneLeadLink)
+ &&(msg.sender != recipient))
+ throw;
+ if ((milestone.status != MilestoneStatus.Completed) ||
+ (now < milestone.doneTime + milestone.reviewTime))
+ throw;
+
+ authorizePayment(_idMilestone);
+ }
+
+ /// @notice `onlyRecipient` Cancels a previously accepted milestone
+ /// @param _idMilestone ID of the milestone to be canceled
+ function cancelMilestone(uint _idMilestone)
+ onlyRecipient campaignNotCanceled notChanging
+ {
+ if (_idMilestone >= milestones.length) throw;
+ Milestone milestone = milestones[_idMilestone];
+ if ((milestone.status != MilestoneStatus.AcceptedAndInProgress) &&
+ (milestone.status != MilestoneStatus.Completed))
+ throw;
+
+ milestone.status = MilestoneStatus.Canceled;
+ ProposalStatusChanged(_idMilestone, milestone.status);
+ }
+
+ /// @notice `onlyArbitrator` Forces a milestone to be paid out as long as it
+ /// has not been paid or canceled
+ /// @param _idMilestone ID of the milestone to be paid out
+ function arbitrateApproveMilestone(uint _idMilestone
+ ) onlyArbitrator campaignNotCanceled notChanging {
+ if (_idMilestone >= milestones.length) throw;
+ Milestone milestone = milestones[_idMilestone];
+ if ((milestone.status != MilestoneStatus.AcceptedAndInProgress) &&
+ (milestone.status != MilestoneStatus.Completed))
+ throw;
+ authorizePayment(_idMilestone);
+ }
+
+ /// @notice `onlyArbitrator` Cancels the entire campaign voiding all
+ /// milestones.
+ function arbitrateCancelCampaign() onlyArbitrator campaignNotCanceled {
+ campaignCanceled = true;
+ CampaignCanceled();
+ }
+
+ // @dev This internal function is executed when the milestone is paid out
+ function authorizePayment(uint _idMilestone) internal {
+ if (_idMilestone >= milestones.length) throw;
+ Milestone milestone = milestones[_idMilestone];
+ // Recheck again to not pay twice
+ if (milestone.status == MilestoneStatus.AuthorizedForPayment) throw;
+ milestone.status = MilestoneStatus.AuthorizedForPayment;
+ if (!milestone.paymentSource.call.value(0)(milestone.payData))
+ throw;
+ ProposalStatusChanged(_idMilestone, milestone.status);
+ }
+}
diff --git a/test/compilationTests/milestonetracker/README.md b/test/compilationTests/milestonetracker/README.md
new file mode 100644
index 00000000..84fb980e
--- /dev/null
+++ b/test/compilationTests/milestonetracker/README.md
@@ -0,0 +1,3 @@
+Giveth milestone tracker, originally from
+
+https://github.com/Giveth/milestonetracker/
diff --git a/test/compilationTests/milestonetracker/RLP.sol b/test/compilationTests/milestonetracker/RLP.sol
new file mode 100644
index 00000000..5bb27bb2
--- /dev/null
+++ b/test/compilationTests/milestonetracker/RLP.sol
@@ -0,0 +1,416 @@
+pragma solidity ^0.4.6;
+
+/**
+* @title RLPReader
+*
+* RLPReader is used to read and parse RLP encoded data in memory.
+*
+* @author Andreas Olofsson (androlo1980@gmail.com)
+*/
+library RLP {
+
+ uint constant DATA_SHORT_START = 0x80;
+ uint constant DATA_LONG_START = 0xB8;
+ uint constant LIST_SHORT_START = 0xC0;
+ uint constant LIST_LONG_START = 0xF8;
+
+ uint constant DATA_LONG_OFFSET = 0xB7;
+ uint constant LIST_LONG_OFFSET = 0xF7;
+
+
+ struct RLPItem {
+ uint _unsafe_memPtr; // Pointer to the RLP-encoded bytes.
+ uint _unsafe_length; // Number of bytes. This is the full length of the string.
+ }
+
+ struct Iterator {
+ RLPItem _unsafe_item; // Item that's being iterated over.
+ uint _unsafe_nextPtr; // Position of the next item in the list.
+ }
+
+ /* Iterator */
+
+ function next(Iterator memory self) internal constant returns (RLPItem memory subItem) {
+ if(hasNext(self)) {
+ var ptr = self._unsafe_nextPtr;
+ var itemLength = _itemLength(ptr);
+ subItem._unsafe_memPtr = ptr;
+ subItem._unsafe_length = itemLength;
+ self._unsafe_nextPtr = ptr + itemLength;
+ }
+ else
+ throw;
+ }
+
+ function next(Iterator memory self, bool strict) internal constant returns (RLPItem memory subItem) {
+ subItem = next(self);
+ if(strict && !_validate(subItem))
+ throw;
+ return;
+ }
+
+ function hasNext(Iterator memory self) internal constant returns (bool) {
+ var item = self._unsafe_item;
+ return self._unsafe_nextPtr < item._unsafe_memPtr + item._unsafe_length;
+ }
+
+ /* RLPItem */
+
+ /// @dev Creates an RLPItem from an array of RLP encoded bytes.
+ /// @param self The RLP encoded bytes.
+ /// @return An RLPItem
+ function toRLPItem(bytes memory self) internal constant returns (RLPItem memory) {
+ uint len = self.length;
+ if (len == 0) {
+ return RLPItem(0, 0);
+ }
+ uint memPtr;
+ assembly {
+ memPtr := add(self, 0x20)
+ }
+ return RLPItem(memPtr, len);
+ }
+
+ /// @dev Creates an RLPItem from an array of RLP encoded bytes.
+ /// @param self The RLP encoded bytes.
+ /// @param strict Will throw if the data is not RLP encoded.
+ /// @return An RLPItem
+ function toRLPItem(bytes memory self, bool strict) internal constant returns (RLPItem memory) {
+ var item = toRLPItem(self);
+ if(strict) {
+ uint len = self.length;
+ if(_payloadOffset(item) > len)
+ throw;
+ if(_itemLength(item._unsafe_memPtr) != len)
+ throw;
+ if(!_validate(item))
+ throw;
+ }
+ return item;
+ }
+
+ /// @dev Check if the RLP item is null.
+ /// @param self The RLP item.
+ /// @return 'true' if the item is null.
+ function isNull(RLPItem memory self) internal constant returns (bool ret) {
+ return self._unsafe_length == 0;
+ }
+
+ /// @dev Check if the RLP item is a list.
+ /// @param self The RLP item.
+ /// @return 'true' if the item is a list.
+ function isList(RLPItem memory self) internal constant returns (bool ret) {
+ if (self._unsafe_length == 0)
+ return false;
+ uint memPtr = self._unsafe_memPtr;
+ assembly {
+ ret := iszero(lt(byte(0, mload(memPtr)), 0xC0))
+ }
+ }
+
+ /// @dev Check if the RLP item is data.
+ /// @param self The RLP item.
+ /// @return 'true' if the item is data.
+ function isData(RLPItem memory self) internal constant returns (bool ret) {
+ if (self._unsafe_length == 0)
+ return false;
+ uint memPtr = self._unsafe_memPtr;
+ assembly {
+ ret := lt(byte(0, mload(memPtr)), 0xC0)
+ }
+ }
+
+ /// @dev Check if the RLP item is empty (string or list).
+ /// @param self The RLP item.
+ /// @return 'true' if the item is null.
+ function isEmpty(RLPItem memory self) internal constant returns (bool ret) {
+ if(isNull(self))
+ return false;
+ uint b0;
+ uint memPtr = self._unsafe_memPtr;
+ assembly {
+ b0 := byte(0, mload(memPtr))
+ }
+ return (b0 == DATA_SHORT_START || b0 == LIST_SHORT_START);
+ }
+
+ /// @dev Get the number of items in an RLP encoded list.
+ /// @param self The RLP item.
+ /// @return The number of items.
+ function items(RLPItem memory self) internal constant returns (uint) {
+ if (!isList(self))
+ return 0;
+ uint b0;
+ uint memPtr = self._unsafe_memPtr;
+ assembly {
+ b0 := byte(0, mload(memPtr))
+ }
+ uint pos = memPtr + _payloadOffset(self);
+ uint last = memPtr + self._unsafe_length - 1;
+ uint itms;
+ while(pos <= last) {
+ pos += _itemLength(pos);
+ itms++;
+ }
+ return itms;
+ }
+
+ /// @dev Create an iterator.
+ /// @param self The RLP item.
+ /// @return An 'Iterator' over the item.
+ function iterator(RLPItem memory self) internal constant returns (Iterator memory it) {
+ if (!isList(self))
+ throw;
+ uint ptr = self._unsafe_memPtr + _payloadOffset(self);
+ it._unsafe_item = self;
+ it._unsafe_nextPtr = ptr;
+ }
+
+ /// @dev Return the RLP encoded bytes.
+ /// @param self The RLPItem.
+ /// @return The bytes.
+ function toBytes(RLPItem memory self) internal constant returns (bytes memory bts) {
+ var len = self._unsafe_length;
+ if (len == 0)
+ return;
+ bts = new bytes(len);
+ _copyToBytes(self._unsafe_memPtr, bts, len);
+ }
+
+ /// @dev Decode an RLPItem into bytes. This will not work if the
+ /// RLPItem is a list.
+ /// @param self The RLPItem.
+ /// @return The decoded string.
+ function toData(RLPItem memory self) internal constant returns (bytes memory bts) {
+ if(!isData(self))
+ throw;
+ var (rStartPos, len) = _decode(self);
+ bts = new bytes(len);
+ _copyToBytes(rStartPos, bts, len);
+ }
+
+ /// @dev Get the list of sub-items from an RLP encoded list.
+ /// Warning: This is inefficient, as it requires that the list is read twice.
+ /// @param self The RLP item.
+ /// @return Array of RLPItems.
+ function toList(RLPItem memory self) internal constant returns (RLPItem[] memory list) {
+ if(!isList(self))
+ throw;
+ var numItems = items(self);
+ list = new RLPItem[](numItems);
+ var it = iterator(self);
+ uint idx;
+ while(hasNext(it)) {
+ list[idx] = next(it);
+ idx++;
+ }
+ }
+
+ /// @dev Decode an RLPItem into an ascii string. This will not work if the
+ /// RLPItem is a list.
+ /// @param self The RLPItem.
+ /// @return The decoded string.
+ function toAscii(RLPItem memory self) internal constant returns (string memory str) {
+ if(!isData(self))
+ throw;
+ var (rStartPos, len) = _decode(self);
+ bytes memory bts = new bytes(len);
+ _copyToBytes(rStartPos, bts, len);
+ str = string(bts);
+ }
+
+ /// @dev Decode an RLPItem into a uint. This will not work if the
+ /// RLPItem is a list.
+ /// @param self The RLPItem.
+ /// @return The decoded string.
+ function toUint(RLPItem memory self) internal constant returns (uint data) {
+ if(!isData(self))
+ throw;
+ var (rStartPos, len) = _decode(self);
+ if (len > 32 || len == 0)
+ throw;
+ assembly {
+ data := div(mload(rStartPos), exp(256, sub(32, len)))
+ }
+ }
+
+ /// @dev Decode an RLPItem into a boolean. This will not work if the
+ /// RLPItem is a list.
+ /// @param self The RLPItem.
+ /// @return The decoded string.
+ function toBool(RLPItem memory self) internal constant returns (bool data) {
+ if(!isData(self))
+ throw;
+ var (rStartPos, len) = _decode(self);
+ if (len != 1)
+ throw;
+ uint temp;
+ assembly {
+ temp := byte(0, mload(rStartPos))
+ }
+ if (temp > 1)
+ throw;
+ return temp == 1 ? true : false;
+ }
+
+ /// @dev Decode an RLPItem into a byte. This will not work if the
+ /// RLPItem is a list.
+ /// @param self The RLPItem.
+ /// @return The decoded string.
+ function toByte(RLPItem memory self) internal constant returns (byte data) {
+ if(!isData(self))
+ throw;
+ var (rStartPos, len) = _decode(self);
+ if (len != 1)
+ throw;
+ uint temp;
+ assembly {
+ temp := byte(0, mload(rStartPos))
+ }
+ return byte(temp);
+ }
+
+ /// @dev Decode an RLPItem into an int. This will not work if the
+ /// RLPItem is a list.
+ /// @param self The RLPItem.
+ /// @return The decoded string.
+ function toInt(RLPItem memory self) internal constant returns (int data) {
+ return int(toUint(self));
+ }
+
+ /// @dev Decode an RLPItem into a bytes32. This will not work if the
+ /// RLPItem is a list.
+ /// @param self The RLPItem.
+ /// @return The decoded string.
+ function toBytes32(RLPItem memory self) internal constant returns (bytes32 data) {
+ return bytes32(toUint(self));
+ }
+
+ /// @dev Decode an RLPItem into an address. This will not work if the
+ /// RLPItem is a list.
+ /// @param self The RLPItem.
+ /// @return The decoded string.
+ function toAddress(RLPItem memory self) internal constant returns (address data) {
+ if(!isData(self))
+ throw;
+ var (rStartPos, len) = _decode(self);
+ if (len != 20)
+ throw;
+ assembly {
+ data := div(mload(rStartPos), exp(256, 12))
+ }
+ }
+
+ // Get the payload offset.
+ function _payloadOffset(RLPItem memory self) private constant returns (uint) {
+ if(self._unsafe_length == 0)
+ return 0;
+ uint b0;
+ uint memPtr = self._unsafe_memPtr;
+ assembly {
+ b0 := byte(0, mload(memPtr))
+ }
+ if(b0 < DATA_SHORT_START)
+ return 0;
+ if(b0 < DATA_LONG_START || (b0 >= LIST_SHORT_START && b0 < LIST_LONG_START))
+ return 1;
+ if(b0 < LIST_SHORT_START)
+ return b0 - DATA_LONG_OFFSET + 1;
+ return b0 - LIST_LONG_OFFSET + 1;
+ }
+
+ // Get the full length of an RLP item.
+ function _itemLength(uint memPtr) private constant returns (uint len) {
+ uint b0;
+ assembly {
+ b0 := byte(0, mload(memPtr))
+ }
+ if (b0 < DATA_SHORT_START)
+ len = 1;
+ else if (b0 < DATA_LONG_START)
+ len = b0 - DATA_SHORT_START + 1;
+ else if (b0 < LIST_SHORT_START) {
+ assembly {
+ let bLen := sub(b0, 0xB7) // bytes length (DATA_LONG_OFFSET)
+ let dLen := div(mload(add(memPtr, 1)), exp(256, sub(32, bLen))) // data length
+ len := add(1, add(bLen, dLen)) // total length
+ }
+ }
+ else if (b0 < LIST_LONG_START)
+ len = b0 - LIST_SHORT_START + 1;
+ else {
+ assembly {
+ let bLen := sub(b0, 0xF7) // bytes length (LIST_LONG_OFFSET)
+ let dLen := div(mload(add(memPtr, 1)), exp(256, sub(32, bLen))) // data length
+ len := add(1, add(bLen, dLen)) // total length
+ }
+ }
+ }
+
+ // Get start position and length of the data.
+ function _decode(RLPItem memory self) private constant returns (uint memPtr, uint len) {
+ if(!isData(self))
+ throw;
+ uint b0;
+ uint start = self._unsafe_memPtr;
+ assembly {
+ b0 := byte(0, mload(start))
+ }
+ if (b0 < DATA_SHORT_START) {
+ memPtr = start;
+ len = 1;
+ return;
+ }
+ if (b0 < DATA_LONG_START) {
+ len = self._unsafe_length - 1;
+ memPtr = start + 1;
+ } else {
+ uint bLen;
+ assembly {
+ bLen := sub(b0, 0xB7) // DATA_LONG_OFFSET
+ }
+ len = self._unsafe_length - 1 - bLen;
+ memPtr = start + bLen + 1;
+ }
+ return;
+ }
+
+ // Assumes that enough memory has been allocated to store in target.
+ function _copyToBytes(uint btsPtr, bytes memory tgt, uint btsLen) private constant {
+ // Exploiting the fact that 'tgt' was the last thing to be allocated,
+ // we can write entire words, and just overwrite any excess.
+ assembly {
+ {
+ let i := 0 // Start at arr + 0x20
+ let words := div(add(btsLen, 31), 32)
+ let rOffset := btsPtr
+ let wOffset := add(tgt, 0x20)
+ tag_loop:
+ jumpi(end, eq(i, words))
+ {
+ let offset := mul(i, 0x20)
+ mstore(add(wOffset, offset), mload(add(rOffset, offset)))
+ i := add(i, 1)
+ }
+ jump(tag_loop)
+ end:
+ mstore(add(tgt, add(0x20, mload(tgt))), 0)
+ }
+ }
+ }
+
+ // Check that an RLP item is valid.
+ function _validate(RLPItem memory self) private constant returns (bool ret) {
+ // Check that RLP is well-formed.
+ uint b0;
+ uint b1;
+ uint memPtr = self._unsafe_memPtr;
+ assembly {
+ b0 := byte(0, mload(memPtr))
+ b1 := byte(1, mload(memPtr))
+ }
+ if(b0 == DATA_SHORT_START + 1 && b1 < DATA_SHORT_START)
+ return false;
+ return true;
+ }
+}
diff --git a/test/compilationTests/stringutils/LICENSE b/test/compilationTests/stringutils/LICENSE
new file mode 100644
index 00000000..769c2409
--- /dev/null
+++ b/test/compilationTests/stringutils/LICENSE
@@ -0,0 +1,201 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "{}"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright 2016 Nick Johnson
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/test/compilationTests/stringutils/README.md b/test/compilationTests/stringutils/README.md
new file mode 100644
index 00000000..48f71f31
--- /dev/null
+++ b/test/compilationTests/stringutils/README.md
@@ -0,0 +1,4 @@
+String utilities, originally from
+
+https://github.com/Arachnid/solidity-stringutils
+
diff --git a/test/compilationTests/stringutils/strings.sol b/test/compilationTests/stringutils/strings.sol
new file mode 100644
index 00000000..0a2d68bd
--- /dev/null
+++ b/test/compilationTests/stringutils/strings.sol
@@ -0,0 +1,709 @@
+/*
+ * @title String & slice utility library for Solidity contracts.
+ * @author Nick Johnson <arachnid@notdot.net>
+ *
+ * @dev Functionality in this library is largely implemented using an
+ * abstraction called a 'slice'. A slice represents a part of a string -
+ * anything from the entire string to a single character, or even no
+ * characters at all (a 0-length slice). Since a slice only has to specify
+ * an offset and a length, copying and manipulating slices is a lot less
+ * expensive than copying and manipulating the strings they reference.
+ *
+ * To further reduce gas costs, most functions on slice that need to return
+ * a slice modify the original one instead of allocating a new one; for
+ * instance, `s.split(".")` will return the text up to the first '.',
+ * modifying s to only contain the remainder of the string after the '.'.
+ * In situations where you do not want to modify the original slice, you
+ * can make a copy first with `.copy()`, for example:
+ * `s.copy().split(".")`. Try and avoid using this idiom in loops; since
+ * Solidity has no memory management, it will result in allocating many
+ * short-lived slices that are later discarded.
+ *
+ * Functions that return two slices come in two versions: a non-allocating
+ * version that takes the second slice as an argument, modifying it in
+ * place, and an allocating version that allocates and returns the second
+ * slice; see `nextRune` for example.
+ *
+ * Functions that have to copy string data will return strings rather than
+ * slices; these can be cast back to slices for further processing if
+ * required.
+ *
+ * For convenience, some functions are provided with non-modifying
+ * variants that create a new slice and return both; for instance,
+ * `s.splitNew('.')` leaves s unmodified, and returns two values
+ * corresponding to the left and right parts of the string.
+ */
+library strings {
+ struct slice {
+ uint _len;
+ uint _ptr;
+ }
+
+ function memcpy(uint dest, uint src, uint len) private {
+ // Copy word-length chunks while possible
+ for(; len >= 32; len -= 32) {
+ assembly {
+ mstore(dest, mload(src))
+ }
+ dest += 32;
+ src += 32;
+ }
+
+ // Copy remaining bytes
+ uint mask = 256 ** (32 - len) - 1;
+ assembly {
+ let srcpart := and(mload(src), not(mask))
+ let destpart := and(mload(dest), mask)
+ mstore(dest, or(destpart, srcpart))
+ }
+ }
+
+ /*
+ * @dev Returns a slice containing the entire string.
+ * @param self The string to make a slice from.
+ * @return A newly allocated slice containing the entire string.
+ */
+ function toSlice(string self) internal returns (slice) {
+ uint ptr;
+ assembly {
+ ptr := add(self, 0x20)
+ }
+ return slice(bytes(self).length, ptr);
+ }
+
+ /*
+ * @dev Returns the length of a null-terminated bytes32 string.
+ * @param self The value to find the length of.
+ * @return The length of the string, from 0 to 32.
+ */
+ function len(bytes32 self) internal returns (uint) {
+ uint ret;
+ if (self == 0)
+ return 0;
+ if (self & 0xffffffffffffffffffffffffffffffff == 0) {
+ ret += 16;
+ self = bytes32(uint(self) / 0x100000000000000000000000000000000);
+ }
+ if (self & 0xffffffffffffffff == 0) {
+ ret += 8;
+ self = bytes32(uint(self) / 0x10000000000000000);
+ }
+ if (self & 0xffffffff == 0) {
+ ret += 4;
+ self = bytes32(uint(self) / 0x100000000);
+ }
+ if (self & 0xffff == 0) {
+ ret += 2;
+ self = bytes32(uint(self) / 0x10000);
+ }
+ if (self & 0xff == 0) {
+ ret += 1;
+ }
+ return 32 - ret;
+ }
+
+ /*
+ * @dev Returns a slice containing the entire bytes32, interpreted as a
+ * null-termintaed utf-8 string.
+ * @param self The bytes32 value to convert to a slice.
+ * @return A new slice containing the value of the input argument up to the
+ * first null.
+ */
+ function toSliceB32(bytes32 self) internal returns (slice ret) {
+ // Allocate space for `self` in memory, copy it there, and point ret at it
+ assembly {
+ let ptr := mload(0x40)
+ mstore(0x40, add(ptr, 0x20))
+ mstore(ptr, self)
+ mstore(add(ret, 0x20), ptr)
+ }
+ ret._len = len(self);
+ }
+
+ /*
+ * @dev Returns a new slice containing the same data as the current slice.
+ * @param self The slice to copy.
+ * @return A new slice containing the same data as `self`.
+ */
+ function copy(slice self) internal returns (slice) {
+ return slice(self._len, self._ptr);
+ }
+
+ /*
+ * @dev Copies a slice to a new string.
+ * @param self The slice to copy.
+ * @return A newly allocated string containing the slice's text.
+ */
+ function toString(slice self) internal returns (string) {
+ var ret = new string(self._len);
+ uint retptr;
+ assembly { retptr := add(ret, 32) }
+
+ memcpy(retptr, self._ptr, self._len);
+ return ret;
+ }
+
+ /*
+ * @dev Returns the length in runes of the slice. Note that this operation
+ * takes time proportional to the length of the slice; avoid using it
+ * in loops, and call `slice.empty()` if you only need to know whether
+ * the slice is empty or not.
+ * @param self The slice to operate on.
+ * @return The length of the slice in runes.
+ */
+ function len(slice self) internal returns (uint) {
+ // Starting at ptr-31 means the LSB will be the byte we care about
+ var ptr = self._ptr - 31;
+ var end = ptr + self._len;
+ for (uint len = 0; ptr < end; len++) {
+ uint8 b;
+ assembly { b := and(mload(ptr), 0xFF) }
+ if (b < 0x80) {
+ ptr += 1;
+ } else if(b < 0xE0) {
+ ptr += 2;
+ } else if(b < 0xF0) {
+ ptr += 3;
+ } else if(b < 0xF8) {
+ ptr += 4;
+ } else if(b < 0xFC) {
+ ptr += 5;
+ } else {
+ ptr += 6;
+ }
+ }
+ return len;
+ }
+
+ /*
+ * @dev Returns true if the slice is empty (has a length of 0).
+ * @param self The slice to operate on.
+ * @return True if the slice is empty, False otherwise.
+ */
+ function empty(slice self) internal returns (bool) {
+ return self._len == 0;
+ }
+
+ /*
+ * @dev Returns a positive number if `other` comes lexicographically after
+ * `self`, a negative number if it comes before, or zero if the
+ * contents of the two slices are equal. Comparison is done per-rune,
+ * on unicode codepoints.
+ * @param self The first slice to compare.
+ * @param other The second slice to compare.
+ * @return The result of the comparison.
+ */
+ function compare(slice self, slice other) internal returns (int) {
+ uint shortest = self._len;
+ if (other._len < self._len)
+ shortest = other._len;
+
+ var selfptr = self._ptr;
+ var otherptr = other._ptr;
+ for (uint idx = 0; idx < shortest; idx += 32) {
+ uint a;
+ uint b;
+ assembly {
+ a := mload(selfptr)
+ b := mload(otherptr)
+ }
+ if (a != b) {
+ // Mask out irrelevant bytes and check again
+ uint mask = ~(2 ** (8 * (32 - shortest + idx)) - 1);
+ var diff = (a & mask) - (b & mask);
+ if (diff != 0)
+ return int(diff);
+ }
+ selfptr += 32;
+ otherptr += 32;
+ }
+ return int(self._len) - int(other._len);
+ }
+
+ /*
+ * @dev Returns true if the two slices contain the same text.
+ * @param self The first slice to compare.
+ * @param self The second slice to compare.
+ * @return True if the slices are equal, false otherwise.
+ */
+ function equals(slice self, slice other) internal returns (bool) {
+ return compare(self, other) == 0;
+ }
+
+ /*
+ * @dev Extracts the first rune in the slice into `rune`, advancing the
+ * slice to point to the next rune and returning `self`.
+ * @param self The slice to operate on.
+ * @param rune The slice that will contain the first rune.
+ * @return `rune`.
+ */
+ function nextRune(slice self, slice rune) internal returns (slice) {
+ rune._ptr = self._ptr;
+
+ if (self._len == 0) {
+ rune._len = 0;
+ return rune;
+ }
+
+ uint len;
+ uint b;
+ // Load the first byte of the rune into the LSBs of b
+ assembly { b := and(mload(sub(mload(add(self, 32)), 31)), 0xFF) }
+ if (b < 0x80) {
+ len = 1;
+ } else if(b < 0xE0) {
+ len = 2;
+ } else if(b < 0xF0) {
+ len = 3;
+ } else {
+ len = 4;
+ }
+
+ // Check for truncated codepoints
+ if (len > self._len) {
+ rune._len = self._len;
+ self._ptr += self._len;
+ self._len = 0;
+ return rune;
+ }
+
+ self._ptr += len;
+ self._len -= len;
+ rune._len = len;
+ return rune;
+ }
+
+ /*
+ * @dev Returns the first rune in the slice, advancing the slice to point
+ * to the next rune.
+ * @param self The slice to operate on.
+ * @return A slice containing only the first rune from `self`.
+ */
+ function nextRune(slice self) internal returns (slice ret) {
+ nextRune(self, ret);
+ }
+
+ /*
+ * @dev Returns the number of the first codepoint in the slice.
+ * @param self The slice to operate on.
+ * @return The number of the first codepoint in the slice.
+ */
+ function ord(slice self) internal returns (uint ret) {
+ if (self._len == 0) {
+ return 0;
+ }
+
+ uint word;
+ uint len;
+ uint div = 2 ** 248;
+
+ // Load the rune into the MSBs of b
+ assembly { word:= mload(mload(add(self, 32))) }
+ var b = word / div;
+ if (b < 0x80) {
+ ret = b;
+ len = 1;
+ } else if(b < 0xE0) {
+ ret = b & 0x1F;
+ len = 2;
+ } else if(b < 0xF0) {
+ ret = b & 0x0F;
+ len = 3;
+ } else {
+ ret = b & 0x07;
+ len = 4;
+ }
+
+ // Check for truncated codepoints
+ if (len > self._len) {
+ return 0;
+ }
+
+ for (uint i = 1; i < len; i++) {
+ div = div / 256;
+ b = (word / div) & 0xFF;
+ if (b & 0xC0 != 0x80) {
+ // Invalid UTF-8 sequence
+ return 0;
+ }
+ ret = (ret * 64) | (b & 0x3F);
+ }
+
+ return ret;
+ }
+
+ /*
+ * @dev Returns the keccak-256 hash of the slice.
+ * @param self The slice to hash.
+ * @return The hash of the slice.
+ */
+ function keccak(slice self) internal returns (bytes32 ret) {
+ assembly {
+ ret := sha3(mload(add(self, 32)), mload(self))
+ }
+ }
+
+ /*
+ * @dev Returns true if `self` starts with `needle`.
+ * @param self The slice to operate on.
+ * @param needle The slice to search for.
+ * @return True if the slice starts with the provided text, false otherwise.
+ */
+ function startsWith(slice self, slice needle) internal returns (bool) {
+ if (self._len < needle._len) {
+ return false;
+ }
+
+ if (self._ptr == needle._ptr) {
+ return true;
+ }
+
+ bool equal;
+ assembly {
+ let len := mload(needle)
+ let selfptr := mload(add(self, 0x20))
+ let needleptr := mload(add(needle, 0x20))
+ equal := eq(sha3(selfptr, len), sha3(needleptr, len))
+ }
+ return equal;
+ }
+
+ /*
+ * @dev If `self` starts with `needle`, `needle` is removed from the
+ * beginning of `self`. Otherwise, `self` is unmodified.
+ * @param self The slice to operate on.
+ * @param needle The slice to search for.
+ * @return `self`
+ */
+ function beyond(slice self, slice needle) internal returns (slice) {
+ if (self._len < needle._len) {
+ return self;
+ }
+
+ bool equal = true;
+ if (self._ptr != needle._ptr) {
+ assembly {
+ let len := mload(needle)
+ let selfptr := mload(add(self, 0x20))
+ let needleptr := mload(add(needle, 0x20))
+ equal := eq(sha3(selfptr, len), sha3(needleptr, len))
+ }
+ }
+
+ if (equal) {
+ self._len -= needle._len;
+ self._ptr += needle._len;
+ }
+
+ return self;
+ }
+
+ /*
+ * @dev Returns true if the slice ends with `needle`.
+ * @param self The slice to operate on.
+ * @param needle The slice to search for.
+ * @return True if the slice starts with the provided text, false otherwise.
+ */
+ function endsWith(slice self, slice needle) internal returns (bool) {
+ if (self._len < needle._len) {
+ return false;
+ }
+
+ var selfptr = self._ptr + self._len - needle._len;
+
+ if (selfptr == needle._ptr) {
+ return true;
+ }
+
+ bool equal;
+ assembly {
+ let len := mload(needle)
+ let needleptr := mload(add(needle, 0x20))
+ equal := eq(sha3(selfptr, len), sha3(needleptr, len))
+ }
+
+ return equal;
+ }
+
+ /*
+ * @dev If `self` ends with `needle`, `needle` is removed from the
+ * end of `self`. Otherwise, `self` is unmodified.
+ * @param self The slice to operate on.
+ * @param needle The slice to search for.
+ * @return `self`
+ */
+ function until(slice self, slice needle) internal returns (slice) {
+ if (self._len < needle._len) {
+ return self;
+ }
+
+ var selfptr = self._ptr + self._len - needle._len;
+ bool equal = true;
+ if (selfptr != needle._ptr) {
+ assembly {
+ let len := mload(needle)
+ let needleptr := mload(add(needle, 0x20))
+ equal := eq(sha3(selfptr, len), sha3(needleptr, len))
+ }
+ }
+
+ if (equal) {
+ self._len -= needle._len;
+ }
+
+ return self;
+ }
+
+ // Returns the memory address of the first byte of the first occurrence of
+ // `needle` in `self`, or the first byte after `self` if not found.
+ function findPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private returns (uint) {
+ uint ptr;
+ uint idx;
+
+ if (needlelen <= selflen) {
+ if (needlelen <= 32) {
+ // Optimized assembly for 68 gas per byte on short strings
+ assembly {
+ let mask := not(sub(exp(2, mul(8, sub(32, needlelen))), 1))
+ let needledata := and(mload(needleptr), mask)
+ let end := add(selfptr, sub(selflen, needlelen))
+ ptr := selfptr
+ loop:
+ jumpi(exit, eq(and(mload(ptr), mask), needledata))
+ ptr := add(ptr, 1)
+ jumpi(loop, lt(sub(ptr, 1), end))
+ ptr := add(selfptr, selflen)
+ exit:
+ }
+ return ptr;
+ } else {
+ // For long needles, use hashing
+ bytes32 hash;
+ assembly { hash := sha3(needleptr, needlelen) }
+ ptr = selfptr;
+ for (idx = 0; idx <= selflen - needlelen; idx++) {
+ bytes32 testHash;
+ assembly { testHash := sha3(ptr, needlelen) }
+ if (hash == testHash)
+ return ptr;
+ ptr += 1;
+ }
+ }
+ }
+ return selfptr + selflen;
+ }
+
+ // Returns the memory address of the first byte after the last occurrence of
+ // `needle` in `self`, or the address of `self` if not found.
+ function rfindPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private returns (uint) {
+ uint ptr;
+
+ if (needlelen <= selflen) {
+ if (needlelen <= 32) {
+ // Optimized assembly for 69 gas per byte on short strings
+ assembly {
+ let mask := not(sub(exp(2, mul(8, sub(32, needlelen))), 1))
+ let needledata := and(mload(needleptr), mask)
+ ptr := add(selfptr, sub(selflen, needlelen))
+ loop:
+ jumpi(ret, eq(and(mload(ptr), mask), needledata))
+ ptr := sub(ptr, 1)
+ jumpi(loop, gt(add(ptr, 1), selfptr))
+ ptr := selfptr
+ jump(exit)
+ ret:
+ ptr := add(ptr, needlelen)
+ exit:
+ }
+ return ptr;
+ } else {
+ // For long needles, use hashing
+ bytes32 hash;
+ assembly { hash := sha3(needleptr, needlelen) }
+ ptr = selfptr + (selflen - needlelen);
+ while (ptr >= selfptr) {
+ bytes32 testHash;
+ assembly { testHash := sha3(ptr, needlelen) }
+ if (hash == testHash)
+ return ptr + needlelen;
+ ptr -= 1;
+ }
+ }
+ }
+ return selfptr;
+ }
+
+ /*
+ * @dev Modifies `self` to contain everything from the first occurrence of
+ * `needle` to the end of the slice. `self` is set to the empty slice
+ * if `needle` is not found.
+ * @param self The slice to search and modify.
+ * @param needle The text to search for.
+ * @return `self`.
+ */
+ function find(slice self, slice needle) internal returns (slice) {
+ uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr);
+ self._len -= ptr - self._ptr;
+ self._ptr = ptr;
+ return self;
+ }
+
+ /*
+ * @dev Modifies `self` to contain the part of the string from the start of
+ * `self` to the end of the first occurrence of `needle`. If `needle`
+ * is not found, `self` is set to the empty slice.
+ * @param self The slice to search and modify.
+ * @param needle The text to search for.
+ * @return `self`.
+ */
+ function rfind(slice self, slice needle) internal returns (slice) {
+ uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr);
+ self._len = ptr - self._ptr;
+ return self;
+ }
+
+ /*
+ * @dev Splits the slice, setting `self` to everything after the first
+ * occurrence of `needle`, and `token` to everything before it. If
+ * `needle` does not occur in `self`, `self` is set to the empty slice,
+ * and `token` is set to the entirety of `self`.
+ * @param self The slice to split.
+ * @param needle The text to search for in `self`.
+ * @param token An output parameter to which the first token is written.
+ * @return `token`.
+ */
+ function split(slice self, slice needle, slice token) internal returns (slice) {
+ uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr);
+ token._ptr = self._ptr;
+ token._len = ptr - self._ptr;
+ if (ptr == self._ptr + self._len) {
+ // Not found
+ self._len = 0;
+ } else {
+ self._len -= token._len + needle._len;
+ self._ptr = ptr + needle._len;
+ }
+ return token;
+ }
+
+ /*
+ * @dev Splits the slice, setting `self` to everything after the first
+ * occurrence of `needle`, and returning everything before it. If
+ * `needle` does not occur in `self`, `self` is set to the empty slice,
+ * and the entirety of `self` is returned.
+ * @param self The slice to split.
+ * @param needle The text to search for in `self`.
+ * @return The part of `self` up to the first occurrence of `delim`.
+ */
+ function split(slice self, slice needle) internal returns (slice token) {
+ split(self, needle, token);
+ }
+
+ /*
+ * @dev Splits the slice, setting `self` to everything before the last
+ * occurrence of `needle`, and `token` to everything after it. If
+ * `needle` does not occur in `self`, `self` is set to the empty slice,
+ * and `token` is set to the entirety of `self`.
+ * @param self The slice to split.
+ * @param needle The text to search for in `self`.
+ * @param token An output parameter to which the first token is written.
+ * @return `token`.
+ */
+ function rsplit(slice self, slice needle, slice token) internal returns (slice) {
+ uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr);
+ token._ptr = ptr;
+ token._len = self._len - (ptr - self._ptr);
+ if (ptr == self._ptr) {
+ // Not found
+ self._len = 0;
+ } else {
+ self._len -= token._len + needle._len;
+ }
+ return token;
+ }
+
+ /*
+ * @dev Splits the slice, setting `self` to everything before the last
+ * occurrence of `needle`, and returning everything after it. If
+ * `needle` does not occur in `self`, `self` is set to the empty slice,
+ * and the entirety of `self` is returned.
+ * @param self The slice to split.
+ * @param needle The text to search for in `self`.
+ * @return The part of `self` after the last occurrence of `delim`.
+ */
+ function rsplit(slice self, slice needle) internal returns (slice token) {
+ rsplit(self, needle, token);
+ }
+
+ /*
+ * @dev Counts the number of nonoverlapping occurrences of `needle` in `self`.
+ * @param self The slice to search.
+ * @param needle The text to search for in `self`.
+ * @return The number of occurrences of `needle` found in `self`.
+ */
+ function count(slice self, slice needle) internal returns (uint count) {
+ uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr) + needle._len;
+ while (ptr <= self._ptr + self._len) {
+ count++;
+ ptr = findPtr(self._len - (ptr - self._ptr), ptr, needle._len, needle._ptr) + needle._len;
+ }
+ }
+
+ /*
+ * @dev Returns True if `self` contains `needle`.
+ * @param self The slice to search.
+ * @param needle The text to search for in `self`.
+ * @return True if `needle` is found in `self`, false otherwise.
+ */
+ function contains(slice self, slice needle) internal returns (bool) {
+ return rfindPtr(self._len, self._ptr, needle._len, needle._ptr) != self._ptr;
+ }
+
+ /*
+ * @dev Returns a newly allocated string containing the concatenation of
+ * `self` and `other`.
+ * @param self The first slice to concatenate.
+ * @param other The second slice to concatenate.
+ * @return The concatenation of the two strings.
+ */
+ function concat(slice self, slice other) internal returns (string) {
+ var ret = new string(self._len + other._len);
+ uint retptr;
+ assembly { retptr := add(ret, 32) }
+ memcpy(retptr, self._ptr, self._len);
+ memcpy(retptr + self._len, other._ptr, other._len);
+ return ret;
+ }
+
+ /*
+ * @dev Joins an array of slices, using `self` as a delimiter, returning a
+ * newly allocated string.
+ * @param self The delimiter to use.
+ * @param parts A list of slices to join.
+ * @return A newly allocated string containing all the slices in `parts`,
+ * joined with `self`.
+ */
+ function join(slice self, slice[] parts) internal returns (string) {
+ if (parts.length == 0)
+ return "";
+
+ uint len = self._len * (parts.length - 1);
+ for(uint i = 0; i < parts.length; i++)
+ len += parts[i]._len;
+
+ var ret = new string(len);
+ uint retptr;
+ assembly { retptr := add(ret, 32) }
+
+ for(i = 0; i < parts.length; i++) {
+ memcpy(retptr, parts[i]._ptr, parts[i]._len);
+ retptr += parts[i]._len;
+ if (i < parts.length - 1) {
+ memcpy(retptr, self._ptr, self._len);
+ retptr += self._len;
+ }
+ }
+
+ return ret;
+ }
+}
diff --git a/test/compilationTests/zeppelin/Bounty.sol b/test/compilationTests/zeppelin/Bounty.sol
new file mode 100644
index 00000000..4425b7a5
--- /dev/null
+++ b/test/compilationTests/zeppelin/Bounty.sol
@@ -0,0 +1,78 @@
+pragma solidity ^0.4.11;
+
+
+import './payment/PullPayment.sol';
+import './lifecycle/Destructible.sol';
+
+
+/**
+ * @title Bounty
+ * @dev This bounty will pay out to a researcher if they break invariant logic of the contract.
+ */
+contract Bounty is PullPayment, Destructible {
+ bool public claimed;
+ mapping(address => address) public researchers;
+
+ event TargetCreated(address createdAddress);
+
+ /**
+ * @dev Fallback function allowing the contract to recieve funds, if they haven't already been claimed.
+ */
+ function() payable {
+ if (claimed) {
+ throw;
+ }
+ }
+
+ /**
+ * @dev Create and deploy the target contract (extension of Target contract), and sets the
+ * msg.sender as a researcher
+ * @return A target contract
+ */
+ function createTarget() returns(Target) {
+ Target target = Target(deployContract());
+ researchers[target] = msg.sender;
+ TargetCreated(target);
+ return target;
+ }
+
+ /**
+ * @dev Internal function to deploy the target contract.
+ * @return A target contract address
+ */
+ function deployContract() internal returns(address);
+
+ /**
+ * @dev Sends the contract funds to the researcher that proved the contract is broken.
+ * @param target contract
+ */
+ function claim(Target target) {
+ address researcher = researchers[target];
+ if (researcher == 0) {
+ throw;
+ }
+ // Check Target contract invariants
+ if (target.checkInvariant()) {
+ throw;
+ }
+ asyncSend(researcher, this.balance);
+ claimed = true;
+ }
+
+}
+
+
+/**
+ * @title Target
+ * @dev Your main contract should inherit from this class and implement the checkInvariant method.
+ */
+contract Target {
+
+ /**
+ * @dev Checks all values a contract assumes to be true all the time. If this function returns
+ * false, the contract is broken in some way and is in an inconsistent state.
+ * In order to win the bounty, security researchers will try to cause this broken state.
+ * @return True if all invariant values are correct, false otherwise.
+ */
+ function checkInvariant() returns(bool);
+}
diff --git a/test/compilationTests/zeppelin/DayLimit.sol b/test/compilationTests/zeppelin/DayLimit.sol
new file mode 100644
index 00000000..3c8d5b0c
--- /dev/null
+++ b/test/compilationTests/zeppelin/DayLimit.sol
@@ -0,0 +1,75 @@
+pragma solidity ^0.4.11;
+
+/**
+ * @title DayLimit
+ * @dev Base contract that enables methods to be protected by placing a linear limit (specifiable)
+ * on a particular resource per calendar day. Is multiowned to allow the limit to be altered.
+ */
+contract DayLimit {
+
+ uint256 public dailyLimit;
+ uint256 public spentToday;
+ uint256 public lastDay;
+
+ /**
+ * @dev Constructor that sets the passed value as a dailyLimit.
+ * @param _limit uint256 to represent the daily limit.
+ */
+ function DayLimit(uint256 _limit) {
+ dailyLimit = _limit;
+ lastDay = today();
+ }
+
+ /**
+ * @dev sets the daily limit. Does not alter the amount already spent today.
+ * @param _newLimit uint256 to represent the new limit.
+ */
+ function _setDailyLimit(uint256 _newLimit) internal {
+ dailyLimit = _newLimit;
+ }
+
+ /**
+ * @dev Resets the amount already spent today.
+ */
+ function _resetSpentToday() internal {
+ spentToday = 0;
+ }
+
+ /**
+ * @dev Checks to see if there is enough resource to spend today. If true, the resource may be expended.
+ * @param _value uint256 representing the amount of resource to spend.
+ * @return A boolean that is True if the resource was spended and false otherwise.
+ */
+ function underLimit(uint256 _value) internal returns (bool) {
+ // reset the spend limit if we're on a different day to last time.
+ if (today() > lastDay) {
+ spentToday = 0;
+ lastDay = today();
+ }
+ // check to see if there's enough left - if so, subtract and return true.
+ // overflow protection // dailyLimit check
+ if (spentToday + _value >= spentToday && spentToday + _value <= dailyLimit) {
+ spentToday += _value;
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * @dev Private function to determine today's index
+ * @return uint256 of today's index.
+ */
+ function today() private constant returns (uint256) {
+ return now / 1 days;
+ }
+
+ /**
+ * @dev Simple modifier for daily limit.
+ */
+ modifier limitedDaily(uint256 _value) {
+ if (!underLimit(_value)) {
+ throw;
+ }
+ _;
+ }
+}
diff --git a/test/compilationTests/zeppelin/LICENSE b/test/compilationTests/zeppelin/LICENSE
new file mode 100644
index 00000000..85f53321
--- /dev/null
+++ b/test/compilationTests/zeppelin/LICENSE
@@ -0,0 +1,22 @@
+The MIT License (MIT)
+
+Copyright (c) 2016 Smart Contract Solutions, Inc.
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be included
+in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/test/compilationTests/zeppelin/LimitBalance.sol b/test/compilationTests/zeppelin/LimitBalance.sol
new file mode 100644
index 00000000..57477c74
--- /dev/null
+++ b/test/compilationTests/zeppelin/LimitBalance.sol
@@ -0,0 +1,33 @@
+pragma solidity ^0.4.11;
+
+
+/**
+ * @title LimitBalance
+ * @dev Simple contract to limit the balance of child contract.
+ * @dev Note this doesn't prevent other contracts to send funds by using selfdestruct(address);
+ * @dev See: https://github.com/ConsenSys/smart-contract-best-practices#remember-that-ether-can-be-forcibly-sent-to-an-account
+ */
+contract LimitBalance {
+
+ uint256 public limit;
+
+ /**
+ * @dev Constructor that sets the passed value as a limit.
+ * @param _limit uint256 to represent the limit.
+ */
+ function LimitBalance(uint256 _limit) {
+ limit = _limit;
+ }
+
+ /**
+ * @dev Checks if limit was reached. Case true, it throws.
+ */
+ modifier limitedPayable() {
+ if (this.balance > limit) {
+ throw;
+ }
+ _;
+
+ }
+
+}
diff --git a/test/compilationTests/zeppelin/MultisigWallet.sol b/test/compilationTests/zeppelin/MultisigWallet.sol
new file mode 100644
index 00000000..939e70f2
--- /dev/null
+++ b/test/compilationTests/zeppelin/MultisigWallet.sol
@@ -0,0 +1,127 @@
+pragma solidity ^0.4.11;
+
+
+import "./ownership/Multisig.sol";
+import "./ownership/Shareable.sol";
+import "./DayLimit.sol";
+
+
+/**
+ * MultisigWallet
+ * Usage:
+ * bytes32 h = Wallet(w).from(oneOwner).execute(to, value, data);
+ * Wallet(w).from(anotherOwner).confirm(h);
+ */
+contract MultisigWallet is Multisig, Shareable, DayLimit {
+
+ struct Transaction {
+ address to;
+ uint256 value;
+ bytes data;
+ }
+
+ /**
+ * Constructor, sets the owners addresses, number of approvals required, and daily spending limit
+ * @param _owners A list of owners.
+ * @param _required The amount required for a transaction to be approved.
+ */
+ function MultisigWallet(address[] _owners, uint256 _required, uint256 _daylimit)
+ Shareable(_owners, _required)
+ DayLimit(_daylimit) { }
+
+ /**
+ * @dev destroys the contract sending everything to `_to`.
+ */
+ function destroy(address _to) onlymanyowners(keccak256(msg.data)) external {
+ selfdestruct(_to);
+ }
+
+ /**
+ * @dev Fallback function, receives value and emits a deposit event.
+ */
+ function() payable {
+ // just being sent some cash?
+ if (msg.value > 0)
+ Deposit(msg.sender, msg.value);
+ }
+
+ /**
+ * @dev Outside-visible transaction entry point. Executes transaction immediately if below daily
+ * spending limit. If not, goes into multisig process. We provide a hash on return to allow the
+ * sender to provide shortcuts for the other confirmations (allowing them to avoid replicating
+ * the _to, _value, and _data arguments). They still get the option of using them if they want,
+ * anyways.
+ * @param _to The receiver address
+ * @param _value The value to send
+ * @param _data The data part of the transaction
+ */
+ function execute(address _to, uint256 _value, bytes _data) external onlyOwner returns (bytes32 _r) {
+ // first, take the opportunity to check that we're under the daily limit.
+ if (underLimit(_value)) {
+ SingleTransact(msg.sender, _value, _to, _data);
+ // yes - just execute the call.
+ if (!_to.call.value(_value)(_data)) {
+ throw;
+ }
+ return 0;
+ }
+ // determine our operation hash.
+ _r = keccak256(msg.data, block.number);
+ if (!confirm(_r) && txs[_r].to == 0) {
+ txs[_r].to = _to;
+ txs[_r].value = _value;
+ txs[_r].data = _data;
+ ConfirmationNeeded(_r, msg.sender, _value, _to, _data);
+ }
+ }
+
+ /**
+ * @dev Confirm a transaction by providing just the hash. We use the previous transactions map,
+ * txs, in order to determine the body of the transaction from the hash provided.
+ * @param _h The transaction hash to approve.
+ */
+ function confirm(bytes32 _h) onlymanyowners(_h) returns (bool) {
+ if (txs[_h].to != 0) {
+ if (!txs[_h].to.call.value(txs[_h].value)(txs[_h].data)) {
+ throw;
+ }
+ MultiTransact(msg.sender, _h, txs[_h].value, txs[_h].to, txs[_h].data);
+ delete txs[_h];
+ return true;
+ }
+ }
+
+ /**
+ * @dev Updates the daily limit value.
+ * @param _newLimit uint256 to represent the new limit.
+ */
+ function setDailyLimit(uint256 _newLimit) onlymanyowners(keccak256(msg.data)) external {
+ _setDailyLimit(_newLimit);
+ }
+
+ /**
+ * @dev Resets the value spent to enable more spending
+ */
+ function resetSpentToday() onlymanyowners(keccak256(msg.data)) external {
+ _resetSpentToday();
+ }
+
+
+ // INTERNAL METHODS
+ /**
+ * @dev Clears the list of transactions pending approval.
+ */
+ function clearPending() internal {
+ uint256 length = pendingsIndex.length;
+ for (uint256 i = 0; i < length; ++i) {
+ delete txs[pendingsIndex[i]];
+ }
+ super.clearPending();
+ }
+
+
+ // FIELDS
+
+ // pending transactions we have at present.
+ mapping (bytes32 => Transaction) txs;
+}
diff --git a/test/compilationTests/zeppelin/README.md b/test/compilationTests/zeppelin/README.md
new file mode 100644
index 00000000..dee2f5ca
--- /dev/null
+++ b/test/compilationTests/zeppelin/README.md
@@ -0,0 +1,3 @@
+Zeppelin contracts, originally from
+
+https://github.com/OpenZeppelin/zeppelin-solidity
diff --git a/test/compilationTests/zeppelin/ReentrancyGuard.sol b/test/compilationTests/zeppelin/ReentrancyGuard.sol
new file mode 100644
index 00000000..ca8b643b
--- /dev/null
+++ b/test/compilationTests/zeppelin/ReentrancyGuard.sol
@@ -0,0 +1,34 @@
+pragma solidity ^0.4.11;
+
+/**
+ * @title Helps contracts guard agains rentrancy attacks.
+ * @author Remco Bloemen <remco@2π.com>
+ * @notice If you mark a function `nonReentrant`, you should also
+ * mark it `external`.
+ */
+contract ReentrancyGuard {
+
+ /**
+ * @dev We use a single lock for the whole contract.
+ */
+ bool private rentrancy_lock = false;
+
+ /**
+ * @dev Prevents a contract from calling itself, directly or indirectly.
+ * @notice If you mark a function `nonReentrant`, you should also
+ * mark it `external`. Calling one nonReentrant function from
+ * another is not supported. Instead, you can implement a
+ * `private` function doing the actual work, and a `external`
+ * wrapper marked as `nonReentrant`.
+ */
+ modifier nonReentrant() {
+ if(rentrancy_lock == false) {
+ rentrancy_lock = true;
+ _;
+ rentrancy_lock = false;
+ } else {
+ throw;
+ }
+ }
+
+}
diff --git a/test/compilationTests/zeppelin/crowdsale/CappedCrowdsale.sol b/test/compilationTests/zeppelin/crowdsale/CappedCrowdsale.sol
new file mode 100644
index 00000000..f04649f3
--- /dev/null
+++ b/test/compilationTests/zeppelin/crowdsale/CappedCrowdsale.sol
@@ -0,0 +1,33 @@
+pragma solidity ^0.4.11;
+
+import '../math/SafeMath.sol';
+import './Crowdsale.sol';
+
+/**
+ * @title CappedCrowdsale
+ * @dev Extension of Crowsdale with a max amount of funds raised
+ */
+contract CappedCrowdsale is Crowdsale {
+ using SafeMath for uint256;
+
+ uint256 public cap;
+
+ function CappedCrowdsale(uint256 _cap) {
+ cap = _cap;
+ }
+
+ // overriding Crowdsale#validPurchase to add extra cap logic
+ // @return true if investors can buy at the moment
+ function validPurchase() internal constant returns (bool) {
+ bool withinCap = weiRaised.add(msg.value) <= cap;
+ return super.validPurchase() && withinCap;
+ }
+
+ // overriding Crowdsale#hasEnded to add cap logic
+ // @return true if crowdsale event has ended
+ function hasEnded() public constant returns (bool) {
+ bool capReached = weiRaised >= cap;
+ return super.hasEnded() || capReached;
+ }
+
+}
diff --git a/test/compilationTests/zeppelin/crowdsale/Crowdsale.sol b/test/compilationTests/zeppelin/crowdsale/Crowdsale.sol
new file mode 100644
index 00000000..bee1efd2
--- /dev/null
+++ b/test/compilationTests/zeppelin/crowdsale/Crowdsale.sol
@@ -0,0 +1,108 @@
+pragma solidity ^0.4.11;
+
+import '../token/MintableToken.sol';
+import '../math/SafeMath.sol';
+
+/**
+ * @title Crowdsale
+ * @dev Crowdsale is a base contract for managing a token crowdsale.
+ * Crowdsales have a start and end block, where investors can make
+ * token purchases and the crowdsale will assign them tokens based
+ * on a token per ETH rate. Funds collected are forwarded to a wallet
+ * as they arrive.
+ */
+contract Crowdsale {
+ using SafeMath for uint256;
+
+ // The token being sold
+ MintableToken public token;
+
+ // start and end block where investments are allowed (both inclusive)
+ uint256 public startBlock;
+ uint256 public endBlock;
+
+ // address where funds are collected
+ address public wallet;
+
+ // how many token units a buyer gets per wei
+ uint256 public rate;
+
+ // amount of raised money in wei
+ uint256 public weiRaised;
+
+ /**
+ * event for token purchase logging
+ * @param purchaser who paid for the tokens
+ * @param beneficiary who got the tokens
+ * @param value weis paid for purchase
+ * @param amount amount of tokens purchased
+ */
+ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
+
+
+ function Crowdsale(uint256 _startBlock, uint256 _endBlock, uint256 _rate, address _wallet) {
+ require(_startBlock >= block.number);
+ require(_endBlock >= _startBlock);
+ require(_rate > 0);
+ require(_wallet != 0x0);
+
+ token = createTokenContract();
+ startBlock = _startBlock;
+ endBlock = _endBlock;
+ rate = _rate;
+ wallet = _wallet;
+ }
+
+ // creates the token to be sold.
+ // override this method to have crowdsale of a specific mintable token.
+ function createTokenContract() internal returns (MintableToken) {
+ return new MintableToken();
+ }
+
+
+ // fallback function can be used to buy tokens
+ function () payable {
+ buyTokens(msg.sender);
+ }
+
+ // low level token purchase function
+ function buyTokens(address beneficiary) payable {
+ require(beneficiary != 0x0);
+ require(validPurchase());
+
+ uint256 weiAmount = msg.value;
+ uint256 updatedWeiRaised = weiRaised.add(weiAmount);
+
+ // calculate token amount to be created
+ uint256 tokens = weiAmount.mul(rate);
+
+ // update state
+ weiRaised = updatedWeiRaised;
+
+ token.mint(beneficiary, tokens);
+ TokenPurchase(msg.sender, beneficiary, weiAmount, tokens);
+
+ forwardFunds();
+ }
+
+ // send ether to the fund collection wallet
+ // override to create custom fund forwarding mechanisms
+ function forwardFunds() internal {
+ wallet.transfer(msg.value);
+ }
+
+ // @return true if the transaction can buy tokens
+ function validPurchase() internal constant returns (bool) {
+ uint256 current = block.number;
+ bool withinPeriod = current >= startBlock && current <= endBlock;
+ bool nonZeroPurchase = msg.value != 0;
+ return withinPeriod && nonZeroPurchase;
+ }
+
+ // @return true if crowdsale event has ended
+ function hasEnded() public constant returns (bool) {
+ return block.number > endBlock;
+ }
+
+
+}
diff --git a/test/compilationTests/zeppelin/crowdsale/FinalizableCrowdsale.sol b/test/compilationTests/zeppelin/crowdsale/FinalizableCrowdsale.sol
new file mode 100644
index 00000000..1a736083
--- /dev/null
+++ b/test/compilationTests/zeppelin/crowdsale/FinalizableCrowdsale.sol
@@ -0,0 +1,39 @@
+pragma solidity ^0.4.11;
+
+import '../math/SafeMath.sol';
+import '../ownership/Ownable.sol';
+import './Crowdsale.sol';
+
+/**
+ * @title FinalizableCrowdsale
+ * @dev Extension of Crowsdale where an owner can do extra work
+ * after finishing. By default, it will end token minting.
+ */
+contract FinalizableCrowdsale is Crowdsale, Ownable {
+ using SafeMath for uint256;
+
+ bool public isFinalized = false;
+
+ event Finalized();
+
+ // should be called after crowdsale ends, to do
+ // some extra finalization work
+ function finalize() onlyOwner {
+ require(!isFinalized);
+ require(hasEnded());
+
+ finalization();
+ Finalized();
+
+ isFinalized = true;
+ }
+
+ // end token minting on finalization
+ // override this with custom logic if needed
+ function finalization() internal {
+ token.finishMinting();
+ }
+
+
+
+}
diff --git a/test/compilationTests/zeppelin/crowdsale/RefundVault.sol b/test/compilationTests/zeppelin/crowdsale/RefundVault.sol
new file mode 100644
index 00000000..cc92ff9f
--- /dev/null
+++ b/test/compilationTests/zeppelin/crowdsale/RefundVault.sol
@@ -0,0 +1,56 @@
+pragma solidity ^0.4.11;
+
+import '../math/SafeMath.sol';
+import '../ownership/Ownable.sol';
+
+/**
+ * @title RefundVault
+ * @dev This contract is used for storing funds while a crowdsale
+ * is in progress. Supports refunding the money if crowdsale fails,
+ * and forwarding it if crowdsale is successful.
+ */
+contract RefundVault is Ownable {
+ using SafeMath for uint256;
+
+ enum State { Active, Refunding, Closed }
+
+ mapping (address => uint256) public deposited;
+ address public wallet;
+ State public state;
+
+ event Closed();
+ event RefundsEnabled();
+ event Refunded(address indexed beneficiary, uint256 weiAmount);
+
+ function RefundVault(address _wallet) {
+ require(_wallet != 0x0);
+ wallet = _wallet;
+ state = State.Active;
+ }
+
+ function deposit(address investor) onlyOwner payable {
+ require(state == State.Active);
+ deposited[investor] = deposited[investor].add(msg.value);
+ }
+
+ function close() onlyOwner {
+ require(state == State.Active);
+ state = State.Closed;
+ Closed();
+ wallet.transfer(this.balance);
+ }
+
+ function enableRefunds() onlyOwner {
+ require(state == State.Active);
+ state = State.Refunding;
+ RefundsEnabled();
+ }
+
+ function refund(address investor) {
+ require(state == State.Refunding);
+ uint256 depositedValue = deposited[investor];
+ deposited[investor] = 0;
+ investor.transfer(depositedValue);
+ Refunded(investor, depositedValue);
+ }
+}
diff --git a/test/compilationTests/zeppelin/crowdsale/RefundableCrowdsale.sol b/test/compilationTests/zeppelin/crowdsale/RefundableCrowdsale.sol
new file mode 100644
index 00000000..f45df1d3
--- /dev/null
+++ b/test/compilationTests/zeppelin/crowdsale/RefundableCrowdsale.sol
@@ -0,0 +1,59 @@
+pragma solidity ^0.4.11;
+
+
+import '../math/SafeMath.sol';
+import './FinalizableCrowdsale.sol';
+import './RefundVault.sol';
+
+
+/**
+ * @title RefundableCrowdsale
+ * @dev Extension of Crowdsale contract that adds a funding goal, and
+ * the possibility of users getting a refund if goal is not met.
+ * Uses a RefundVault as the crowdsale's vault.
+ */
+contract RefundableCrowdsale is FinalizableCrowdsale {
+ using SafeMath for uint256;
+
+ // minimum amount of funds to be raised in weis
+ uint256 public goal;
+
+ // refund vault used to hold funds while crowdsale is running
+ RefundVault public vault;
+
+ function RefundableCrowdsale(uint256 _goal) {
+ vault = new RefundVault(wallet);
+ goal = _goal;
+ }
+
+ // We're overriding the fund forwarding from Crowdsale.
+ // In addition to sending the funds, we want to call
+ // the RefundVault deposit function
+ function forwardFunds() internal {
+ vault.deposit.value(msg.value)(msg.sender);
+ }
+
+ // if crowdsale is unsuccessful, investors can claim refunds here
+ function claimRefund() {
+ require(isFinalized);
+ require(!goalReached());
+
+ vault.refund(msg.sender);
+ }
+
+ // vault finalization task, called when owner calls finalize()
+ function finalization() internal {
+ if (goalReached()) {
+ vault.close();
+ } else {
+ vault.enableRefunds();
+ }
+
+ super.finalization();
+ }
+
+ function goalReached() public constant returns (bool) {
+ return weiRaised >= goal;
+ }
+
+}
diff --git a/test/compilationTests/zeppelin/lifecycle/Destructible.sol b/test/compilationTests/zeppelin/lifecycle/Destructible.sol
new file mode 100644
index 00000000..3561e3b7
--- /dev/null
+++ b/test/compilationTests/zeppelin/lifecycle/Destructible.sol
@@ -0,0 +1,25 @@
+pragma solidity ^0.4.11;
+
+
+import "../ownership/Ownable.sol";
+
+
+/**
+ * @title Destructible
+ * @dev Base contract that can be destroyed by owner. All funds in contract will be sent to the owner.
+ */
+contract Destructible is Ownable {
+
+ function Destructible() payable { }
+
+ /**
+ * @dev Transfers the current balance to the owner and terminates the contract.
+ */
+ function destroy() onlyOwner {
+ selfdestruct(owner);
+ }
+
+ function destroyAndSend(address _recipient) onlyOwner {
+ selfdestruct(_recipient);
+ }
+}
diff --git a/test/compilationTests/zeppelin/lifecycle/Migrations.sol b/test/compilationTests/zeppelin/lifecycle/Migrations.sol
new file mode 100644
index 00000000..d5b05308
--- /dev/null
+++ b/test/compilationTests/zeppelin/lifecycle/Migrations.sol
@@ -0,0 +1,21 @@
+pragma solidity ^0.4.11;
+
+
+import '../ownership/Ownable.sol';
+
+/**
+ * @title Migrations
+ * @dev This is a truffle contract, needed for truffle integration, not meant for use by Zeppelin users.
+ */
+contract Migrations is Ownable {
+ uint256 public lastCompletedMigration;
+
+ function setCompleted(uint256 completed) onlyOwner {
+ lastCompletedMigration = completed;
+ }
+
+ function upgrade(address newAddress) onlyOwner {
+ Migrations upgraded = Migrations(newAddress);
+ upgraded.setCompleted(lastCompletedMigration);
+ }
+}
diff --git a/test/compilationTests/zeppelin/lifecycle/Pausable.sol b/test/compilationTests/zeppelin/lifecycle/Pausable.sol
new file mode 100644
index 00000000..b14f8767
--- /dev/null
+++ b/test/compilationTests/zeppelin/lifecycle/Pausable.sol
@@ -0,0 +1,51 @@
+pragma solidity ^0.4.11;
+
+
+import "../ownership/Ownable.sol";
+
+
+/**
+ * @title Pausable
+ * @dev Base contract which allows children to implement an emergency stop mechanism.
+ */
+contract Pausable is Ownable {
+ event Pause();
+ event Unpause();
+
+ bool public paused = false;
+
+
+ /**
+ * @dev modifier to allow actions only when the contract IS paused
+ */
+ modifier whenNotPaused() {
+ if (paused) throw;
+ _;
+ }
+
+ /**
+ * @dev modifier to allow actions only when the contract IS NOT paused
+ */
+ modifier whenPaused {
+ if (!paused) throw;
+ _;
+ }
+
+ /**
+ * @dev called by the owner to pause, triggers stopped state
+ */
+ function pause() onlyOwner whenNotPaused returns (bool) {
+ paused = true;
+ Pause();
+ return true;
+ }
+
+ /**
+ * @dev called by the owner to unpause, returns to normal state
+ */
+ function unpause() onlyOwner whenPaused returns (bool) {
+ paused = false;
+ Unpause();
+ return true;
+ }
+}
diff --git a/test/compilationTests/zeppelin/lifecycle/TokenDestructible.sol b/test/compilationTests/zeppelin/lifecycle/TokenDestructible.sol
new file mode 100644
index 00000000..fe0b46b6
--- /dev/null
+++ b/test/compilationTests/zeppelin/lifecycle/TokenDestructible.sol
@@ -0,0 +1,36 @@
+pragma solidity ^0.4.11;
+
+
+import "../ownership/Ownable.sol";
+import "../token/ERC20Basic.sol";
+
+/**
+ * @title TokenDestructible:
+ * @author Remco Bloemen <remco@2π.com>
+ * @dev Base contract that can be destroyed by owner. All funds in contract including
+ * listed tokens will be sent to the owner.
+ */
+contract TokenDestructible is Ownable {
+
+ function TokenDestructible() payable { }
+
+ /**
+ * @notice Terminate contract and refund to owner
+ * @param tokens List of addresses of ERC20 or ERC20Basic token contracts to
+ refund.
+ * @notice The called token contracts could try to re-enter this contract. Only
+ supply token contracts you trust.
+ */
+ function destroy(address[] tokens) onlyOwner {
+
+ // Transfer tokens to owner
+ for(uint256 i = 0; i < tokens.length; i++) {
+ ERC20Basic token = ERC20Basic(tokens[i]);
+ uint256 balance = token.balanceOf(this);
+ token.transfer(owner, balance);
+ }
+
+ // Transfer Eth to owner and terminate contract
+ selfdestruct(owner);
+ }
+}
diff --git a/test/compilationTests/zeppelin/math/Math.sol b/test/compilationTests/zeppelin/math/Math.sol
new file mode 100644
index 00000000..3d016c0a
--- /dev/null
+++ b/test/compilationTests/zeppelin/math/Math.sol
@@ -0,0 +1,24 @@
+pragma solidity ^0.4.11;
+
+/**
+ * @title Math
+ * @dev Assorted math operations
+ */
+
+library Math {
+ function max64(uint64 a, uint64 b) internal constant returns (uint64) {
+ return a >= b ? a : b;
+ }
+
+ function min64(uint64 a, uint64 b) internal constant returns (uint64) {
+ return a < b ? a : b;
+ }
+
+ function max256(uint256 a, uint256 b) internal constant returns (uint256) {
+ return a >= b ? a : b;
+ }
+
+ function min256(uint256 a, uint256 b) internal constant returns (uint256) {
+ return a < b ? a : b;
+ }
+}
diff --git a/test/compilationTests/zeppelin/math/SafeMath.sol b/test/compilationTests/zeppelin/math/SafeMath.sol
new file mode 100644
index 00000000..dc05ba28
--- /dev/null
+++ b/test/compilationTests/zeppelin/math/SafeMath.sol
@@ -0,0 +1,32 @@
+pragma solidity ^0.4.11;
+
+
+/**
+ * @title SafeMath
+ * @dev Math operations with safety checks that throw on error
+ */
+library SafeMath {
+ function mul(uint256 a, uint256 b) internal returns (uint256) {
+ uint256 c = a * b;
+ assert(a == 0 || c / a == b);
+ return c;
+ }
+
+ function div(uint256 a, uint256 b) internal returns (uint256) {
+ // assert(b > 0); // Solidity automatically throws when dividing by 0
+ uint256 c = a / b;
+ // assert(a == b * c + a % b); // There is no case in which this doesn't hold
+ return c;
+ }
+
+ function sub(uint256 a, uint256 b) internal returns (uint256) {
+ assert(b <= a);
+ return a - b;
+ }
+
+ function add(uint256 a, uint256 b) internal returns (uint256) {
+ uint256 c = a + b;
+ assert(c >= a);
+ return c;
+ }
+}
diff --git a/test/compilationTests/zeppelin/ownership/Claimable.sol b/test/compilationTests/zeppelin/ownership/Claimable.sol
new file mode 100644
index 00000000..d063502d
--- /dev/null
+++ b/test/compilationTests/zeppelin/ownership/Claimable.sol
@@ -0,0 +1,40 @@
+pragma solidity ^0.4.11;
+
+
+import './Ownable.sol';
+
+
+/**
+ * @title Claimable
+ * @dev Extension for the Ownable contract, where the ownership needs to be claimed.
+ * This allows the new owner to accept the transfer.
+ */
+contract Claimable is Ownable {
+ address public pendingOwner;
+
+ /**
+ * @dev Modifier throws if called by any account other than the pendingOwner.
+ */
+ modifier onlyPendingOwner() {
+ if (msg.sender != pendingOwner) {
+ throw;
+ }
+ _;
+ }
+
+ /**
+ * @dev Allows the current owner to set the pendingOwner address.
+ * @param newOwner The address to transfer ownership to.
+ */
+ function transferOwnership(address newOwner) onlyOwner {
+ pendingOwner = newOwner;
+ }
+
+ /**
+ * @dev Allows the pendingOwner address to finalize the transfer.
+ */
+ function claimOwnership() onlyPendingOwner {
+ owner = pendingOwner;
+ pendingOwner = 0x0;
+ }
+}
diff --git a/test/compilationTests/zeppelin/ownership/Contactable.sol b/test/compilationTests/zeppelin/ownership/Contactable.sol
new file mode 100644
index 00000000..0db3ee07
--- /dev/null
+++ b/test/compilationTests/zeppelin/ownership/Contactable.sol
@@ -0,0 +1,21 @@
+pragma solidity ^0.4.11;
+
+import './Ownable.sol';
+
+/**
+ * @title Contactable token
+ * @dev Basic version of a contactable contract, allowing the owner to provide a string with their
+ * contact information.
+ */
+contract Contactable is Ownable{
+
+ string public contactInformation;
+
+ /**
+ * @dev Allows the owner to set a string with their contact information.
+ * @param info The contact information to attach to the contract.
+ */
+ function setContactInformation(string info) onlyOwner{
+ contactInformation = info;
+ }
+}
diff --git a/test/compilationTests/zeppelin/ownership/DelayedClaimable.sol b/test/compilationTests/zeppelin/ownership/DelayedClaimable.sol
new file mode 100644
index 00000000..f5fee614
--- /dev/null
+++ b/test/compilationTests/zeppelin/ownership/DelayedClaimable.sol
@@ -0,0 +1,43 @@
+pragma solidity ^0.4.11;
+
+
+import './Claimable.sol';
+
+
+/**
+ * @title DelayedClaimable
+ * @dev Extension for the Claimable contract, where the ownership needs to be claimed before/after
+ * a certain block number.
+ */
+contract DelayedClaimable is Claimable {
+
+ uint256 public end;
+ uint256 public start;
+
+ /**
+ * @dev Used to specify the time period during which a pending
+ * owner can claim ownership.
+ * @param _start The earliest time ownership can be claimed.
+ * @param _end The latest time ownership can be claimed.
+ */
+ function setLimits(uint256 _start, uint256 _end) onlyOwner {
+ if (_start > _end)
+ throw;
+ end = _end;
+ start = _start;
+ }
+
+
+ /**
+ * @dev Allows the pendingOwner address to finalize the transfer, as long as it is called within
+ * the specified start and end time.
+ */
+ function claimOwnership() onlyPendingOwner {
+ if ((block.number > end) || (block.number < start))
+ throw;
+ owner = pendingOwner;
+ pendingOwner = 0x0;
+ end = 0;
+ }
+
+}
diff --git a/test/compilationTests/zeppelin/ownership/HasNoContracts.sol b/test/compilationTests/zeppelin/ownership/HasNoContracts.sol
new file mode 100644
index 00000000..b5bd649d
--- /dev/null
+++ b/test/compilationTests/zeppelin/ownership/HasNoContracts.sol
@@ -0,0 +1,21 @@
+pragma solidity ^0.4.11;
+
+import "./Ownable.sol";
+
+/**
+ * @title Contracts that should not own Contracts
+ * @author Remco Bloemen <remco@2π.com>
+ * @dev Should contracts (anything Ownable) end up being owned by this contract, it allows the owner
+ * of this contract to reclaim ownership of the contracts.
+ */
+contract HasNoContracts is Ownable {
+
+ /**
+ * @dev Reclaim ownership of Ownable contracts
+ * @param contractAddr The address of the Ownable to be reclaimed.
+ */
+ function reclaimContract(address contractAddr) external onlyOwner {
+ Ownable contractInst = Ownable(contractAddr);
+ contractInst.transferOwnership(owner);
+ }
+}
diff --git a/test/compilationTests/zeppelin/ownership/HasNoEther.sol b/test/compilationTests/zeppelin/ownership/HasNoEther.sol
new file mode 100644
index 00000000..2bcaf1b8
--- /dev/null
+++ b/test/compilationTests/zeppelin/ownership/HasNoEther.sol
@@ -0,0 +1,44 @@
+pragma solidity ^0.4.11;
+
+import "./Ownable.sol";
+
+/**
+ * @title Contracts that should not own Ether
+ * @author Remco Bloemen <remco@2π.com>
+ * @dev This tries to block incoming ether to prevent accidental loss of Ether. Should Ether end up
+ * in the contract, it will allow the owner to reclaim this ether.
+ * @notice Ether can still be send to this contract by:
+ * calling functions labeled `payable`
+ * `selfdestruct(contract_address)`
+ * mining directly to the contract address
+*/
+contract HasNoEther is Ownable {
+
+ /**
+ * @dev Constructor that rejects incoming Ether
+ * @dev The `payable` flag is added so we can access `msg.value` without compiler warning. If we
+ * leave out payable, then Solidity will allow inheriting contracts to implement a payable
+ * constructor. By doing it this way we prevent a payable constructor from working. Alternatively
+ * we could use assembly to access msg.value.
+ */
+ function HasNoEther() payable {
+ if(msg.value > 0) {
+ throw;
+ }
+ }
+
+ /**
+ * @dev Disallows direct send by settings a default function without the `payable` flag.
+ */
+ function() external {
+ }
+
+ /**
+ * @dev Transfer all Ether held by the contract to the owner.
+ */
+ function reclaimEther() external onlyOwner {
+ if(!owner.send(this.balance)) {
+ throw;
+ }
+ }
+}
diff --git a/test/compilationTests/zeppelin/ownership/HasNoTokens.sol b/test/compilationTests/zeppelin/ownership/HasNoTokens.sol
new file mode 100644
index 00000000..d1dc4b3e
--- /dev/null
+++ b/test/compilationTests/zeppelin/ownership/HasNoTokens.sol
@@ -0,0 +1,34 @@
+pragma solidity ^0.4.11;
+
+import "./Ownable.sol";
+import "../token/ERC20Basic.sol";
+
+/**
+ * @title Contracts that should not own Tokens
+ * @author Remco Bloemen <remco@2π.com>
+ * @dev This blocks incoming ERC23 tokens to prevent accidental loss of tokens.
+ * Should tokens (any ERC20Basic compatible) end up in the contract, it allows the
+ * owner to reclaim the tokens.
+ */
+contract HasNoTokens is Ownable {
+
+ /**
+ * @dev Reject all ERC23 compatible tokens
+ * @param from_ address The address that is transferring the tokens
+ * @param value_ uint256 the amount of the specified token
+ * @param data_ Bytes The data passed from the caller.
+ */
+ function tokenFallback(address from_, uint256 value_, bytes data_) external {
+ throw;
+ }
+
+ /**
+ * @dev Reclaim all ERC20Basic compatible tokens
+ * @param tokenAddr address The address of the token contract
+ */
+ function reclaimToken(address tokenAddr) external onlyOwner {
+ ERC20Basic tokenInst = ERC20Basic(tokenAddr);
+ uint256 balance = tokenInst.balanceOf(this);
+ tokenInst.transfer(owner, balance);
+ }
+}
diff --git a/test/compilationTests/zeppelin/ownership/Multisig.sol b/test/compilationTests/zeppelin/ownership/Multisig.sol
new file mode 100644
index 00000000..76c78411
--- /dev/null
+++ b/test/compilationTests/zeppelin/ownership/Multisig.sol
@@ -0,0 +1,28 @@
+pragma solidity ^0.4.11;
+
+
+/**
+ * @title Multisig
+ * @dev Interface contract for multisig proxy contracts; see below for docs.
+ */
+contract Multisig {
+ // EVENTS
+
+ // logged events:
+ // Funds has arrived into the wallet (record how much).
+ event Deposit(address _from, uint256 value);
+ // Single transaction going out of the wallet (record who signed for it, how much, and to whom it's going).
+ event SingleTransact(address owner, uint256 value, address to, bytes data);
+ // Multi-sig transaction going out of the wallet (record who signed for it last, the operation hash, how much, and to whom it's going).
+ event MultiTransact(address owner, bytes32 operation, uint256 value, address to, bytes data);
+ // Confirmation still needed for a transaction.
+ event ConfirmationNeeded(bytes32 operation, address initiator, uint256 value, address to, bytes data);
+
+
+ // FUNCTIONS
+
+ // TODO: document
+ function changeOwner(address _from, address _to) external;
+ function execute(address _to, uint256 _value, bytes _data) external returns (bytes32);
+ function confirm(bytes32 _h) returns (bool);
+}
diff --git a/test/compilationTests/zeppelin/ownership/NoOwner.sol b/test/compilationTests/zeppelin/ownership/NoOwner.sol
new file mode 100644
index 00000000..7215abf3
--- /dev/null
+++ b/test/compilationTests/zeppelin/ownership/NoOwner.sol
@@ -0,0 +1,14 @@
+pragma solidity ^0.4.11;
+
+import "./HasNoEther.sol";
+import "./HasNoTokens.sol";
+import "./HasNoContracts.sol";
+
+/**
+ * @title Base contract for contracts that should not own things.
+ * @author Remco Bloemen <remco@2π.com>
+ * @dev Solves a class of errors where a contract accidentally becomes owner of Ether, Tokens or
+ * Owned contracts. See respective base contracts for details.
+ */
+contract NoOwner is HasNoEther, HasNoTokens, HasNoContracts {
+}
diff --git a/test/compilationTests/zeppelin/ownership/Ownable.sol b/test/compilationTests/zeppelin/ownership/Ownable.sol
new file mode 100644
index 00000000..f1628454
--- /dev/null
+++ b/test/compilationTests/zeppelin/ownership/Ownable.sol
@@ -0,0 +1,43 @@
+pragma solidity ^0.4.11;
+
+
+/**
+ * @title Ownable
+ * @dev The Ownable contract has an owner address, and provides basic authorization control
+ * functions, this simplifies the implementation of "user permissions".
+ */
+contract Ownable {
+ address public owner;
+
+
+ /**
+ * @dev The Ownable constructor sets the original `owner` of the contract to the sender
+ * account.
+ */
+ function Ownable() {
+ owner = msg.sender;
+ }
+
+
+ /**
+ * @dev Throws if called by any account other than the owner.
+ */
+ modifier onlyOwner() {
+ if (msg.sender != owner) {
+ throw;
+ }
+ _;
+ }
+
+
+ /**
+ * @dev Allows the current owner to transfer control of the contract to a newOwner.
+ * @param newOwner The address to transfer ownership to.
+ */
+ function transferOwnership(address newOwner) onlyOwner {
+ if (newOwner != address(0)) {
+ owner = newOwner;
+ }
+ }
+
+}
diff --git a/test/compilationTests/zeppelin/ownership/Shareable.sol b/test/compilationTests/zeppelin/ownership/Shareable.sol
new file mode 100644
index 00000000..9fdaccfd
--- /dev/null
+++ b/test/compilationTests/zeppelin/ownership/Shareable.sol
@@ -0,0 +1,189 @@
+pragma solidity ^0.4.11;
+
+
+/**
+ * @title Shareable
+ * @dev inheritable "property" contract that enables methods to be protected by requiring the
+ * acquiescence of either a single, or, crucially, each of a number of, designated owners.
+ * @dev Usage: use modifiers onlyowner (just own owned) or onlymanyowners(hash), whereby the same hash must be provided by some number (specified in constructor) of the set of owners (specified in the constructor) before the interior is executed.
+ */
+contract Shareable {
+
+ // struct for the status of a pending operation.
+ struct PendingState {
+ uint256 yetNeeded;
+ uint256 ownersDone;
+ uint256 index;
+ }
+
+ // the number of owners that must confirm the same operation before it is run.
+ uint256 public required;
+
+ // list of owners
+ address[256] owners;
+ // index on the list of owners to allow reverse lookup
+ mapping(address => uint256) ownerIndex;
+ // the ongoing operations.
+ mapping(bytes32 => PendingState) pendings;
+ bytes32[] pendingsIndex;
+
+
+ // this contract only has six types of events: it can accept a confirmation, in which case
+ // we record owner and operation (hash) alongside it.
+ event Confirmation(address owner, bytes32 operation);
+ event Revoke(address owner, bytes32 operation);
+
+
+ // simple single-sig function modifier.
+ modifier onlyOwner {
+ if (!isOwner(msg.sender)) {
+ throw;
+ }
+ _;
+ }
+
+ /**
+ * @dev Modifier for multisig functions.
+ * @param _operation The operation must have an intrinsic hash in order that later attempts can be
+ * realised as the same underlying operation and thus count as confirmations.
+ */
+ modifier onlymanyowners(bytes32 _operation) {
+ if (confirmAndCheck(_operation)) {
+ _;
+ }
+ }
+
+ /**
+ * @dev Constructor is given the number of sigs required to do protected "onlymanyowners"
+ * transactions as well as the selection of addresses capable of confirming them.
+ * @param _owners A list of owners.
+ * @param _required The amount required for a transaction to be approved.
+ */
+ function Shareable(address[] _owners, uint256 _required) {
+ owners[1] = msg.sender;
+ ownerIndex[msg.sender] = 1;
+ for (uint256 i = 0; i < _owners.length; ++i) {
+ owners[2 + i] = _owners[i];
+ ownerIndex[_owners[i]] = 2 + i;
+ }
+ required = _required;
+ if (required > owners.length) {
+ throw;
+ }
+ }
+
+ /**
+ * @dev Revokes a prior confirmation of the given operation.
+ * @param _operation A string identifying the operation.
+ */
+ function revoke(bytes32 _operation) external {
+ uint256 index = ownerIndex[msg.sender];
+ // make sure they're an owner
+ if (index == 0) {
+ return;
+ }
+ uint256 ownerIndexBit = 2**index;
+ var pending = pendings[_operation];
+ if (pending.ownersDone & ownerIndexBit > 0) {
+ pending.yetNeeded++;
+ pending.ownersDone -= ownerIndexBit;
+ Revoke(msg.sender, _operation);
+ }
+ }
+
+ /**
+ * @dev Gets an owner by 0-indexed position (using numOwners as the count)
+ * @param ownerIndex uint256 The index of the owner
+ * @return The address of the owner
+ */
+ function getOwner(uint256 ownerIndex) external constant returns (address) {
+ return address(owners[ownerIndex + 1]);
+ }
+
+ /**
+ * @dev Checks if given address is an owner.
+ * @param _addr address The address which you want to check.
+ * @return True if the address is an owner and fase otherwise.
+ */
+ function isOwner(address _addr) constant returns (bool) {
+ return ownerIndex[_addr] > 0;
+ }
+
+ /**
+ * @dev Function to check is specific owner has already confirme the operation.
+ * @param _operation The operation identifier.
+ * @param _owner The owner address.
+ * @return True if the owner has confirmed and false otherwise.
+ */
+ function hasConfirmed(bytes32 _operation, address _owner) constant returns (bool) {
+ var pending = pendings[_operation];
+ uint256 index = ownerIndex[_owner];
+
+ // make sure they're an owner
+ if (index == 0) {
+ return false;
+ }
+
+ // determine the bit to set for this owner.
+ uint256 ownerIndexBit = 2**index;
+ return !(pending.ownersDone & ownerIndexBit == 0);
+ }
+
+ /**
+ * @dev Confirm and operation and checks if it's already executable.
+ * @param _operation The operation identifier.
+ * @return Returns true when operation can be executed.
+ */
+ function confirmAndCheck(bytes32 _operation) internal returns (bool) {
+ // determine what index the present sender is:
+ uint256 index = ownerIndex[msg.sender];
+ // make sure they're an owner
+ if (index == 0) {
+ throw;
+ }
+
+ var pending = pendings[_operation];
+ // if we're not yet working on this operation, switch over and reset the confirmation status.
+ if (pending.yetNeeded == 0) {
+ // reset count of confirmations needed.
+ pending.yetNeeded = required;
+ // reset which owners have confirmed (none) - set our bitmap to 0.
+ pending.ownersDone = 0;
+ pending.index = pendingsIndex.length++;
+ pendingsIndex[pending.index] = _operation;
+ }
+ // determine the bit to set for this owner.
+ uint256 ownerIndexBit = 2**index;
+ // make sure we (the message sender) haven't confirmed this operation previously.
+ if (pending.ownersDone & ownerIndexBit == 0) {
+ Confirmation(msg.sender, _operation);
+ // ok - check if count is enough to go ahead.
+ if (pending.yetNeeded <= 1) {
+ // enough confirmations: reset and run interior.
+ delete pendingsIndex[pendings[_operation].index];
+ delete pendings[_operation];
+ return true;
+ } else {
+ // not enough: record that this owner in particular confirmed.
+ pending.yetNeeded--;
+ pending.ownersDone |= ownerIndexBit;
+ }
+ }
+ return false;
+ }
+
+
+ /**
+ * @dev Clear the pending list.
+ */
+ function clearPending() internal {
+ uint256 length = pendingsIndex.length;
+ for (uint256 i = 0; i < length; ++i) {
+ if (pendingsIndex[i] != 0) {
+ delete pendings[pendingsIndex[i]];
+ }
+ }
+ delete pendingsIndex;
+ }
+
+}
diff --git a/test/compilationTests/zeppelin/payment/PullPayment.sol b/test/compilationTests/zeppelin/payment/PullPayment.sol
new file mode 100644
index 00000000..ba710b53
--- /dev/null
+++ b/test/compilationTests/zeppelin/payment/PullPayment.sol
@@ -0,0 +1,50 @@
+pragma solidity ^0.4.11;
+
+
+import '../math/SafeMath.sol';
+
+
+/**
+ * @title PullPayment
+ * @dev Base contract supporting async send for pull payments. Inherit from this
+ * contract and use asyncSend instead of send.
+ */
+contract PullPayment {
+ using SafeMath for uint256;
+
+ mapping(address => uint256) public payments;
+ uint256 public totalPayments;
+
+ /**
+ * @dev Called by the payer to store the sent amount as credit to be pulled.
+ * @param dest The destination address of the funds.
+ * @param amount The amount to transfer.
+ */
+ function asyncSend(address dest, uint256 amount) internal {
+ payments[dest] = payments[dest].add(amount);
+ totalPayments = totalPayments.add(amount);
+ }
+
+ /**
+ * @dev withdraw accumulated balance, called by payee.
+ */
+ function withdrawPayments() {
+ address payee = msg.sender;
+ uint256 payment = payments[payee];
+
+ if (payment == 0) {
+ throw;
+ }
+
+ if (this.balance < payment) {
+ throw;
+ }
+
+ totalPayments = totalPayments.sub(payment);
+ payments[payee] = 0;
+
+ if (!payee.send(payment)) {
+ throw;
+ }
+ }
+}
diff --git a/test/compilationTests/zeppelin/token/BasicToken.sol b/test/compilationTests/zeppelin/token/BasicToken.sol
new file mode 100644
index 00000000..5618227a
--- /dev/null
+++ b/test/compilationTests/zeppelin/token/BasicToken.sol
@@ -0,0 +1,37 @@
+pragma solidity ^0.4.11;
+
+
+import './ERC20Basic.sol';
+import '../math/SafeMath.sol';
+
+
+/**
+ * @title Basic token
+ * @dev Basic version of StandardToken, with no allowances.
+ */
+contract BasicToken is ERC20Basic {
+ using SafeMath for uint256;
+
+ mapping(address => uint256) balances;
+
+ /**
+ * @dev transfer token for a specified address
+ * @param _to The address to transfer to.
+ * @param _value The amount to be transferred.
+ */
+ function transfer(address _to, uint256 _value) {
+ balances[msg.sender] = balances[msg.sender].sub(_value);
+ balances[_to] = balances[_to].add(_value);
+ Transfer(msg.sender, _to, _value);
+ }
+
+ /**
+ * @dev Gets the balance of the specified address.
+ * @param _owner The address to query the the balance of.
+ * @return An uint256 representing the amount owned by the passed address.
+ */
+ function balanceOf(address _owner) constant returns (uint256 balance) {
+ return balances[_owner];
+ }
+
+}
diff --git a/test/compilationTests/zeppelin/token/ERC20.sol b/test/compilationTests/zeppelin/token/ERC20.sol
new file mode 100644
index 00000000..1045ac35
--- /dev/null
+++ b/test/compilationTests/zeppelin/token/ERC20.sol
@@ -0,0 +1,16 @@
+pragma solidity ^0.4.11;
+
+
+import './ERC20Basic.sol';
+
+
+/**
+ * @title ERC20 interface
+ * @dev see https://github.com/ethereum/EIPs/issues/20
+ */
+contract ERC20 is ERC20Basic {
+ function allowance(address owner, address spender) constant returns (uint256);
+ function transferFrom(address from, address to, uint256 value);
+ function approve(address spender, uint256 value);
+ event Approval(address indexed owner, address indexed spender, uint256 value);
+}
diff --git a/test/compilationTests/zeppelin/token/ERC20Basic.sol b/test/compilationTests/zeppelin/token/ERC20Basic.sol
new file mode 100644
index 00000000..0e98779e
--- /dev/null
+++ b/test/compilationTests/zeppelin/token/ERC20Basic.sol
@@ -0,0 +1,14 @@
+pragma solidity ^0.4.11;
+
+
+/**
+ * @title ERC20Basic
+ * @dev Simpler version of ERC20 interface
+ * @dev see https://github.com/ethereum/EIPs/issues/20
+ */
+contract ERC20Basic {
+ uint256 public totalSupply;
+ function balanceOf(address who) constant returns (uint256);
+ function transfer(address to, uint256 value);
+ event Transfer(address indexed from, address indexed to, uint256 value);
+}
diff --git a/test/compilationTests/zeppelin/token/LimitedTransferToken.sol b/test/compilationTests/zeppelin/token/LimitedTransferToken.sol
new file mode 100644
index 00000000..ee5032c9
--- /dev/null
+++ b/test/compilationTests/zeppelin/token/LimitedTransferToken.sol
@@ -0,0 +1,57 @@
+pragma solidity ^0.4.11;
+
+import "./ERC20.sol";
+
+/**
+ * @title LimitedTransferToken
+ * @dev LimitedTransferToken defines the generic interface and the implementation to limit token
+ * transferability for different events. It is intended to be used as a base class for other token
+ * contracts.
+ * LimitedTransferToken has been designed to allow for different limiting factors,
+ * this can be achieved by recursively calling super.transferableTokens() until the base class is
+ * hit. For example:
+ * function transferableTokens(address holder, uint64 time) constant public returns (uint256) {
+ * return min256(unlockedTokens, super.transferableTokens(holder, time));
+ * }
+ * A working example is VestedToken.sol:
+ * https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/token/VestedToken.sol
+ */
+
+contract LimitedTransferToken is ERC20 {
+
+ /**
+ * @dev Checks whether it can transfer or otherwise throws.
+ */
+ modifier canTransfer(address _sender, uint256 _value) {
+ if (_value > transferableTokens(_sender, uint64(now))) throw;
+ _;
+ }
+
+ /**
+ * @dev Checks modifier and allows transfer if tokens are not locked.
+ * @param _to The address that will recieve the tokens.
+ * @param _value The amount of tokens to be transferred.
+ */
+ function transfer(address _to, uint256 _value) canTransfer(msg.sender, _value) {
+ super.transfer(_to, _value);
+ }
+
+ /**
+ * @dev Checks modifier and allows transfer if tokens are not locked.
+ * @param _from The address that will send the tokens.
+ * @param _to The address that will recieve the tokens.
+ * @param _value The amount of tokens to be transferred.
+ */
+ function transferFrom(address _from, address _to, uint256 _value) canTransfer(_from, _value) {
+ super.transferFrom(_from, _to, _value);
+ }
+
+ /**
+ * @dev Default transferable tokens function returns all tokens for a holder (no limit).
+ * @dev Overwriting transferableTokens(address holder, uint64 time) is the way to provide the
+ * specific logic for limiting token transferability for a holder over time.
+ */
+ function transferableTokens(address holder, uint64 time) constant public returns (uint256) {
+ return balanceOf(holder);
+ }
+}
diff --git a/test/compilationTests/zeppelin/token/MintableToken.sol b/test/compilationTests/zeppelin/token/MintableToken.sol
new file mode 100644
index 00000000..505d13c3
--- /dev/null
+++ b/test/compilationTests/zeppelin/token/MintableToken.sol
@@ -0,0 +1,50 @@
+pragma solidity ^0.4.11;
+
+
+import './StandardToken.sol';
+import '../ownership/Ownable.sol';
+
+
+
+/**
+ * @title Mintable token
+ * @dev Simple ERC20 Token example, with mintable token creation
+ * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120
+ * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
+ */
+
+contract MintableToken is StandardToken, Ownable {
+ event Mint(address indexed to, uint256 amount);
+ event MintFinished();
+
+ bool public mintingFinished = false;
+
+
+ modifier canMint() {
+ if(mintingFinished) throw;
+ _;
+ }
+
+ /**
+ * @dev Function to mint tokens
+ * @param _to The address that will recieve the minted tokens.
+ * @param _amount The amount of tokens to mint.
+ * @return A boolean that indicates if the operation was successful.
+ */
+ function mint(address _to, uint256 _amount) onlyOwner canMint returns (bool) {
+ totalSupply = totalSupply.add(_amount);
+ balances[_to] = balances[_to].add(_amount);
+ Mint(_to, _amount);
+ return true;
+ }
+
+ /**
+ * @dev Function to stop minting new tokens.
+ * @return True if the operation was successful.
+ */
+ function finishMinting() onlyOwner returns (bool) {
+ mintingFinished = true;
+ MintFinished();
+ return true;
+ }
+}
diff --git a/test/compilationTests/zeppelin/token/PausableToken.sol b/test/compilationTests/zeppelin/token/PausableToken.sol
new file mode 100644
index 00000000..8ee114e1
--- /dev/null
+++ b/test/compilationTests/zeppelin/token/PausableToken.sol
@@ -0,0 +1,21 @@
+pragma solidity ^0.4.11;
+
+import './StandardToken.sol';
+import '../lifecycle/Pausable.sol';
+
+/**
+ * Pausable token
+ *
+ * Simple ERC20 Token example, with pausable token creation
+ **/
+
+contract PausableToken is StandardToken, Pausable {
+
+ function transfer(address _to, uint _value) whenNotPaused {
+ super.transfer(_to, _value);
+ }
+
+ function transferFrom(address _from, address _to, uint _value) whenNotPaused {
+ super.transferFrom(_from, _to, _value);
+ }
+}
diff --git a/test/compilationTests/zeppelin/token/SimpleToken.sol b/test/compilationTests/zeppelin/token/SimpleToken.sol
new file mode 100644
index 00000000..898cb21d
--- /dev/null
+++ b/test/compilationTests/zeppelin/token/SimpleToken.sol
@@ -0,0 +1,28 @@
+pragma solidity ^0.4.11;
+
+
+import "./StandardToken.sol";
+
+
+/**
+ * @title SimpleToken
+ * @dev Very simple ERC20 Token example, where all tokens are pre-assigned to the creator.
+ * Note they can later distribute these tokens as they wish using `transfer` and other
+ * `StandardToken` functions.
+ */
+contract SimpleToken is StandardToken {
+
+ string public name = "SimpleToken";
+ string public symbol = "SIM";
+ uint256 public decimals = 18;
+ uint256 public INITIAL_SUPPLY = 10000;
+
+ /**
+ * @dev Contructor that gives msg.sender all of existing tokens.
+ */
+ function SimpleToken() {
+ totalSupply = INITIAL_SUPPLY;
+ balances[msg.sender] = INITIAL_SUPPLY;
+ }
+
+}
diff --git a/test/compilationTests/zeppelin/token/StandardToken.sol b/test/compilationTests/zeppelin/token/StandardToken.sol
new file mode 100644
index 00000000..b1b49fe3
--- /dev/null
+++ b/test/compilationTests/zeppelin/token/StandardToken.sol
@@ -0,0 +1,65 @@
+pragma solidity ^0.4.11;
+
+
+import './BasicToken.sol';
+import './ERC20.sol';
+
+
+/**
+ * @title Standard ERC20 token
+ *
+ * @dev Implementation of the basic standard token.
+ * @dev https://github.com/ethereum/EIPs/issues/20
+ * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
+ */
+contract StandardToken is ERC20, BasicToken {
+
+ mapping (address => mapping (address => uint256)) allowed;
+
+
+ /**
+ * @dev Transfer tokens from one address to another
+ * @param _from address The address which you want to send tokens from
+ * @param _to address The address which you want to transfer to
+ * @param _value uint256 the amout of tokens to be transfered
+ */
+ function transferFrom(address _from, address _to, uint256 _value) {
+ var _allowance = allowed[_from][msg.sender];
+
+ // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
+ // if (_value > _allowance) throw;
+
+ balances[_to] = balances[_to].add(_value);
+ balances[_from] = balances[_from].sub(_value);
+ allowed[_from][msg.sender] = _allowance.sub(_value);
+ Transfer(_from, _to, _value);
+ }
+
+ /**
+ * @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender.
+ * @param _spender The address which will spend the funds.
+ * @param _value The amount of tokens to be spent.
+ */
+ function approve(address _spender, uint256 _value) {
+
+ // To change the approve amount you first have to reduce the addresses`
+ // allowance to zero by calling `approve(_spender, 0)` if it is not
+ // already 0 to mitigate the race condition described here:
+ // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
+ if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) throw;
+
+ allowed[msg.sender][_spender] = _value;
+ Approval(msg.sender, _spender, _value);
+ }
+
+ /**
+ * @dev Function to check the amount of tokens that an owner allowed to a spender.
+ * @param _owner address The address which owns the funds.
+ * @param _spender address The address which will spend the funds.
+ * @return A uint256 specifing the amount of tokens still avaible for the spender.
+ */
+ function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
+ return allowed[_owner][_spender];
+ }
+
+}
diff --git a/test/compilationTests/zeppelin/token/TokenTimelock.sol b/test/compilationTests/zeppelin/token/TokenTimelock.sol
new file mode 100644
index 00000000..595bf8d0
--- /dev/null
+++ b/test/compilationTests/zeppelin/token/TokenTimelock.sol
@@ -0,0 +1,41 @@
+pragma solidity ^0.4.11;
+
+
+import './ERC20Basic.sol';
+
+/**
+ * @title TokenTimelock
+ * @dev TokenTimelock is a token holder contract that will allow a
+ * beneficiary to extract the tokens after a given release time
+ */
+contract TokenTimelock {
+
+ // ERC20 basic token contract being held
+ ERC20Basic token;
+
+ // beneficiary of tokens after they are released
+ address beneficiary;
+
+ // timestamp when token release is enabled
+ uint releaseTime;
+
+ function TokenTimelock(ERC20Basic _token, address _beneficiary, uint _releaseTime) {
+ require(_releaseTime > now);
+ token = _token;
+ beneficiary = _beneficiary;
+ releaseTime = _releaseTime;
+ }
+
+ /**
+ * @dev beneficiary claims tokens held by time lock
+ */
+ function claim() {
+ require(msg.sender == beneficiary);
+ require(now >= releaseTime);
+
+ uint amount = token.balanceOf(this);
+ require(amount > 0);
+
+ token.transfer(beneficiary, amount);
+ }
+}
diff --git a/test/compilationTests/zeppelin/token/VestedToken.sol b/test/compilationTests/zeppelin/token/VestedToken.sol
new file mode 100644
index 00000000..b7748b09
--- /dev/null
+++ b/test/compilationTests/zeppelin/token/VestedToken.sol
@@ -0,0 +1,248 @@
+pragma solidity ^0.4.11;
+
+import "../math/Math.sol";
+import "./StandardToken.sol";
+import "./LimitedTransferToken.sol";
+
+/**
+ * @title Vested token
+ * @dev Tokens that can be vested for a group of addresses.
+ */
+contract VestedToken is StandardToken, LimitedTransferToken {
+
+ uint256 MAX_GRANTS_PER_ADDRESS = 20;
+
+ struct TokenGrant {
+ address granter; // 20 bytes
+ uint256 value; // 32 bytes
+ uint64 cliff;
+ uint64 vesting;
+ uint64 start; // 3 * 8 = 24 bytes
+ bool revokable;
+ bool burnsOnRevoke; // 2 * 1 = 2 bits? or 2 bytes?
+ } // total 78 bytes = 3 sstore per operation (32 per sstore)
+
+ mapping (address => TokenGrant[]) public grants;
+
+ event NewTokenGrant(address indexed from, address indexed to, uint256 value, uint256 grantId);
+
+ /**
+ * @dev Grant tokens to a specified address
+ * @param _to address The address which the tokens will be granted to.
+ * @param _value uint256 The amount of tokens to be granted.
+ * @param _start uint64 Time of the beginning of the grant.
+ * @param _cliff uint64 Time of the cliff period.
+ * @param _vesting uint64 The vesting period.
+ */
+ function grantVestedTokens(
+ address _to,
+ uint256 _value,
+ uint64 _start,
+ uint64 _cliff,
+ uint64 _vesting,
+ bool _revokable,
+ bool _burnsOnRevoke
+ ) public {
+
+ // Check for date inconsistencies that may cause unexpected behavior
+ if (_cliff < _start || _vesting < _cliff) {
+ throw;
+ }
+
+ if (tokenGrantsCount(_to) > MAX_GRANTS_PER_ADDRESS) throw; // To prevent a user being spammed and have his balance locked (out of gas attack when calculating vesting).
+
+ uint256 count = grants[_to].push(
+ TokenGrant(
+ _revokable ? msg.sender : 0, // avoid storing an extra 20 bytes when it is non-revokable
+ _value,
+ _cliff,
+ _vesting,
+ _start,
+ _revokable,
+ _burnsOnRevoke
+ )
+ );
+
+ transfer(_to, _value);
+
+ NewTokenGrant(msg.sender, _to, _value, count - 1);
+ }
+
+ /**
+ * @dev Revoke the grant of tokens of a specifed address.
+ * @param _holder The address which will have its tokens revoked.
+ * @param _grantId The id of the token grant.
+ */
+ function revokeTokenGrant(address _holder, uint256 _grantId) public {
+ TokenGrant grant = grants[_holder][_grantId];
+
+ if (!grant.revokable) { // Check if grant was revokable
+ throw;
+ }
+
+ if (grant.granter != msg.sender) { // Only granter can revoke it
+ throw;
+ }
+
+ address receiver = grant.burnsOnRevoke ? 0xdead : msg.sender;
+
+ uint256 nonVested = nonVestedTokens(grant, uint64(now));
+
+ // remove grant from array
+ delete grants[_holder][_grantId];
+ grants[_holder][_grantId] = grants[_holder][grants[_holder].length.sub(1)];
+ grants[_holder].length -= 1;
+
+ balances[receiver] = balances[receiver].add(nonVested);
+ balances[_holder] = balances[_holder].sub(nonVested);
+
+ Transfer(_holder, receiver, nonVested);
+ }
+
+
+ /**
+ * @dev Calculate the total amount of transferable tokens of a holder at a given time
+ * @param holder address The address of the holder
+ * @param time uint64 The specific time.
+ * @return An uint256 representing a holder's total amount of transferable tokens.
+ */
+ function transferableTokens(address holder, uint64 time) constant public returns (uint256) {
+ uint256 grantIndex = tokenGrantsCount(holder);
+
+ if (grantIndex == 0) return balanceOf(holder); // shortcut for holder without grants
+
+ // Iterate through all the grants the holder has, and add all non-vested tokens
+ uint256 nonVested = 0;
+ for (uint256 i = 0; i < grantIndex; i++) {
+ nonVested = SafeMath.add(nonVested, nonVestedTokens(grants[holder][i], time));
+ }
+
+ // Balance - totalNonVested is the amount of tokens a holder can transfer at any given time
+ uint256 vestedTransferable = SafeMath.sub(balanceOf(holder), nonVested);
+
+ // Return the minimum of how many vested can transfer and other value
+ // in case there are other limiting transferability factors (default is balanceOf)
+ return Math.min256(vestedTransferable, super.transferableTokens(holder, time));
+ }
+
+ /**
+ * @dev Check the amount of grants that an address has.
+ * @param _holder The holder of the grants.
+ * @return A uint256 representing the total amount of grants.
+ */
+ function tokenGrantsCount(address _holder) constant returns (uint256 index) {
+ return grants[_holder].length;
+ }
+
+ /**
+ * @dev Calculate amount of vested tokens at a specifc time.
+ * @param tokens uint256 The amount of tokens grantted.
+ * @param time uint64 The time to be checked
+ * @param start uint64 A time representing the begining of the grant
+ * @param cliff uint64 The cliff period.
+ * @param vesting uint64 The vesting period.
+ * @return An uint256 representing the amount of vested tokensof a specif grant.
+ * transferableTokens
+ * | _/-------- vestedTokens rect
+ * | _/
+ * | _/
+ * | _/
+ * | _/
+ * | /
+ * | .|
+ * | . |
+ * | . |
+ * | . |
+ * | . |
+ * | . |
+ * +===+===========+---------+----------> time
+ * Start Clift Vesting
+ */
+ function calculateVestedTokens(
+ uint256 tokens,
+ uint256 time,
+ uint256 start,
+ uint256 cliff,
+ uint256 vesting) constant returns (uint256)
+ {
+ // Shortcuts for before cliff and after vesting cases.
+ if (time < cliff) return 0;
+ if (time >= vesting) return tokens;
+
+ // Interpolate all vested tokens.
+ // As before cliff the shortcut returns 0, we can use just calculate a value
+ // in the vesting rect (as shown in above's figure)
+
+ // vestedTokens = tokens * (time - start) / (vesting - start)
+ uint256 vestedTokens = SafeMath.div(
+ SafeMath.mul(
+ tokens,
+ SafeMath.sub(time, start)
+ ),
+ SafeMath.sub(vesting, start)
+ );
+
+ return vestedTokens;
+ }
+
+ /**
+ * @dev Get all information about a specifc grant.
+ * @param _holder The address which will have its tokens revoked.
+ * @param _grantId The id of the token grant.
+ * @return Returns all the values that represent a TokenGrant(address, value, start, cliff,
+ * revokability, burnsOnRevoke, and vesting) plus the vested value at the current time.
+ */
+ function tokenGrant(address _holder, uint256 _grantId) constant returns (address granter, uint256 value, uint256 vested, uint64 start, uint64 cliff, uint64 vesting, bool revokable, bool burnsOnRevoke) {
+ TokenGrant grant = grants[_holder][_grantId];
+
+ granter = grant.granter;
+ value = grant.value;
+ start = grant.start;
+ cliff = grant.cliff;
+ vesting = grant.vesting;
+ revokable = grant.revokable;
+ burnsOnRevoke = grant.burnsOnRevoke;
+
+ vested = vestedTokens(grant, uint64(now));
+ }
+
+ /**
+ * @dev Get the amount of vested tokens at a specific time.
+ * @param grant TokenGrant The grant to be checked.
+ * @param time The time to be checked
+ * @return An uint256 representing the amount of vested tokens of a specific grant at a specific time.
+ */
+ function vestedTokens(TokenGrant grant, uint64 time) private constant returns (uint256) {
+ return calculateVestedTokens(
+ grant.value,
+ uint256(time),
+ uint256(grant.start),
+ uint256(grant.cliff),
+ uint256(grant.vesting)
+ );
+ }
+
+ /**
+ * @dev Calculate the amount of non vested tokens at a specific time.
+ * @param grant TokenGrant The grant to be checked.
+ * @param time uint64 The time to be checked
+ * @return An uint256 representing the amount of non vested tokens of a specifc grant on the
+ * passed time frame.
+ */
+ function nonVestedTokens(TokenGrant grant, uint64 time) private constant returns (uint256) {
+ return grant.value.sub(vestedTokens(grant, time));
+ }
+
+ /**
+ * @dev Calculate the date when the holder can trasfer all its tokens
+ * @param holder address The address of the holder
+ * @return An uint256 representing the date of the last transferable tokens.
+ */
+ function lastTokenIsTransferableDate(address holder) constant public returns (uint64 date) {
+ date = uint64(now);
+ uint256 grantIndex = grants[holder].length;
+ for (uint256 i = 0; i < grantIndex; i++) {
+ date = Math.max64(grants[holder][i].vesting, date);
+ }
+ }
+}