commit
e032b86231
@ -0,0 +1,290 @@ |
||||
# OpenZeppelin Audit |
||||
|
||||
March, 2017 |
||||
Authored by Dennis Peterson and Peter Vessenes |
||||
|
||||
# Introduction |
||||
|
||||
Zeppelin requested that New Alchemy perform an audit of the contracts in their OpenZeppelin library. The OpenZeppelin contracts are a set of contracts intended to be a safe building block for a variety of uses by parties that may not be as sophisticated as the OpenZeppelin team. It is a design goal that the contracts be deployable safely and "as-is". |
||||
|
||||
The contracts are hosted at: |
||||
|
||||
https://github.com/OpenZeppelin/zeppelin-solidity |
||||
|
||||
All the contracts in the "contracts" folder are in scope. |
||||
|
||||
The git commit hash we evaluated is: |
||||
9c5975a706b076b7000e8179f8101e0c61024c87 |
||||
|
||||
# Disclaimer |
||||
|
||||
The audit makes no statements or warrantees about utility of the code, safety of the code, suitability of the business model, regulatory regime for the business model, or any other statements about fitness of the contracts to purpose, or their bugfree status. The audit documentation is for discussion purposes only. |
||||
|
||||
# Executive Summary |
||||
|
||||
Overall the OpenZeppelin codebase is of reasonably high quality -- it is clean, modular and follows best practices throughout. |
||||
|
||||
It is still in flux as a codebase, and needs better documentation per file as to expected behavior and future plans. It probably needs more comprehensive and aggressive tests written by people less nice than the current OpenZeppelin team. |
||||
|
||||
We identified two critical errors and one moderate issue, and would not recommend this commit hash for public use until these bugs are remedied. |
||||
|
||||
The repository includes a set of Truffle unit tests, a requirement and best practice for smart contracts like these; we recommend these be bulked up. |
||||
|
||||
# Discussion |
||||
|
||||
## Big Picture: Is This A Worthwhile Project? |
||||
|
||||
As soon as a developer touches OpenZeppelin contracts, they will modify something, leaving them in an un-audited state. We do not recommend developers deploy any unaudited code to the Blockchain if it will handle money, information or other things of value. |
||||
|
||||
> "In accordance with Unix philosophy, Perl gives you enough rope to hang yourself" |
||||
> --Larry Wall |
||||
|
||||
We think this is an incredibly worthwhile project -- aided by the high code quality. Creating a framework that can be easily extended helps increase the average code quality on the Blockchain by charting a course for developers and encouraging containment of modifications to certain sections. |
||||
|
||||
> "Rust: The language that makes you take the safety off before shooting yourself in the foot" |
||||
> -- (@mbrubeck) |
||||
|
||||
We think much more could be done here, and recommend the OpenZeppelin team keep at this and keep focusing on the design goal of removing rope and adding safety. |
||||
|
||||
## Solidity Version Updates Recommended |
||||
|
||||
Most of the code uses Solidity 0.4.8, but some files under `Ownership` are marked 0.4.0. These should be updated. |
||||
|
||||
Solidity 0.4.10 will add several features which could be useful in these contracts: |
||||
|
||||
- `assert(condition)`, which throws if the condition is false |
||||
|
||||
- `revert()`, which rolls back without consuming all remaining gas. |
||||
|
||||
- `address.transfer(value)`, which is like `send` but automatically propagates exceptions, and supports `.gas()`. See https://github.com/ethereum/solidity/issues/610 for more on this. |
||||
|
||||
## Error Handling: Throw vs Return False |
||||
Solidity standards allow two ways to handle an error -- either calling `throw` or returning `false`. Both have benefits. In particular, a `throw` guarantees a complete wipe of the call stack (up to the preceding external call), whereas `false` allows a function to continue. |
||||
|
||||
In general we prefer `throw` in our code audits, because it is simpler -- it's less for an engineer to keep track of. Returning `false` and using logic to check results can quickly become a poorly-tracked state machine, and this sort of complexity can cause errors. |
||||
|
||||
In the OpenZeppelin contracts, both styles are used in different parts of the codebase. `SimpleToken` transfers throw upon failure, while the full ERC20 token returns `false`. Some modifiers `throw`, others just wrap the function body in a conditional, effectively allowing the function to return false if the condition is not met. |
||||
|
||||
We don't love this, and would usually recommend you stick with one style or the other throughout the codebase. |
||||
|
||||
In at least one case, these different techniques are combined cleverly (see the Multisig comments, line 65). As a set of contracts intended for general use, we recommend you either strive for more consistency or document explicit design criteria that govern which techniques are used where. |
||||
|
||||
Note that it may be impossible to use either one in all situations. For example, SafeMath functions pretty much have to throw upon failure, but ERC20 specifies returning booleans. Therefore we make no particular recommendations, but simply point out inconsistencies to consider. |
||||
|
||||
# Critical Issues |
||||
|
||||
## Stuck Ether in Crowdsale contract |
||||
CrowdsaleToken.sol has no provision for withdrawing the raised ether. We *strongly* recommend a standard `withdraw` function be added. There is no scenario in which someone should deploy this contract as is, whether for testing or live. |
||||
|
||||
## Recursive Call in MultisigWallet |
||||
Line 45 of `MultisigWallet.sol` checks if the amount being sent by `execute` is under a daily limit. |
||||
|
||||
This function can only be called by the "Owner". As a first angle of attack, it's worth asking what will happen if the multisig wallet owners reset the daily limit by approving a call to `resetSpentToday`. |
||||
|
||||
If a chain of calls can be constructed in which the owner confirms the `resetSpentToday` function and then withdraws through `execute` in a recursive call, the contract can be drained. In fact, this could be done without a recursive call, just through repeated `execute` calls alternating with the `confirm` calls. |
||||
|
||||
We are still working through the confirmation protocol in `Shareable.sol`, but we are not convinced that this is impossible, in fact it looks possible. The flexibility any shared owner has in being able to revoke confirmation later is another worrisome angle of approach even if some simple patches are included. |
||||
|
||||
This bug has a number of causes that need to be addressed: |
||||
|
||||
1. `resetSpentToday` and `confirm` together do not limit the days on which the function can be called or (it appears) the number of times it can be called. |
||||
1. Once a call has been confirmed and `execute`d it appears that it can be re-executed. This is not good. |
||||
3. `confirmandCheck` doesn't seem to have logic about whether or not the function in question has been called. |
||||
4. Even if it did, `revoke` would need updates and logic to deal with revocation requests after a function call had been completed. |
||||
|
||||
We do not recommend using the MultisigWallet until these issues are fixed. |
||||
|
||||
# Moderate to Minor Issues |
||||
|
||||
## PullPayment |
||||
PullPayment.sol needs some work. It has no explicit provision for cancelling a payment. This would be desirable in a number of scenarios; consider a payee losing their wallet, or giving a griefing address, or just an address that requires more than the default gas offered by `send`. |
||||
|
||||
`asyncSend` has no overflow checking. This is a bad plan. We recommend overflow and underflow checking at the layer closest to the data manipulation. |
||||
|
||||
`asyncSend` allows more balance to be queued up for sending than the contract holds. This is probably a bad idea, or at the very least should be called something different. If the intent is to allow this, it should have provisions for dealing with race conditions between competing `withdrawPayments` calls. |
||||
|
||||
It would be nice to see how many payments are pending. This would imply a bit of a rewrite; we recommend this contract get some design time, and that developers don't rely on it in its current state. |
||||
|
||||
## Shareable Contract |
||||
|
||||
We do not believe the `Shareable.sol` contract is ready for primetime. It is missing functions, and as written may be vulnerable to a reordering attack -- an attack in which a miner or other party "racing" with a smart contract participant inserts their own information into a list or mapping. |
||||
|
||||
The confirmation and revocation code needs to be looked over with a very careful eye imagining extraordinarily bad behavior by shared owners before this contract can be called safe. |
||||
|
||||
No sanity checks on the initial constructor's `required` argument are worrisome as well. |
||||
|
||||
# Line by Line Comments |
||||
|
||||
## Lifecycle |
||||
|
||||
### Killable |
||||
|
||||
Very simple, allows owner to call selfdestruct, sending funds to owner. No issues. However, note that `selfdestruct` should typically not be used; it is common that a developer may want to access data in a former contract, and they may not understand that `selfdestruct` limits access to the contract. We recommend better documentation about this dynamic, and an alternate function name for `kill` like `completelyDestroy` while `kill` would perhaps merely send funds to the owner. |
||||
|
||||
Also note that a killable function allows the owner to take funds regardless of other logic. This may be desirable or undesirable depending on the circumstances. Perhaps `Killable` should have a different name as well. |
||||
|
||||
### Migrations |
||||
|
||||
I presume that the goal of this contract is to allow and annotate a migration to a new smart contract address. We are not clear here how this would be accomplished by the code; we'd like to review with the OpenZeppelin team. |
||||
|
||||
### Pausable |
||||
|
||||
We like these pauses! Note that these allow significant griefing potential by owners, and that this might not be obvious to participants in smart contracts using the OpenZeppelin framework. We would recommend that additional sample logic be added to for instance the TokenContract showing safer use of the pause and resume functions. In particular, we would recommend a timelock after which anyone could unpause the contract. |
||||
|
||||
The modifers use the pattern `if(bool){_;}`. This is fine for functions that return false upon failure, but could be problematic for functions expected to throw upon failure. See our comments above on standardizing on `throw` or `return(false)`. |
||||
|
||||
## Ownership |
||||
|
||||
### Ownable |
||||
|
||||
Line 19: Modifier throws if doesn't meet condition, in contrast to some other inheritable modifiers (e.g. in Pausable) that use `if(bool){_;}`. |
||||
|
||||
### Claimable |
||||
|
||||
Inherits from Ownable but the existing owner sets a pendingOwner who has to claim ownership. |
||||
|
||||
Line 17: Another modifier that throws. |
||||
|
||||
### DelayedClaimable |
||||
|
||||
Is there any reason to descend from Ownable directly, instead of just Claimable, which descends from Ownable? If not, descending from both just adds confusion. |
||||
|
||||
### Contactable |
||||
|
||||
Allows owner to set a public string of contract information. No issues. |
||||
|
||||
### Shareable |
||||
|
||||
This needs some work. Doesn't check if `_required <= len(_owners)` for instance, that would be a bummer. What if _required were like `MAX - 1`? |
||||
|
||||
I have a general concern about the difference between `owners`, `_owners`, and `owner` in `Ownable.sol`. I recommend "Owners" be renamed. In general we do not recomment single character differences in variable names, although a preceding underscore is not uncommon in Solidity code. |
||||
|
||||
Line 34: "this contract only has six types of events"...actually only two. |
||||
|
||||
Line 61: Why is `ownerIndex` keyed by addresses hashed to `uint`s? Why not use the addresses directly, so `ownerIndex` is less obscure, and so there's stronger typing? |
||||
|
||||
Line 62: Do not love `++i) ... owners[2+ i]`. Makes me do math, which is not what I want to do. I want to not have to do math. |
||||
|
||||
There should probably be a function for adding a new operation, so the developer doesn't have to work directly with the internal data. (This would make the multisig contract even shorter.) |
||||
|
||||
There's a `revoke` function but not a `propose` function that we can see. |
||||
|
||||
Beware reordering. If `propose` allows the user to choose a bytes string for their proposal, bad things(TM) will happen as currently written. |
||||
|
||||
|
||||
### Multisig |
||||
|
||||
Just an interface. Note it allows changing an owner address, but not changing the number of owners. This is somewhat limiting but also simplifies implementation. |
||||
|
||||
## Payment |
||||
|
||||
### PullPayment |
||||
|
||||
Safe from reentrance attack since ether send is at the end, plus it uses `.send()` rather than `.call.value()`. |
||||
|
||||
There's an argument to be made that `.call.value()` is a better option *if* you're sure that it will be done after all state updates, since `.send` will fail if the recipient has an expensive fallback function. However, in the context of a function meant to be embedded in other contracts, it's probably better to use `.send`. One possible compromise is to add a function which allows only the owner to send ether via `.call.value`. |
||||
|
||||
If you don't use `call.value` you should implement a `cancel` function in case some value is pending here. |
||||
|
||||
Line 14: |
||||
Doesn't use safeAdd. Although it appears that payout amounts can only be increased, in fact the payer could lower the payout as much as desired via overflow. Also, the payer could add a large non-overflowing amount, causing the payment to exceed the contract balance and therefore fail when withdraw is attempted. |
||||
|
||||
Recommendation: track the sum of non-withdrawn asyncSends, and don't allow a new one which exceeds the leftover balance. If it's ever desirable to make payments revocable, it should be done explicitly. |
||||
|
||||
## Tokens |
||||
|
||||
### ERC20 |
||||
|
||||
Standard ERC20 interface only. |
||||
|
||||
There's a security hole in the standard, reported at Edcon: `approve` does not protect against race conditions and simply replaces the current value. An approved spender could wait for the owner to call `approve` again, then attempt to spend the old limit before the new limit is applied. If successful, this attacker could successfully spend the sum of both limits. |
||||
|
||||
This could be fixed by either (1) including the old limit as a parameter, so the update will fail if some gets spent, or (2) using the value parameter as a delta instead of replacement value. |
||||
|
||||
This is not fixable while adhering to the current full ERC20 standard, though it would be possible to add a "secureApprove" function. The impact isn't extreme since at least you can only be attacked by addresses you approved. Also, users could mitigate this by always setting spending limits to zero and checking for spends, before setting the new limit. |
||||
|
||||
Edcon slides: |
||||
https://drive.google.com/file/d/0ByMtMw2hul0EN3NCaVFHSFdxRzA/view |
||||
|
||||
### ERC20Basic |
||||
|
||||
Simpler interface skipping the Approve function. Note this departs from ERC20 in another way: transfer throws instead of returning false. |
||||
|
||||
### BasicToken |
||||
|
||||
Uses `SafeSub` and `SafeMath`, so transfer `throw`s instead of returning false. This complies with ERC20Basic but not the actual ERC20 standard. |
||||
|
||||
### StandardToken |
||||
|
||||
Implementation of full ERC20 token. |
||||
|
||||
Transfer() and transferFrom() use SafeMath functions, which will cause them to throw instead of returning false. Not a security issue but departs from standard. |
||||
|
||||
### SimpleToken |
||||
|
||||
Sample instantiation of StandardToken. Note that in this sample, decimals is 18 and supply only 10,000, so the supply is a small fraction of a single nominal token. |
||||
|
||||
### CrowdsaleToken |
||||
|
||||
StandardToken which mints tokens at a fixed price when sent ether. |
||||
|
||||
There's no provision for owner withdrawing the ether. As a sample for crowdsales it should be Ownable and allow the owner to withdraw ether, rather than stranding the ether in the contract. |
||||
|
||||
Note: an alternative pattern is a mint() function which is only callable from a separate crowdsale contract, so any sort of rules can be added without modifying the token itself. |
||||
|
||||
### VestedToken |
||||
|
||||
Lines 23, 27: |
||||
Functions `transfer()` and `transferFrom()` have a modifier canTransfer which throws if not enough tokens are available. However, transfer() returns a boolean success. Inconsistent treatment of failure conditions may cause problems for other contracts using the token. (Note that transferableTokens() relies on safeSub(), so will also throw if there's insufficient balance.) |
||||
|
||||
Line 64: |
||||
Delete not actually necessary since the value is overwritten in the next line anyway. |
||||
|
||||
## Root level |
||||
|
||||
### Bounty |
||||
|
||||
Avoids potential race condition by having each researcher deploy a separate contract for attack; if a research manages to break his associated contract, other researchers can't immediately claim the reward, they have to reproduce the attack in their own contracts. |
||||
|
||||
A developer could subvert this intent by implementing `deployContract()` to always return the same address. However, this would break the `researchers` mapping, updating the researcher address associated with the contract. This could be prevented by blocking rewrites in `researchers`. |
||||
|
||||
### DayLimit |
||||
|
||||
The modifier `limitedDaily` calls `underLimit`, which both checks that the spend is below the daily limit, and adds the input value to the daily spend. This is fine if all functions throw upon failure. However, not all OpenZeppelin functions do this; there are functions that returns false, and modifiers that wrap the function body in `if (bool) {_;}`. In these cases, `_value` will be added to `spentToday`, but ether may not actually be sent because other preconditions were not met. (However in the OpenZeppelin multisig this is not a problem.) |
||||
|
||||
Lines 4, 11: |
||||
Comment claims that `DayLimit` is multiowned, and Shareable is imported, but DayLimit does not actually inherit from Shareable. The intent may be for child contracts to inherit from Shareable (as Multisig does); in this case the import should be removed and the comment altered. |
||||
|
||||
Line 46: |
||||
Manual overflow check instead of using safeAdd. Since this is called from a function that throws upon failure anyway, there's no real downside to using safeAdd. |
||||
|
||||
### LimitBalance |
||||
|
||||
No issues. |
||||
|
||||
### MultisigWallet |
||||
|
||||
Lines 28, 76, 80: |
||||
`kill`, `setDailyLimit`, and `resetSpentToday` only happen with multisig approval, and hashes for these actions are logged by Shareable. However, they should probably post their own events for easy reading. |
||||
|
||||
Line 45: |
||||
This call to underLimit will reduce the daily limit, and then either throw or return 0. So in this case there's no danger that the limit will be reduced without the operation going through. |
||||
|
||||
Line 65: |
||||
Shareable's onlyManyOwners will take the user's confirmation, and execute the function body if and only if enough users have confirmed. Whole thing throws if the send fails, which will roll back the confirmation. Confirm returns false if not enough have confirmed yet, true if the whole thing succeeds, and throws only in the exceptional circumstance that the designated transaction unexpectedly fails. Elegant design. |
||||
|
||||
Line 68: |
||||
Throw here is good but note this function can fail either by returning false or by throwing. |
||||
|
||||
Line 92: |
||||
A bit odd to split `clearPending()` between this contract and Shareable. However this does allow contracts inheriting from Shareable to use custom structs for pending transactions. |
||||
|
||||
|
||||
### SafeMath |
||||
|
||||
Another interesting comment from the same Edcon presentation was that the overflow behavior of Solidity is undocumented, so in theory, source code that relies on it could break with a future revision. |
||||
|
||||
However, compiled code should be fine, and in the unlikely event that the compiler is revised in this way, there should be plenty of warning. (But this is an argument for keeping overflow checks isolated in SafeMath.) |
||||
|
||||
Aside from that small caveat, these are fine. |
||||
|
@ -0,0 +1,28 @@ |
||||
pragma solidity ^0.4.8; |
||||
|
||||
/// @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; |
||||
|
||||
/// Prevent 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; |
||||
} |
||||
} |
||||
|
||||
} |
@ -0,0 +1,19 @@ |
||||
pragma solidity ^0.4.8; |
||||
|
||||
|
||||
import "../ownership/Ownable.sol"; |
||||
|
||||
|
||||
/* |
||||
* Destructible |
||||
* Base contract that can be destroyed by owner. All funds in contract will be sent to the owner. |
||||
*/ |
||||
contract Destructible is Ownable { |
||||
function destroy() onlyOwner { |
||||
selfdestruct(owner); |
||||
} |
||||
|
||||
function destroyAndSend(address _recipient) onlyOwner { |
||||
selfdestruct(_recipient); |
||||
} |
||||
} |
@ -1,15 +0,0 @@ |
||||
pragma solidity ^0.4.8; |
||||
|
||||
|
||||
import "../ownership/Ownable.sol"; |
||||
|
||||
|
||||
/* |
||||
* Killable |
||||
* Base contract that can be killed by owner. All funds in contract will be sent to the owner. |
||||
*/ |
||||
contract Killable is Ownable { |
||||
function kill() onlyOwner { |
||||
selfdestruct(owner); |
||||
} |
||||
} |
@ -0,0 +1,30 @@ |
||||
pragma solidity ^0.4.8; |
||||
|
||||
|
||||
import "../ownership/Ownable.sol"; |
||||
import "../token/ERC20Basic.sol"; |
||||
|
||||
/// @title TokenDestructible: |
||||
/// @author Remco Bloemen <remco@2π.com> |
||||
///.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 { |
||||
|
||||
/// @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 |
||||
function destroy(address[] tokens) onlyOwner { |
||||
|
||||
// Transfer tokens to owner |
||||
for(uint 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); |
||||
} |
||||
} |
@ -0,0 +1,18 @@ |
||||
pragma solidity ^0.4.8; |
||||
|
||||
import "./Ownable.sol"; |
||||
|
||||
/// @title Contracts that should not own Contracts |
||||
/// @author Remco Bloemen <remco@2π.com> |
||||
/// |
||||
/// 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 { |
||||
|
||||
/// Reclaim ownership of Ownable contracts |
||||
function reclaimContract(address contractAddr) external onlyOwner { |
||||
Ownable contractInst = Ownable(contractAddr); |
||||
contractInst.transferOwnership(owner); |
||||
} |
||||
} |
@ -0,0 +1,42 @@ |
||||
pragma solidity ^0.4.8; |
||||
|
||||
import "./Ownable.sol"; |
||||
|
||||
/// @title Contracts that should not own Ether |
||||
/// @author Remco Bloemen <remco@2π.com> |
||||
/// |
||||
/// This tries to block incoming ether to prevent accidental |
||||
/// loss of Ether. Should Ether end up in the contrat, 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 { |
||||
|
||||
/// Constructor that rejects incoming Ether |
||||
/// @dev The flag `payable` 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; |
||||
} |
||||
} |
||||
|
||||
/// Disallow direct send by settings a default function without `payable` |
||||
function() external { |
||||
} |
||||
|
||||
/// Transfer all Ether owned by the contract to the owner |
||||
/// @dev What if owner is itself a contract marked HasNoEther? |
||||
function reclaimEther() external onlyOwner { |
||||
if(!owner.send(this.balance)) { |
||||
throw; |
||||
} |
||||
} |
||||
} |
@ -0,0 +1,26 @@ |
||||
pragma solidity ^0.4.8; |
||||
|
||||
import "./Ownable.sol"; |
||||
import "../token/ERC20Basic.sol"; |
||||
|
||||
/// @title Contracts that should not own Tokens |
||||
/// @author Remco Bloemen <remco@2π.com> |
||||
/// |
||||
/// 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 { |
||||
|
||||
/// Reject all ERC23 compatible tokens |
||||
function tokenFallback(address from_, uint value_, bytes data_) external { |
||||
throw; |
||||
} |
||||
|
||||
/// Reclaim all ERC20Basic compatible tokens |
||||
function reclaimToken(address tokenAddr) external onlyOwner { |
||||
ERC20Basic tokenInst = ERC20Basic(tokenAddr); |
||||
uint256 balance = tokenInst.balanceOf(this); |
||||
tokenInst.transfer(owner, balance); |
||||
} |
||||
} |
@ -0,0 +1,14 @@ |
||||
pragma solidity ^0.4.8; |
||||
|
||||
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> |
||||
/// |
||||
/// 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 { |
||||
} |
@ -1,18 +1,16 @@ |
||||
pragma solidity ^0.4.8; |
||||
|
||||
|
||||
import './ERC20Basic.sol'; |
||||
|
||||
|
||||
/* |
||||
* ERC20 interface |
||||
* see https://github.com/ethereum/EIPs/issues/20 |
||||
*/ |
||||
contract ERC20 { |
||||
uint public totalSupply; |
||||
function balanceOf(address who) constant returns (uint); |
||||
contract ERC20 is ERC20Basic { |
||||
function allowance(address owner, address spender) constant returns (uint); |
||||
|
||||
function transfer(address to, uint value) returns (bool ok); |
||||
function transferFrom(address from, address to, uint value) returns (bool ok); |
||||
function approve(address spender, uint value) returns (bool ok); |
||||
event Transfer(address indexed from, address indexed to, uint value); |
||||
function transferFrom(address from, address to, uint value); |
||||
function approve(address spender, uint value); |
||||
event Approval(address indexed owner, address indexed spender, uint value); |
||||
} |
||||
|
@ -0,0 +1,43 @@ |
||||
pragma solidity ^0.4.8; |
||||
|
||||
|
||||
import './StandardToken.sol'; |
||||
import '../ownership/Ownable.sol'; |
||||
|
||||
|
||||
|
||||
/** |
||||
* Mintable token |
||||
* |
||||
* Simple ERC20 Token example, with mintable token creation |
||||
* 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, uint value); |
||||
event MintFinished(); |
||||
|
||||
bool public mintingFinished = false; |
||||
uint public totalSupply = 0; |
||||
|
||||
modifier canMint() { |
||||
if(mintingFinished) throw; |
||||
_; |
||||
} |
||||
|
||||
function mint(address _to, uint _amount) onlyOwner canMint returns (bool) { |
||||
totalSupply = totalSupply.add(_amount); |
||||
balances[_to] = balances[_to].add(_amount); |
||||
Mint(_to, _amount); |
||||
return true; |
||||
} |
||||
|
||||
function finishMinting() onlyOwner returns (bool) { |
||||
mintingFinished = true; |
||||
MintFinished(); |
||||
return true; |
||||
} |
||||
} |
@ -0,0 +1,25 @@ |
||||
pragma solidity ^0.4.8; |
||||
|
||||
import './StandardToken.sol'; |
||||
import '../lifecycle/Pausable.sol'; |
||||
|
||||
/** |
||||
* Pausable token |
||||
* |
||||
* Simple ERC20 Token example, with pausable token creation |
||||
* Issue: |
||||
* https://github.com/OpenZeppelin/zeppelin-solidity/issues/194 |
||||
* Based on code by BCAPtoken: |
||||
* https://github.com/BCAPtoken/BCAPToken/blob/5cb5e76338cc47343ba9268663a915337c8b268e/sol/BCAPToken.sol#L27 |
||||
**/ |
||||
|
||||
contract PausableToken is Pausable, StandardToken { |
||||
|
||||
function transfer(address _to, uint _value) whenNotPaused { |
||||
return super.transfer(_to, _value); |
||||
} |
||||
|
||||
function transferFrom(address _from, address _to, uint _value) whenNotPaused { |
||||
return super.transferFrom(_from, _to, _value); |
||||
} |
||||
} |
@ -1,11 +1,16 @@ |
||||
Killable |
||||
Destructible |
||||
============================================= |
||||
|
||||
Base contract that can be killed by owner. |
||||
Base contract that can be destroyed by owner. |
||||
|
||||
Inherits from contract Ownable. |
||||
|
||||
kill( ) onlyOwner |
||||
destroy( ) onlyOwner |
||||
""""""""""""""""""" |
||||
|
||||
Destroys the contract and sends funds back to the owner. |
||||
Destroys the contract and sends funds back to the owner. |
||||
|
||||
destroyAndSend(address _recipient) onlyOwner |
||||
""""""""""""""""""" |
||||
|
||||
Destroys the contract and sends funds back to the _recepient. |
@ -1,26 +1,27 @@ |
||||
Pausable |
||||
============================================= |
||||
|
||||
Base contract that provides an emergency stop mechanism. |
||||
Base contract that provides a pause mechanism. |
||||
|
||||
Inherits from contract Ownable. |
||||
|
||||
emergencyStop( ) external onlyOwner |
||||
pause() onlyOwner whenNotPaused returns (bool) |
||||
""""""""""""""""""""""""""""""""""""" |
||||
|
||||
Triggers the stop mechanism on the contract. After this function is called (by the owner of the contract), any function with modifier stopInEmergency will not run. |
||||
Triggers pause mechanism on the contract. After this function is called (by the owner of the contract), any function with modifier whenNotPaused will not run. |
||||
|
||||
modifier stopInEmergency |
||||
|
||||
modifier whenNotPaused() |
||||
""""""""""""""""""""""""""""""""""""" |
||||
|
||||
Prevents function from running if stop mechanism is activated. |
||||
Prevents function from running if pause mechanism is activated. |
||||
|
||||
modifier onlyInEmergency |
||||
modifier whenPaused() |
||||
""""""""""""""""""""""""""""""""""""" |
||||
|
||||
Only runs if stop mechanism is activated. |
||||
Only runs if pause mechanism is activated. |
||||
|
||||
release( ) external onlyOwner onlyInEmergency |
||||
unpause() onlyOwner whenPaused returns (bool) |
||||
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" |
||||
|
||||
Deactivates the stop mechanism. |
||||
Deactivates the pause mechanism. |
@ -0,0 +1,26 @@ |
||||
'use strict'; |
||||
|
||||
var Destructible = artifacts.require('../contracts/lifecycle/Destructible.sol'); |
||||
require('./helpers/transactionMined.js'); |
||||
|
||||
contract('Destructible', function(accounts) { |
||||
|
||||
it('should send balance to owner after destruction', async function() { |
||||
let destructible = await Destructible.new({from: accounts[0], value: web3.toWei('10','ether')}); |
||||
let owner = await destructible.owner(); |
||||
let initBalance = web3.eth.getBalance(owner); |
||||
await destructible.destroy({from: owner}); |
||||
let newBalance = web3.eth.getBalance(owner); |
||||
assert.isTrue(newBalance > initBalance); |
||||
}); |
||||
|
||||
it('should send balance to recepient after destruction', async function() { |
||||
let destructible = await Destructible.new({from: accounts[0], value: web3.toWei('10','ether')}); |
||||
let owner = await destructible.owner(); |
||||
let initBalance = web3.eth.getBalance(accounts[1]); |
||||
await destructible.destroyAndSend(accounts[1], {from: owner} ); |
||||
let newBalance = web3.eth.getBalance(accounts[1]); |
||||
assert.isTrue(newBalance.greaterThan(initBalance)); |
||||
}); |
||||
|
||||
}); |
@ -0,0 +1,35 @@ |
||||
'use strict'; |
||||
import expectThrow from './helpers/expectThrow'; |
||||
import toPromise from './helpers/toPromise'; |
||||
const Ownable = artifacts.require('../contracts/ownership/Ownable.sol'); |
||||
const HasNoContracts = artifacts.require( |
||||
'../contracts/ownership/HasNoContracts.sol', |
||||
); |
||||
|
||||
contract('HasNoContracts', function(accounts) { |
||||
let hasNoContracts = null; |
||||
let ownable = null; |
||||
|
||||
beforeEach(async () => { |
||||
// Create contract and token
|
||||
hasNoContracts = await HasNoContracts.new(); |
||||
ownable = await Ownable.new(); |
||||
|
||||
// Force ownership into contract
|
||||
await ownable.transferOwnership(hasNoContracts.address); |
||||
const owner = await ownable.owner(); |
||||
assert.equal(owner, hasNoContracts.address); |
||||
}); |
||||
|
||||
it('should allow owner to reclaim contracts', async function() { |
||||
await hasNoContracts.reclaimContract(ownable.address); |
||||
const owner = await ownable.owner(); |
||||
assert.equal(owner, accounts[0]); |
||||
}); |
||||
|
||||
it('should allow only owner to reclaim contracts', async function() { |
||||
await expectThrow( |
||||
hasNoContracts.reclaimContract(ownable.address, {from: accounts[1]}), |
||||
); |
||||
}); |
||||
}); |
@ -0,0 +1,63 @@ |
||||
'use strict'; |
||||
import expectThrow from './helpers/expectThrow'; |
||||
import toPromise from './helpers/toPromise'; |
||||
const HasNoEther = artifacts.require('../contracts/lifecycle/HasNoEther.sol'); |
||||
const HasNoEtherTest = artifacts.require('../helpers/HasNoEtherTest.sol'); |
||||
const ForceEther = artifacts.require('../helpers/ForceEther.sol'); |
||||
|
||||
contract('HasNoEther', function(accounts) { |
||||
const amount = web3.toWei('1', 'ether'); |
||||
|
||||
it('should be constructorable', async function() { |
||||
let hasNoEther = await HasNoEtherTest.new(); |
||||
}); |
||||
|
||||
it('should not accept ether in constructor', async function() { |
||||
await expectThrow(HasNoEtherTest.new({value: amount})); |
||||
}); |
||||
|
||||
it('should not accept ether', async function() { |
||||
let hasNoEther = await HasNoEtherTest.new(); |
||||
|
||||
await expectThrow( |
||||
toPromise(web3.eth.sendTransaction)({ |
||||
from: accounts[1], |
||||
to: hasNoEther.address, |
||||
value: amount, |
||||
}), |
||||
); |
||||
}); |
||||
|
||||
it('should allow owner to reclaim ether', async function() { |
||||
// Create contract
|
||||
let hasNoEther = await HasNoEtherTest.new(); |
||||
const startBalance = await web3.eth.getBalance(hasNoEther.address); |
||||
assert.equal(startBalance, 0); |
||||
|
||||
// Force ether into it
|
||||
await ForceEther.new(hasNoEther.address, {value: amount}); |
||||
const forcedBalance = await web3.eth.getBalance(hasNoEther.address); |
||||
assert.equal(forcedBalance, amount); |
||||
|
||||
// Reclaim
|
||||
const ownerStartBalance = await web3.eth.getBalance(accounts[0]); |
||||
await hasNoEther.reclaimEther(); |
||||
const ownerFinalBalance = await web3.eth.getBalance(accounts[0]); |
||||
const finalBalance = await web3.eth.getBalance(hasNoEther.address); |
||||
assert.equal(finalBalance, 0); |
||||
assert.isAbove(ownerFinalBalance, ownerStartBalance); |
||||
}); |
||||
|
||||
it('should allow only owner to reclaim ether', async function() { |
||||
// Create contract
|
||||
let hasNoEther = await HasNoEtherTest.new({from: accounts[0]}); |
||||
|
||||
// Force ether into it
|
||||
await ForceEther.new(hasNoEther.address, {value: amount}); |
||||
const forcedBalance = await web3.eth.getBalance(hasNoEther.address); |
||||
assert.equal(forcedBalance, amount); |
||||
|
||||
// Reclaim
|
||||
await expectThrow(hasNoEther.reclaimEther({from: accounts[1]})); |
||||
}); |
||||
}); |
@ -0,0 +1,40 @@ |
||||
'use strict'; |
||||
import expectThrow from './helpers/expectThrow'; |
||||
import toPromise from './helpers/toPromise'; |
||||
const HasNoTokens = artifacts.require('../contracts/lifecycle/HasNoTokens.sol'); |
||||
const ERC23TokenMock = artifacts.require('./helpers/ERC23TokenMock.sol'); |
||||
|
||||
contract('HasNoTokens', function(accounts) { |
||||
let hasNoTokens = null; |
||||
let token = null; |
||||
|
||||
beforeEach(async () => { |
||||
// Create contract and token
|
||||
hasNoTokens = await HasNoTokens.new(); |
||||
token = await ERC23TokenMock.new(accounts[0], 100); |
||||
|
||||
// Force token into contract
|
||||
await token.transfer(hasNoTokens.address, 10); |
||||
const startBalance = await token.balanceOf(hasNoTokens.address); |
||||
assert.equal(startBalance, 10); |
||||
}); |
||||
|
||||
it('should not accept ERC23 tokens', async function() { |
||||
await expectThrow(token.transferERC23(hasNoTokens.address, 10, '')); |
||||
}); |
||||
|
||||
it('should allow owner to reclaim tokens', async function() { |
||||
const ownerStartBalance = await token.balanceOf(accounts[0]); |
||||
await hasNoTokens.reclaimToken(token.address); |
||||
const ownerFinalBalance = await token.balanceOf(accounts[0]); |
||||
const finalBalance = await token.balanceOf(hasNoTokens.address); |
||||
assert.equal(finalBalance, 0); |
||||
assert.equal(ownerFinalBalance - ownerStartBalance, 10); |
||||
}); |
||||
|
||||
it('should allow only owner to reclaim tokens', async function() { |
||||
await expectThrow( |
||||
hasNoTokens.reclaimToken(token.address, {from: accounts[1]}), |
||||
); |
||||
}); |
||||
}); |
@ -1,18 +0,0 @@ |
||||
'use strict'; |
||||
|
||||
var Killable = artifacts.require('../contracts/lifecycle/Killable.sol'); |
||||
require('./helpers/transactionMined.js'); |
||||
|
||||
contract('Killable', function(accounts) { |
||||
|
||||
it('should send balance to owner after death', async function() { |
||||
let killable = await Killable.new({from: accounts[0], value: web3.toWei('10','ether')}); |
||||
let owner = await killable.owner(); |
||||
let initBalance = web3.eth.getBalance(owner); |
||||
await killable.kill({from: owner}); |
||||
let newBalance = web3.eth.getBalance(owner); |
||||
|
||||
assert.isTrue(newBalance > initBalance); |
||||
}); |
||||
|
||||
}); |
@ -0,0 +1,35 @@ |
||||
'use strict'; |
||||
|
||||
const assertJump = require('./helpers/assertJump'); |
||||
var MintableToken = artifacts.require('../contracts/Tokens/MintableToken.sol'); |
||||
|
||||
contract('Mintable', function(accounts) { |
||||
let token; |
||||
|
||||
beforeEach(async function() { |
||||
token = await MintableToken.new(); |
||||
}); |
||||
|
||||
it('should start with a totalSupply of 0', async function() { |
||||
let totalSupply = await token.totalSupply(); |
||||
|
||||
assert.equal(totalSupply, 0); |
||||
}); |
||||
|
||||
it('should return mintingFinished false after construction', async function() { |
||||
let mintingFinished = await token.mintingFinished(); |
||||
|
||||
assert.equal(mintingFinished, false); |
||||
}); |
||||
|
||||
it('should mint a given amount of tokens to a given address', async function() { |
||||
await token.mint(accounts[0], 100); |
||||
|
||||
let balance0 = await token.balanceOf(accounts[0]); |
||||
assert(balance0, 100); |
||||
|
||||
let totalSupply = await token.totalSupply(); |
||||
assert(totalSupply, 100); |
||||
}) |
||||
|
||||
}); |
@ -0,0 +1,73 @@ |
||||
'user strict'; |
||||
|
||||
const assertJump = require('./helpers/assertJump'); |
||||
var PausableTokenMock = artifacts.require('./helpers/PausableTokenMock.sol'); |
||||
|
||||
contract('PausableToken', function(accounts) { |
||||
let token; |
||||
|
||||
beforeEach(async function() { |
||||
token = await PausableTokenMock.new(accounts[0], 100); |
||||
}); |
||||
|
||||
it('should return paused false after construction', async function() { |
||||
let paused = await token.paused(); |
||||
|
||||
assert.equal(paused, false); |
||||
}); |
||||
|
||||
it('should return paused true after pause', async function() { |
||||
await token.pause(); |
||||
let paused = await token.paused(); |
||||
|
||||
assert.equal(paused, true); |
||||
}); |
||||
|
||||
it('should return paused false after pause and unpause', async function() { |
||||
await token.pause(); |
||||
await token.unpause(); |
||||
let paused = await token.paused(); |
||||
|
||||
assert.equal(paused, false); |
||||
}); |
||||
|
||||
it('should be able to transfer if transfers are unpaused', async function() { |
||||
await token.transfer(accounts[1], 100); |
||||
let balance0 = await token.balanceOf(accounts[0]); |
||||
assert.equal(balance0, 0); |
||||
|
||||
let balance1 = await token.balanceOf(accounts[1]); |
||||
assert.equal(balance1, 100); |
||||
}); |
||||
|
||||
it('should be able to transfer after transfers are paused and unpaused', async function() { |
||||
await token.pause(); |
||||
await token.unpause(); |
||||
await token.transfer(accounts[1], 100); |
||||
let balance0 = await token.balanceOf(accounts[0]); |
||||
assert.equal(balance0, 0); |
||||
|
||||
let balance1 = await token.balanceOf(accounts[1]); |
||||
assert.equal(balance1, 100); |
||||
}); |
||||
|
||||
it('should throw an error trying to transfer while transactions are paused', async function() { |
||||
await token.pause(); |
||||
try {
|
||||
await token.transfer(accounts[1], 100); |
||||
} catch (error) { |
||||
return assertJump(error); |
||||
} |
||||
assert.fail('should have thrown before'); |
||||
}); |
||||
|
||||
it('should throw an error trying to transfer from another account while transactions are paused', async function() { |
||||
await token.pause(); |
||||
try {
|
||||
await token.transferFrom(accounts[0], accounts[1], 100); |
||||
} catch (error) { |
||||
return assertJump(error); |
||||
} |
||||
assert.fail('should have thrown before'); |
||||
}); |
||||
}) |
@ -0,0 +1,31 @@ |
||||
'use strict'; |
||||
import expectThrow from './helpers/expectThrow'; |
||||
const ReentrancyMock = artifacts.require('./helper/ReentrancyMock.sol'); |
||||
const ReentrancyAttack = artifacts.require('./helper/ReentrancyAttack.sol'); |
||||
|
||||
contract('ReentrancyGuard', function(accounts) { |
||||
let reentrancyMock; |
||||
|
||||
beforeEach(async function() { |
||||
reentrancyMock = await ReentrancyMock.new(); |
||||
let initialCounter = await reentrancyMock.counter(); |
||||
assert.equal(initialCounter, 0); |
||||
}); |
||||
|
||||
it('should not allow remote callback', async function() { |
||||
let attacker = await ReentrancyAttack.new(); |
||||
await expectThrow(reentrancyMock.countAndCall(attacker.address)); |
||||
}); |
||||
|
||||
// The following are more side-effects that intended behaviour:
|
||||
// I put them here as documentation, and to monitor any changes
|
||||
// in the side-effects.
|
||||
|
||||
it('should not allow local recursion', async function() { |
||||
await expectThrow(reentrancyMock.countLocalRecursive(10)); |
||||
}); |
||||
|
||||
it('should not allow indirect local recursion', async function() { |
||||
await expectThrow(reentrancyMock.countThisRecursive(10)); |
||||
}); |
||||
}); |
@ -0,0 +1,32 @@ |
||||
'use strict'; |
||||
|
||||
var TokenDestructible = artifacts.require('../contracts/lifecycle/TokenDestructible.sol'); |
||||
var StandardTokenMock = artifacts.require("./helpers/StandardTokenMock.sol"); |
||||
require('./helpers/transactionMined.js'); |
||||
|
||||
contract('TokenDestructible', function(accounts) { |
||||
|
||||
it('should send balance to owner after destruction', async function() { |
||||
let destructible = await TokenDestructible.new({from: accounts[0], value: web3.toWei('10','ether')}); |
||||
let owner = await destructible.owner(); |
||||
let initBalance = web3.eth.getBalance(owner); |
||||
await destructible.destroy([], {from: owner}); |
||||
let newBalance = web3.eth.getBalance(owner); |
||||
assert.isTrue(newBalance > initBalance); |
||||
}); |
||||
|
||||
it('should send tokens to owner after destruction', async function() { |
||||
let destructible = await TokenDestructible.new({from: accounts[0], value: web3.toWei('10','ether')}); |
||||
let owner = await destructible.owner(); |
||||
let token = await StandardTokenMock.new(destructible.address, 100); |
||||
let initContractBalance = await token.balanceOf(destructible.address); |
||||
let initOwnerBalance = await token.balanceOf(owner); |
||||
assert.equal(initContractBalance, 100); |
||||
assert.equal(initOwnerBalance, 0); |
||||
await destructible.destroy([token.address], {from: owner}); |
||||
let newContractBalance = await token.balanceOf(destructible.address); |
||||
let newOwnerBalance = await token.balanceOf(owner); |
||||
assert.equal(newContractBalance, 0); |
||||
assert.equal(newOwnerBalance, 100); |
||||
}); |
||||
}); |
@ -0,0 +1,33 @@ |
||||
pragma solidity ^0.4.8; |
||||
|
||||
|
||||
import '../../contracts/token/BasicToken.sol'; |
||||
|
||||
|
||||
contract ERC23ContractInterface { |
||||
function tokenFallback(address _from, uint _value, bytes _data) external; |
||||
} |
||||
|
||||
contract ERC23TokenMock is BasicToken { |
||||
|
||||
function ERC23TokenMock(address initialAccount, uint initialBalance) { |
||||
balances[initialAccount] = initialBalance; |
||||
totalSupply = initialBalance; |
||||
} |
||||
|
||||
// ERC23 compatible transfer function (except the name) |
||||
function transferERC23(address _to, uint _value, bytes _data) |
||||
returns (bool success) |
||||
{ |
||||
transfer(_to, _value); |
||||
bool is_contract = false; |
||||
assembly { |
||||
is_contract := not(iszero(extcodesize(_to))) |
||||
} |
||||
if(is_contract) { |
||||
ERC23ContractInterface receiver = ERC23ContractInterface(_to); |
||||
receiver.tokenFallback(msg.sender, _value, _data); |
||||
} |
||||
return true; |
||||
} |
||||
} |
@ -0,0 +1,13 @@ |
||||
pragma solidity ^0.4.8; |
||||
|
||||
// @title Force Ether into a contract. |
||||
// @notice even |
||||
// if the contract is not payable. |
||||
// @notice To use, construct the contract with the target as argument. |
||||
// @author Remco Bloemen <remco@neufund.org> |
||||
contract ForceEther { |
||||
function ForceEther(address target) payable { |
||||
// Selfdestruct transfers all Ether to the arget address |
||||
selfdestruct(target); |
||||
} |
||||
} |
@ -0,0 +1,11 @@ |
||||
pragma solidity ^0.4.8; |
||||
|
||||
import "../../contracts/ownership/HasNoEther.sol"; |
||||
|
||||
contract HasNoEtherTest is HasNoEther { |
||||
|
||||
// Constructor with explicit payable — should still fail |
||||
function HasNoEtherTest() payable { |
||||
} |
||||
|
||||
} |
@ -0,0 +1,12 @@ |
||||
pragma solidity ^0.4.8; |
||||
|
||||
import '../../contracts/token/PausableToken.sol'; |
||||
|
||||
// mock class using PausableToken |
||||
contract PausableTokenMock is PausableToken { |
||||
|
||||
function PausableTokenMock(address initialAccount, uint initialBalance) { |
||||
balances[initialAccount] = initialBalance; |
||||
} |
||||
|
||||
} |
@ -0,0 +1,11 @@ |
||||
pragma solidity ^0.4.8; |
||||
|
||||
contract ReentrancyAttack { |
||||
|
||||
function callSender(bytes4 data) { |
||||
if(!msg.sender.call(data)) { |
||||
throw; |
||||
} |
||||
} |
||||
|
||||
} |
@ -0,0 +1,46 @@ |
||||
pragma solidity ^0.4.8; |
||||
|
||||
import '../../contracts/ReentrancyGuard.sol'; |
||||
import './ReentrancyAttack.sol'; |
||||
|
||||
contract ReentrancyMock is ReentrancyGuard { |
||||
|
||||
uint256 public counter; |
||||
|
||||
function ReentrancyMock() { |
||||
counter = 0; |
||||
} |
||||
|
||||
function count() private { |
||||
counter += 1; |
||||
} |
||||
|
||||
function countLocalRecursive(uint n) public nonReentrant { |
||||
if(n > 0) { |
||||
count(); |
||||
countLocalRecursive(n - 1); |
||||
} |
||||
} |
||||
|
||||
function countThisRecursive(uint256 n) public nonReentrant { |
||||
bytes4 func = bytes4(keccak256("countThisRecursive(uint256)")); |
||||
if(n > 0) { |
||||
count(); |
||||
bool result = this.call(func, n - 1); |
||||
if(result != true) { |
||||
throw; |
||||
} |
||||
} |
||||
} |
||||
|
||||
function countAndCall(ReentrancyAttack attacker) public nonReentrant { |
||||
count(); |
||||
bytes4 func = bytes4(keccak256("callback()")); |
||||
attacker.callSender(func); |
||||
} |
||||
|
||||
function callback() external nonReentrant { |
||||
count(); |
||||
} |
||||
|
||||
} |
@ -0,0 +1,20 @@ |
||||
export default async promise => { |
||||
try { |
||||
await promise; |
||||
} catch (error) { |
||||
// TODO: Check jump destination to destinguish between a throw
|
||||
// and an actual invalid jump.
|
||||
const invalidJump = error.message.search('invalid JUMP') >= 0; |
||||
// TODO: When we contract A calls contract B, and B throws, instead
|
||||
// of an 'invalid jump', we get an 'out of gas' error. How do
|
||||
// we distinguish this from an actual out of gas event? (The
|
||||
// testrpc log actually show an 'invalid jump' event.)
|
||||
const outOfGas = error.message.search('out of gas') >= 0; |
||||
assert( |
||||
invalidJump || outOfGas, |
||||
"Expected throw, got '" + error + "' instead", |
||||
); |
||||
return; |
||||
} |
||||
assert.fail('Expected throw not received'); |
||||
}; |
@ -0,0 +1,4 @@ |
||||
export default func => |
||||
(...args) => |
||||
new Promise((accept, reject) => |
||||
func(...args, (error, data) => error ? reject(error) : accept(data))); |
Loading…
Reference in new issue