Browse Source

Sync with v1.0.0 of zeppelin-solidity

AugustoL 8 years ago
parent
commit
42ccbb2276

+ 12 - 0
.travis.yml

@@ -0,0 +1,12 @@
+dist: trusty
+sudo: false
+group: beta
+language: node_js
+node_js:
+  - "6"
+before_install:
+  - npm i -g ethereumjs-testrpc
+  - npm i -g truffle
+script:
+  - testrpc&
+  - npm test

+ 209 - 45
README.md

@@ -1,4 +1,7 @@
 # Zeppelin Solidity
+[![NPM Package](https://img.shields.io/npm/v/zeppelin-solidity.svg?style=flat-square)](https://www.npmjs.org/package/zeppelin-solidity)
+[![Build Status](https://img.shields.io/travis/OpenZeppelin/zeppelin-solidity.svg?branch=master&style=flat-square)](https://travis-ci.org/OpenZeppelin/zeppelin-solidity)
+
 Zeppelin is a library for writing secure Smart Contracts on Ethereum.
 
 With Zeppelin, you can build distributed applications, protocols and organizations:
@@ -7,9 +10,9 @@ With Zeppelin, you can build distributed applications, protocols and organizatio
 
 ## Getting Started
 
-Zeppelin integrates with [Truffle](https://github.com/ConsenSys/truffle), an Ethereum development environment. Please [install Truffle](https://github.com/ConsenSys/truffle#install) and initialize your project with `truffle init`.
+Zeppelin integrates with [Truffle](https://github.com/ConsenSys/truffle), an Ethereum development environment. Please install Truffle and initialize your project with `truffle init`.
 ```sh
-sudo npm install -g truffle
+npm install -g truffle
 mkdir myproject && cd myproject
 truffle init
 ```
@@ -22,21 +25,188 @@ npm i zeppelin-solidity
 After that, you'll get all the library's contracts in the `contracts/zeppelin` folder. You can use the contracts in the library like so:
 
 ```js
-import "./zeppelin/Rejector.sol";
+import "./zeppelin/Ownable.sol";
 
-contract MetaCoin is Rejector {
+contract MyContract is Ownable {
   ...
 }
 ```
 
 > NOTE: The current distribution channel is npm, which is not ideal. [We're looking into providing a better tool for code distribution](https://github.com/OpenZeppelin/zeppelin-solidity/issues/13), and ideas are welcome.
 
-## Add your own bounty contract
+#### Truffle Beta Support
+We also support Truffle Beta npm integration. If you're using Truffle Beta, the contracts in `node_modules` will be enough, so feel free to delete the copies at your `contracts` folder. If you're using Truffle Beta, you can use Zeppelin contracts like so:
+
+```js
+import "zeppelin-solidity/contracts/Ownable.sol";
+
+contract MyContract is Ownable {
+  ...
+}
+```
+
+For more info see [the Truffle Beta package management tutorial](http://truffleframework.com/tutorials/package-management).
+
+
+## Security
+Zeppelin is meant to provide secure, tested and community-audited code, but please use common sense when doing anything that deals with real money! We take no responsibility for your implementation decisions and any security problem you might experience.
+
+If you find a security issue, please email [security@openzeppelin.org](mailto:security@openzeppelin.org).
+
+## Contracts
+
+### Ownable
+Base contract with an owner.
+
+#### Ownable( )
+Sets the address of the creator of the contract as the owner.
+
+#### modifier onlyOwner( )
+Prevents function from running if it is called by anyone other than the owner.
+
+#### transfer(address newOwner) onlyOwner
+Transfers ownership of the contract to the passed address.
+
+---
+### Stoppable
+Base contract that provides an emergency stop mechanism.
+
+Inherits from contract Ownable.
+
+#### emergencyStop( ) external onlyOwner
+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.
+
+#### modifier stopInEmergency
+Prevents function from running if stop mechanism is activated.
+
+#### modifier onlyInEmergency
+Only runs if stop mechanism is activated.
+
+#### release( ) external onlyOwner onlyInEmergency
+Deactivates the stop mechanism.
+
+---
+### Killable
+Base contract that can be killed by owner.
+
+Inherits from contract Ownable.
+
+#### kill( ) onlyOwner
+Destroys the contract and sends funds back to the owner.
+___
+### Claimable
+Extension for the Ownable contract, where the ownership needs to be claimed
+
+#### transfer(address newOwner) onlyOwner
+Sets the passed address as the pending owner.
+
+#### modifier onlyPendingOwner
+Function only runs if called by pending owner.
+
+#### claimOwnership( ) onlyPendingOwner
+Completes transfer of ownership by setting pending owner as the new owner.
+___
+### Migrations
+Base contract that allows for a new instance of itself to be created at a different address.
+
+Inherits from contract Ownable.
+
+#### upgrade(address new_address) onlyOwner
+Creates a new instance of the contract at the passed address.
+
+#### setCompleted(uint completed) onlyOwner
+Sets the last time that a migration was completed.
+
+___
+### SafeMath
+Provides functions of mathematical operations with safety checks.
+
+#### assert(bool assertion) internal
+Throws an error if the passed result is false. Used in this contract by checking mathematical expressions.
+
+#### safeMul(uint a, uint b) internal returns (uint)
+Multiplies two unisgned integers. Asserts that dividing the product by the non-zero multiplicand results in the multiplier.
+
+#### safeSub(uint a, unit b) internal returns (uint)
+Checks that b is not greater than a before subtracting.
 
-To create a bounty for your contract, inherit from the base Bounty contract and provide an implementation for `deployContract()` returning the new contract address.
+#### safeAdd(unit a, unit b) internal returns (uint)
+Checks that the result is greater than both a and b.
+
+___
+### LimitBalance
+
+Base contract that provides mechanism for limiting the amount of funds a contract can hold.
+
+#### LimitBalance(unit _limit)
+Constructor takes an unisgned integer and sets it as the limit of funds this contract can hold.
+
+#### modifier limitedPayable()
+Throws an error if this contract's balance is already above the limit.
+
+___
+### PullPayment
+Base contract supporting async send for pull payments.
+Inherit from this contract and use asyncSend instead of send.
+
+#### asyncSend(address dest, uint amount) internal
+Adds sent amount to available balance that payee can pull from this contract, called by payer.
+
+#### withdrawPayments( )
+Sends designated balance to payee calling the contract. Throws error if designated balance is 0, if contract does not hold enough funds ot pay the payee, or if the send transaction is not successful.
+
+___
+### StandardToken
+Based on code by FirstBlood: [FirstBloodToken.sol]
+
+Inherits from contract SafeMath. Implementation of abstract contract ERC20 (see https://github.com/ethereum/EIPs/issues/20)
+
+[FirstBloodToken.sol]: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
+
+#### approve(address _spender, uint _value) returns (bool success)
+Sets the amount of the sender's token balance that the passed address is approved to use.
+
+###allowance(address _owner, address _spender) constant returns (uint remaining)
+Returns the approved amount of the owner's balance that the spender can use.
+
+###balanceOf(address _owner) constant returns (uint balance)
+Returns the token balance of the passed address.
+
+###transferFrom(address _from, address _to, uint _value) returns (bool success)
+Transfers tokens from an account that the sender is approved to transfer from. Amount must not be greater than the approved amount or the account's balance.
+
+###function transfer(address _to, uint _value) returns (bool success)
+Transfers tokens from sender's account. Amount must not be greater than sender's balance.
+
+___
+### BasicToken
+Simpler version of StandardToken, with no allowances
+
+#### balanceOf(address _owner) constant returns (uint balance)
+Returns the token balance of the passed address.
+
+###function transfer(address _to, uint _value) returns (bool success)
+Transfers tokens from sender's account. Amount must not be greater than sender's balance.
+
+___
+### CrowdsaleToken
+Simple ERC20 Token example, with crowdsale token creation.
+
+Inherits from contract StandardToken.
+
+#### createTokens(address recipient) payable
+Creates tokens based on message value and credits to the recipient.
+
+#### getPrice() constant returns (uint result)
+Returns the amount of tokens per 1 ether.
+
+
+___
+### Bounty
+To create a bounty for your contract, inherit from the base `Bounty` contract and provide an implementation for `deployContract()` returning the new contract address.
 
 ```
-import "./zeppelin/Bounty.sol";
+import {Bounty, Target} from "./zeppelin/Bounty.sol";
 import "./YourContract.sol";
 
 contract YourBounty is Bounty {
@@ -46,19 +216,21 @@ contract YourBounty is Bounty {
 }
 ```
 
-### Implement invariant logic into your smart contract
+Next, implement invariant logic into your smart contract.
+Your main contract should inherit from the Target class and implement the checkInvariant method. This is a function that should check everything your contract assumes to be true all the time. If this function returns false, it means your contract was broken in some way and is in an inconsistent state. This is what security researchers will try to acomplish when trying to get the bounty.
 
 At contracts/YourContract.sol
 
 ```
-contract YourContract {
+import {Bounty, Target} from "./zeppelin/Bounty.sol";
+contract YourContract is Target {
   function checkInvariant() returns(bool) {
-    // Implement your logic to make sure that none of the state is broken.
+    // Implement your logic to make sure that none of the invariants are broken.
   }
 }
 ```
 
-### Deploy your bounty contract as usual
+Next, deploy your bounty contract along with your main contract to the network.
 
 At `migrations/2_deploy_contracts.js`
 
@@ -69,55 +241,37 @@ module.exports = function(deployer) {
 };
 ```
 
-### Add a reward to the bounty contract
+Next, add a reward to the bounty contract
 
-After deploying the contract, send rewards money into the bounty contract.
+After deploying the contract, send reward funds into the bounty contract.
 
 From `truffle console`
 
 ```
-address = 'your account address'
-reward = 'reward to pay to a researcher'
+bounty = YourBounty.deployed();
+address = 0xb9f68f96cde3b895cc9f6b14b856081b41cb96f1; // your account address
+reward = 5; // reward to pay to a researcher who breaks your contract
 
 web3.eth.sendTransaction({
-  from:address,
-  to:bounty.address,
+  from: address,
+  to: bounty.address,
   value: web3.toWei(reward, "ether")
-}
+})
 
 ```
 
-### Researchers hack the contract and claim their reward.
+If researchers break the contract, they can claim their reward.
 
 For each researcher who wants to hack the contract and claims the reward, refer to our [test](./test/Bounty.js) for the detail.
 
-### Ends the contract
-
-If you manage to protect your contract from security researchers and wants to end the bounty, kill the contract so that all the rewards go back to the owner of the bounty contract.
+Finally, if you manage to protect your contract from security researchers, you can reclaim the bounty funds. To end the bounty, kill the contract so that all the rewards go back to the owner.
 
 ```
-bounty.kill()
+bounty.kill();
 ```
 
-#### Truffle Beta Support
-We also support Truffle Beta npm integration. If you're using Truffle Beta, the contracts in `node_modules` will be enough, so feel free to delete the copies at your `contracts` folder. If you're using Truffle Beta, you can use Zeppelin contracts like so:
 
-```js
-import "zeppelin-solidity/contracts/Rejector.sol";
-
-contract MetaCoin is Rejector {
-  ...
-}
-```
-
-For more info see [the Truffle Beta package management tutorial](http://truffleframework.com/tutorials/package-management).
-
-## Security
-Zeppelin is meant to provide secure, tested and community-audited code, but please use common sense when doing anything that deals with real money! We take no responsibility for your implementation decisions and any security problem you might experience.
-
-If you find a security issue, please email [security@openzeppelin.org](mailto:security@openzeppelin.org).
-
-## Developer Resources
+## More Developer Resources
 
 Building a distributed application, protocol or organization with Zeppelin?
 
@@ -129,11 +283,21 @@ Interested in contributing to Zeppelin?
 - Issue tracker: https://github.com/OpenZeppelin/zeppelin-solidity/issues
 - Contribution guidelines: https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/CONTRIBUTING.md
 
-## Projects using Zeppelin
-- [Blockparty](https://github.com/makoto/blockparty)
+## Collaborating organizations and audits by Zeppelin
+- [Golem](https://golem.network/)
+- [Mediachain](https://golem.network/)
+- [Truffle](http://truffleframework.com/)
+- [Firstblood](http://firstblood.io/)
+- [Rootstock](http://www.rsk.co/)
+- [Consensys](https://consensys.net/)
+- [DigixGlobal](https://www.dgx.io/)
+- [Coinfund](https://coinfund.io/)
+- [DemocracyEarth](http://democracy.earth/)
+- [Signatura](https://signatura.co/)
+- [Ether.camp](http://www.ether.camp/)
+
+among others...
 
-## Contracts
-TODO
 
 ## License
 Code released under the [MIT License](https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/LICENSE).

+ 15 - 7
contracts/Bounty.sol

@@ -1,17 +1,15 @@
 pragma solidity ^0.4.4;
+
+
 import './PullPayment.sol';
 import './Killable.sol';
 
+
 /*
  * Bounty
- * This bounty will pay out to a researcher if he/she breaks invariant logic of
- * the contract you bet reward against.
+ * 
+ * This bounty will pay out to a researcher if they break invariant logic of the contract.
  */
-
-contract Target {
-  function checkInvariant() returns(bool);
-}
-
 contract Bounty is PullPayment, Killable {
   Target target;
   bool public claimed;
@@ -48,3 +46,13 @@ contract Bounty is PullPayment, Killable {
   }
 
 }
+
+/*
+ * Target
+ * 
+ * Your main contract should inherit from this class and implement the checkInvariant method. This is a function that should check everything your contract assumes to be true all the time. If this function returns false, it means your contract was broken in some way and is in an inconsistent state. This is what security researchers will try to acomplish when trying to get the bounty.
+ */
+contract Target {
+  function checkInvariant() returns(bool);
+}
+

+ 6 - 3
contracts/Claimable.sol

@@ -1,11 +1,14 @@
-pragma solidity ^0.4.4;
+pragma solidity ^0.4.0;
+
+
 import './Ownable.sol';
 
+
 /*
  * Claimable
- * Extension for the Ownable contract, where the ownership needs to be claimed
+ *
+ * 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;
 

+ 75 - 0
contracts/DayLimit.sol

@@ -0,0 +1,75 @@
+pragma solidity ^0.4.4;
+
+
+import './Shareable.sol';
+
+
+/*
+ * DayLimit
+ *
+ * inheritable "property" 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. resource that method
+ * uses is specified in the modifier.
+ */
+contract DayLimit is Shareable {
+  // FIELDS
+
+  uint public dailyLimit;
+  uint public spentToday;
+  uint public lastDay;
+
+
+  // MODIFIERS
+
+  // simple modifier for daily limit.
+  modifier limitedDaily(uint _value) {
+    if (underLimit(_value))
+      _;
+  }
+
+
+  // CONSTRUCTOR
+  // stores initial daily limit and records the present day's index.
+  function DayLimit(uint _limit) {
+    dailyLimit = _limit;
+    lastDay = today();
+  }
+
+
+  // METHODS
+
+  // (re)sets the daily limit. needs many of the owners to confirm. doesn't alter the amount already spent today.
+  function setDailyLimit(uint _newLimit) onlymanyowners(sha3(msg.data)) external {
+    dailyLimit = _newLimit;
+  }
+
+  // resets the amount already spent today. needs many of the owners to confirm
+  function resetSpentToday() onlymanyowners(sha3(msg.data)) external {
+    spentToday = 0;
+  }
+
+
+  // INTERNAL METHODS
+
+  // checks to see if there is at least `_value` left from the daily limit today. if there is, subtracts it and
+  // returns true. otherwise just returns false.
+  function underLimit(uint _value) internal onlyOwner 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;
+  }
+
+  // determines today's index.
+  function today() private constant returns (uint) {
+    return now / 1 days;
+  }
+}

+ 6 - 3
contracts/Killable.sol

@@ -1,12 +1,15 @@
 pragma solidity ^0.4.4;
+
+
 import "./Ownable.sol";
 
+
 /*
  * Killable
- * Base contract that can be killed by owner
+ * Base contract that can be killed by owner. All funds in contract will be sent to the owner.
  */
 contract Killable is Ownable {
-  function kill() {
-    if (msg.sender == owner) selfdestruct(owner);
+  function kill() onlyOwner {
+    selfdestruct(owner);
   }
 }

+ 18 - 0
contracts/LimitBalance.sol

@@ -0,0 +1,18 @@
+pragma solidity ^0.4.4;
+contract LimitBalance {
+
+  uint public limit;
+
+  function LimitBalance(uint _limit) {
+    limit = _limit;
+  }
+
+  modifier limitedPayable() { 
+    if (this.balance > limit) {
+      throw;
+    }
+    _;
+    
+  }
+
+}

+ 0 - 12
contracts/LimitFunds.sol

@@ -1,12 +0,0 @@
-pragma solidity ^0.4.4;
-contract LimitFunds {
-
-  uint LIMIT = 5000;
-
-  function() { throw; }
-
-  function deposit() {
-    if (this.balance > LIMIT) throw;
-  }
-
-}

+ 8 - 15
contracts/Migrations.sol

@@ -1,22 +1,15 @@
 pragma solidity ^0.4.4;
-contract Migrations {
-  address public owner;
-  uint public last_completed_migration;
+import './Ownable.sol';
 
-  modifier restricted() {
-    if (msg.sender == owner) _;
-  }
-
-  function Migrations() {
-    owner = msg.sender;
-  }
+contract Migrations is Ownable {
+  uint public lastCompletedMigration;
 
-  function setCompleted(uint completed) restricted {
-    last_completed_migration = completed;
+  function setCompleted(uint completed) onlyOwner {
+    lastCompletedMigration = completed;
   }
 
-  function upgrade(address new_address) restricted {
-    Migrations upgraded = Migrations(new_address);
-    upgraded.setCompleted(last_completed_migration);
+  function upgrade(address newAddress) onlyOwner {
+    Migrations upgraded = Migrations(newAddress);
+    upgraded.setCompleted(lastCompletedMigration);
   }
 }

+ 29 - 0
contracts/Multisig.sol

@@ -0,0 +1,29 @@
+pragma solidity ^0.4.4;
+
+
+/*
+ * Multisig
+ * 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, uint 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, uint 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, uint value, address to, bytes data);
+  // Confirmation still needed for a transaction.
+  event ConfirmationNeeded(bytes32 operation, address initiator, uint value, address to, bytes data);
+
+
+  // FUNCTIONS
+
+  // TODO: document
+  function changeOwner(address _from, address _to) external;
+  function execute(address _to, uint _value, bytes _data) external returns (bytes32);
+  function confirm(bytes32 _h) returns (bool);
+}
+

+ 102 - 0
contracts/MultisigWallet.sol

@@ -0,0 +1,102 @@
+pragma solidity ^0.4.4;
+
+
+import "./Multisig.sol";
+import "./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 {
+  // TYPES
+
+  // Transaction structure to remember details of transaction lest it need be saved for a later call.
+  struct Transaction {
+    address to;
+    uint value;
+    bytes data;
+  }
+
+
+  // CONSTRUCTOR
+
+  // just pass on the owner array to the multiowned and
+  // the limit to daylimit
+  function MultisigWallet(address[] _owners, uint _required, uint _daylimit)
+    Shareable(_owners, _required)
+    DayLimit(_daylimit) { }
+
+
+  // METHODS
+
+  // kills the contract sending everything to `_to`.
+  function kill(address _to) onlymanyowners(sha3(msg.data)) external {
+    suicide(_to);
+  }
+
+  // gets called when no other function matches
+  function() payable {
+    // just being sent some cash?
+    if (msg.value > 0)
+      Deposit(msg.sender, msg.value);
+  }
+
+  // Outside-visible transact entry point. Executes transaction immediately if below daily spend 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.
+  function execute(address _to, uint _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 = sha3(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);
+    }
+  }
+
+  // confirm a transaction through just the hash. we use the previous transactions map, txs, in order
+  // to determine the body of the transaction from the hash provided.
+  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;
+    }
+  }
+
+
+  // INTERNAL METHODS
+
+  function clearPending() internal {
+    uint length = pendingsIndex.length;
+    for (uint i = 0; i < length; ++i) {
+      delete txs[pendingsIndex[i]];
+    }
+    super.clearPending();
+  }
+
+
+  // FIELDS
+
+  // pending transactions we have at present.
+  mapping (bytes32 => Transaction) txs;
+}

+ 5 - 2
contracts/Ownable.sol

@@ -1,8 +1,11 @@
 pragma solidity ^0.4.4;
 
+
 /*
  * Ownable
- * Base contract with an owner
+ *
+ * Base contract with an owner.
+ * Provides onlyOwner modifier, which prevents function from running if it is called by anyone other than the owner.
  */
 contract Ownable {
   address public owner;
@@ -17,7 +20,7 @@ contract Ownable {
   }
 
   function transfer(address newOwner) onlyOwner {
-    owner = newOwner;
+    if (newOwner != address(0)) owner = newOwner;
   }
 
 }

+ 2 - 0
contracts/PullPayment.sol

@@ -1,4 +1,6 @@
 pragma solidity ^0.4.4;
+
+
 /*
  * PullPayment
  * Base contract supporting async send for pull payments.

+ 1 - 0
contracts/SafeMath.sol

@@ -1,5 +1,6 @@
 pragma solidity ^0.4.4;
 
+
 /**
  * Math operations with safety checks
  */

+ 165 - 0
contracts/Shareable.sol

@@ -0,0 +1,165 @@
+pragma solidity ^0.4.4;
+
+
+/*
+ * Shareable
+ *
+ * Based on https://github.com/ethereum/dapp-bin/blob/master/wallet/wallet.sol 
+ *
+ * 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.
+ *
+ * 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 {
+  // TYPES
+
+  // struct for the status of a pending operation.
+  struct PendingState {
+    uint yetNeeded;
+    uint ownersDone;
+    uint index;
+  }
+
+
+  // FIELDS
+
+  // the number of owners that must confirm the same operation before it is run.
+  uint public required;
+
+  // list of owners
+  uint[256] owners;
+  uint constant c_maxOwners = 250;
+  // index on the list of owners to allow reverse lookup
+  mapping(uint => uint) ownerIndex;
+  // the ongoing operations.
+  mapping(bytes32 => PendingState) pendings;
+  bytes32[] pendingsIndex;
+
+
+  // EVENTS
+
+  // 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);
+
+
+  // MODIFIERS
+
+  // simple single-sig function modifier.
+  modifier onlyOwner {
+    if (isOwner(msg.sender))
+      _;
+  }
+
+  // multi-sig function modifier: 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))
+      _;
+  }
+
+
+  // CONSTRUCTOR
+
+  // constructor is given number of sigs required to do protected "onlymanyowners" transactions
+  // as well as the selection of addresses capable of confirming them.
+  function Shareable(address[] _owners, uint _required) {
+    owners[1] = uint(msg.sender);
+    ownerIndex[uint(msg.sender)] = 1;
+    for (uint i = 0; i < _owners.length; ++i) {
+      owners[2 + i] = uint(_owners[i]);
+      ownerIndex[uint(_owners[i])] = 2 + i;
+    }
+    required = _required;
+  }
+
+
+  // METHODS
+
+  // Revokes a prior confirmation of the given operation
+  function revoke(bytes32 _operation) external {
+    uint index = ownerIndex[uint(msg.sender)];
+    // make sure they're an owner
+    if (index == 0) return;
+    uint ownerIndexBit = 2**index;
+    var pending = pendings[_operation];
+    if (pending.ownersDone & ownerIndexBit > 0) {
+      pending.yetNeeded++;
+      pending.ownersDone -= ownerIndexBit;
+      Revoke(msg.sender, _operation);
+    }
+  }
+
+  // Gets an owner by 0-indexed position (using numOwners as the count)
+  function getOwner(uint ownerIndex) external constant returns (address) {
+    return address(owners[ownerIndex + 1]);
+  }
+
+  function isOwner(address _addr) returns (bool) {
+    return ownerIndex[uint(_addr)] > 0;
+  }
+
+  function hasConfirmed(bytes32 _operation, address _owner) constant returns (bool) {
+    var pending = pendings[_operation];
+    uint index = ownerIndex[uint(_owner)];
+
+    // make sure they're an owner
+    if (index == 0) return false;
+
+    // determine the bit to set for this owner.
+    uint ownerIndexBit = 2**index;
+    return !(pending.ownersDone & ownerIndexBit == 0);
+  }
+
+  // INTERNAL METHODS
+
+  function confirmAndCheck(bytes32 _operation) internal returns (bool) {
+    // determine what index the present sender is:
+    uint index = ownerIndex[uint(msg.sender)];
+    // make sure they're an owner
+    if (index == 0) return;
+
+    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.
+    uint 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;
+        }
+    }
+  }
+
+  function clearPending() internal {
+    uint length = pendingsIndex.length;
+    for (uint i = 0; i < length; ++i)
+    if (pendingsIndex[i] != 0)
+      delete pendings[pendingsIndex[i]];
+    delete pendingsIndex;
+  }
+
+}
+

+ 5 - 0
contracts/Stoppable.sol

@@ -1,6 +1,9 @@
 pragma solidity ^0.4.4;
 
+
 import "./Ownable.sol";
+
+
 /*
  * Stoppable
  * Abstract contract that allows children to implement an
@@ -12,10 +15,12 @@ contract Stoppable is Ownable {
   modifier stopInEmergency { if (!stopped) _; }
   modifier onlyInEmergency { if (stopped) _; }
 
+  // called by the owner on emergency, triggers stopped state
   function emergencyStop() external onlyOwner {
     stopped = true;
   }
 
+  // called by the owner on end of emergency, returns to normal state
   function release() external onlyOwner onlyInEmergency {
     stopped = false;
   }

+ 12 - 0
contracts/test-helpers/BasicTokenMock.sol

@@ -0,0 +1,12 @@
+pragma solidity ^0.4.4;
+import '../token/BasicToken.sol';
+
+// mock class using BasicToken
+contract BasicTokenMock is BasicToken {
+
+  function BasicTokenMock(address initialAccount, uint initialBalance) {
+    balances[initialAccount] = initialBalance;
+    totalSupply = initialBalance;
+  }
+
+}

+ 4 - 2
contracts/test-helpers/InsecureTargetBounty.sol

@@ -1,8 +1,10 @@
 pragma solidity ^0.4.4;
 
-import "../Bounty.sol";
 
-contract InsecureTargetMock {
+import {Bounty, Target} from "../Bounty.sol";
+
+
+contract InsecureTargetMock is Target {
   function checkInvariant() returns(bool){
     return false;
   }

+ 10 - 0
contracts/test-helpers/LimitBalanceMock.sol

@@ -0,0 +1,10 @@
+pragma solidity ^0.4.4;
+import '../LimitBalance.sol';
+
+// mock class using LimitBalance
+contract LimitBalanceMock is LimitBalance(1000) {
+
+  function limitedDeposit() payable limitedPayable {
+  }
+
+}

+ 18 - 0
contracts/test-helpers/SafeMathMock.sol

@@ -0,0 +1,18 @@
+pragma solidity ^0.4.4;
+import '../SafeMath.sol';
+
+contract SafeMathMock is SafeMath {
+  uint public result;
+
+  function multiply(uint a, uint b) {
+    result = safeMul(a, b);
+  }
+
+  function subtract(uint a, uint b) {
+    result = safeSub(a, b);
+  }
+
+  function add(uint a, uint b) {
+    result = safeAdd(a, b);
+  }
+}

+ 5 - 3
contracts/test-helpers/SecureTargetBounty.sol

@@ -1,9 +1,11 @@
 pragma solidity ^0.4.4;
 
-import "../Bounty.sol";
 
-contract SecureTargetMock {
-  function checkInvariant() returns(bool){
+import {Bounty, Target} from "../Bounty.sol";
+
+
+contract SecureTargetMock is Target {
+  function checkInvariant() returns(bool) {
     return true;
   }
 }

+ 1 - 1
contracts/test-helpers/StandardTokenMock.sol

@@ -1,5 +1,5 @@
 pragma solidity ^0.4.4;
-import '../StandardToken.sol';
+import '../token/StandardToken.sol';
 
 // mock class using StandardToken
 contract StandardTokenMock is StandardToken {

+ 29 - 0
contracts/token/BasicToken.sol

@@ -0,0 +1,29 @@
+pragma solidity ^0.4.4;
+
+
+import './ERC20Basic.sol';
+import '../SafeMath.sol';
+
+
+/*
+ * Basic token
+ * Basic version of StandardToken, with no allowances
+ */
+contract BasicToken is ERC20Basic, SafeMath {
+
+  mapping(address => uint) balances;
+
+  function transfer(address _to, uint _value) {
+    if (balances[msg.sender] < _value) {
+      throw;
+    } 
+    balances[msg.sender] = safeSub(balances[msg.sender], _value);
+    balances[_to] = safeAdd(balances[_to], _value);
+    Transfer(msg.sender, _to, _value);
+  }
+
+  function balanceOf(address _owner) constant returns (uint balance) {
+    return balances[_owner];
+  }
+  
+}

+ 5 - 1
contracts/token/CrowdsaleToken.sol

@@ -1,8 +1,12 @@
 pragma solidity ^0.4.4;
 
-import "../StandardToken.sol";
+
+import "./StandardToken.sol";
+
 
 /*
+ * CrowdsaleToken
+ *
  * Simple ERC20 Token example, with crowdsale token creation
  */
 contract CrowdsaleToken is StandardToken {

+ 4 - 2
contracts/ERC20.sol → contracts/token/ERC20.sol

@@ -1,8 +1,10 @@
 pragma solidity ^0.4.4;
 
 
-// see https://github.com/ethereum/EIPs/issues/20
-
+/*
+ * ERC20 interface
+ * see https://github.com/ethereum/EIPs/issues/20
+ */
 contract ERC20 {
   uint public totalSupply;
   function balanceOf(address who) constant returns (uint);

+ 14 - 0
contracts/token/ERC20Basic.sol

@@ -0,0 +1,14 @@
+pragma solidity ^0.4.4;
+
+
+/*
+ * ERC20Basic
+ * Simpler version of ERC20 interface
+ * see https://github.com/ethereum/EIPs/issues/20
+ */
+contract ERC20Basic {
+  uint public totalSupply;
+  function balanceOf(address who) constant returns (uint);
+  function transfer(address to, uint value);
+  event Transfer(address indexed from, address indexed to, uint value);
+}

+ 5 - 1
contracts/token/SimpleToken.sol

@@ -1,8 +1,12 @@
 pragma solidity ^0.4.4;
 
-import "../StandardToken.sol";
+
+import "./StandardToken.sol";
+
 
 /*
+ * SimpleToken
+ *
  * 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.

+ 2 - 9
contracts/StandardToken.sol → contracts/token/StandardToken.sol

@@ -1,7 +1,7 @@
 pragma solidity ^0.4.4;
 
 import './ERC20.sol';
-import './SafeMath.sol';
+import '../SafeMath.sol';
 
 /**
  * ERC20 token
@@ -16,9 +16,6 @@ contract StandardToken is ERC20, SafeMath {
   mapping (address => mapping (address => uint)) allowed;
 
   function transfer(address _to, uint _value) returns (bool success) {
-    if (balances[msg.sender] < _value) {
-      throw;
-    } 
     balances[msg.sender] = safeSub(balances[msg.sender], _value);
     balances[_to] = safeAdd(balances[_to], _value);
     Transfer(msg.sender, _to, _value);
@@ -27,11 +24,7 @@ contract StandardToken is ERC20, SafeMath {
 
   function transferFrom(address _from, address _to, uint _value) returns (bool success) {
     var _allowance = allowed[_from][msg.sender];
-    if (balances[_from] < _value ||
-        _allowance < _value) {
-      throw;
-    }
-
+    
     balances[_to] = safeAdd(balances[_to], _value);
     balances[_from] = safeSub(balances[_from], _value);
     allowed[_from][msg.sender] = safeSub(_allowance, _value);

+ 1 - 1
migrations/2_deploy_contracts.js

@@ -4,7 +4,7 @@ module.exports = function(deployer) {
   deployer.deploy(ProofOfExistence);
   deployer.deploy(Ownable);
   deployer.deploy(Claimable);
-  deployer.deploy(LimitFunds);
+  deployer.deploy(LimitBalance);
   if(deployer.network == 'test'){
     deployer.deploy(SecureTargetBounty);
     deployer.deploy(InsecureTargetBounty);

+ 5 - 2
package.json

@@ -1,9 +1,12 @@
 {
   "name": "zeppelin-solidity",
-  "version": "0.0.11",
+  "version": "1.0.0",
   "description": "Secure Smart Contract library for Solidity",
   "main": "truffle.js",
-  "devDependencies": {},
+  "devDependencies": {
+    "ethereumjs-testrpc": "^3.0.2",
+    "truffle": "^2.1.1"
+  },
   "scripts": {
     "test": "truffle test",
     "install": "scripts/install.sh"

+ 49 - 0
test/BasicToken.js

@@ -0,0 +1,49 @@
+contract('BasicToken', function(accounts) {
+
+  it("should return the correct totalSupply after construction", function(done) {
+    return BasicTokenMock.new(accounts[0], 100)
+      .then(function(token) {
+        return token.totalSupply();
+      })
+      .then(function(totalSupply) {
+        assert.equal(totalSupply, 100);
+      })
+      .then(done);
+  })
+
+  it("should return correct balances after transfer", function(done) {
+    var token;
+    return BasicTokenMock.new(accounts[0], 100)
+      .then(function(_token) {
+        token = _token;
+        return token.transfer(accounts[1], 100);
+      })
+      .then(function() {
+        return token.balanceOf(accounts[0]);
+      })
+      .then(function(balance) {
+        assert.equal(balance, 0);
+      })
+      .then(function() {
+        return token.balanceOf(accounts[1]);
+      })
+      .then(function(balance) {
+        assert.equal(balance, 100);
+      })
+      .then(done);
+  });
+
+  it("should throw an error when trying to transfer more than balance", function(done) {
+    var token;
+    return BasicTokenMock.new(accounts[0], 100)
+      .then(function(_token) {
+        token = _token;
+        return token.transfer(accounts[1], 101);
+      })
+      .catch(function(error) {
+        if (error.message.search('invalid JUMP') == -1) throw error
+      })
+      .then(done);
+  });
+
+});

+ 69 - 0
test/Killable.js

@@ -0,0 +1,69 @@
+
+contract('Killable', function(accounts) {
+  //from https://gist.github.com/xavierlepretre/88682e871f4ad07be4534ae560692ee6
+  web3.eth.getTransactionReceiptMined = function (txnHash, interval) {
+    var transactionReceiptAsync;
+    interval = interval ? interval : 500;
+    transactionReceiptAsync = function(txnHash, resolve, reject) {
+        try {
+            var receipt = web3.eth.getTransactionReceipt(txnHash);
+            if (receipt == null) {
+                setTimeout(function () {
+                    transactionReceiptAsync(txnHash, resolve, reject);
+                }, interval);
+            } else {
+                resolve(receipt);
+            }
+        } catch(e) {
+            reject(e);
+        }
+    };
+
+    if (Array.isArray(txnHash)) {
+        var promises = [];
+        txnHash.forEach(function (oneTxHash) {
+            promises.push(web3.eth.getTransactionReceiptMined(oneTxHash, interval));
+        });
+        return Promise.all(promises);
+    } else {
+        return new Promise(function (resolve, reject) {
+                transactionReceiptAsync(txnHash, resolve, reject);
+            });
+    }
+};
+
+  it("should send balance to owner after death", function(done) {
+    var initBalance, newBalance, owner, address, killable, kBalance;
+    web3.eth.sendTransaction({from: web3.eth.coinbase, to: accounts[0], value: web3.toWei('50','ether')}, function(err, result) {
+      if(err)
+        console.log("ERROR:" + err);
+      else {
+        console.log(result);
+      }
+    })
+    return Killable.new({from: accounts[0], value: web3.toWei('10','ether')})
+      .then(function(_killable) {
+        killable = _killable;
+        return killable.owner();
+      })
+      .then(function(_owner) {
+        owner = _owner;
+        initBalance = web3.eth.getBalance(owner);
+        kBalance = web3.eth.getBalance(killable.address);
+      })
+      .then(function() {
+        return killable.kill({from: owner});
+      })
+      .then(function (txnHash) {
+        return web3.eth.getTransactionReceiptMined(txnHash);
+      })
+      .then(function() {
+        newBalance = web3.eth.getBalance(owner);
+      })
+      .then(function() {
+        assert.isTrue(newBalance > initBalance);
+      })
+      .then(done);
+  });
+
+});

+ 64 - 0
test/LimitBalance.js

@@ -0,0 +1,64 @@
+contract('LimitBalance', function(accounts) {
+  var lb;
+
+  beforeEach(function() {
+    return LimitBalanceMock.new().then(function(deployed) {
+      lb = deployed;
+    });
+  });
+
+  var LIMIT = 1000;
+
+  it("should expose limit", function(done) {
+    return lb.limit()
+      .then(function(limit) { 
+        assert.equal(limit, LIMIT);
+      })
+      .then(done)
+  });
+
+  it("should allow sending below limit", function(done) {
+    var amount = 1;
+    return lb.limitedDeposit({value: amount})
+      .then(function() { 
+        assert.equal(web3.eth.getBalance(lb.address), amount);
+      })
+      .then(done)
+  });
+
+  it("shouldnt allow sending above limit", function(done) {
+    var amount = 1100;
+    return lb.limitedDeposit({value: amount})
+      .catch(function(error) {
+        if (error.message.search('invalid JUMP') == -1) throw error
+      })
+      .then(done)
+  });
+
+  it("should allow multiple sends below limit", function(done) {
+    var amount = 500;
+    return lb.limitedDeposit({value: amount})
+      .then(function() { 
+        assert.equal(web3.eth.getBalance(lb.address), amount);
+        return lb.limitedDeposit({value: amount})
+      })
+      .then(function() { 
+        assert.equal(web3.eth.getBalance(lb.address), amount*2);
+      })
+      .then(done)
+  });
+
+  it("shouldnt allow multiple sends above limit", function(done) {
+    var amount = 500;
+    return lb.limitedDeposit({value: amount})
+      .then(function() { 
+        assert.equal(web3.eth.getBalance(lb.address), amount);
+        return lb.limitedDeposit({value: amount+1})
+      })
+      .catch(function(error) {
+        if (error.message.search('invalid JUMP') == -1) throw error;
+      })
+      .then(done)
+  });
+
+});

+ 16 - 0
test/Ownable.js

@@ -39,4 +39,20 @@ contract('Ownable', function(accounts) {
       .then(done)
   });
 
+  it("should guard ownership against stuck state" ,function(done) {
+    var ownable = Ownable.deployed();
+
+    return ownable.owner()
+      .then(function (originalOwner) {
+        return ownable.transfer(null, {from: originalOwner})
+          .then(function() {
+            return ownable.owner();
+          })
+          .then(function(newOwner) {
+            assert.equal(originalOwner, newOwner);
+          })
+          .then(done);
+      });
+  });
+
 });

+ 82 - 0
test/SafeMath.js

@@ -0,0 +1,82 @@
+
+contract('SafeMath', function(accounts) {
+
+  var safeMath;
+
+  before(function() {
+    return SafeMathMock.new()
+      .then(function(_safeMath) {
+        safeMath = _safeMath;
+      });
+  });
+
+  it("multiplies correctly", function(done) {
+    var a = 5678;
+    var b = 1234;
+    return safeMath.multiply(a, b)
+      .then(function() {
+        return safeMath.result();
+      })
+      .then(function(result) {
+        assert.equal(result, a*b);
+      })
+      .then(done);
+  });
+
+  it("adds correctly", function(done) {
+    var a = 5678;
+    var b = 1234;
+    return safeMath.add(a, b)
+      .then(function() {
+        return safeMath.result();
+      })
+      .then(function(result) {
+        assert.equal(result, a+b);
+      })
+      .then(done);
+  });
+
+  it("subtracts correctly", function(done) {
+    var a = 5678;
+    var b = 1234;
+    return safeMath.subtract(a, b)
+      .then(function() {
+        return safeMath.result();
+      })
+      .then(function(result) {
+        assert.equal(result, a-b);
+      })
+      .then(done);
+  });
+
+  it("should throw an error if subtraction result would be negative", function (done) {
+    var a = 1234;
+    var b = 5678;
+    return safeMath.subtract(a, b)
+      .catch(function(error) {
+        if (error.message.search('invalid JUMP') == -1) throw error
+      })
+      .then(done);
+  });
+
+  it("should throw an error on addition overflow", function(done) {
+    var a = 115792089237316195423570985008687907853269984665640564039457584007913129639935;
+    var b = 1;
+    return safeMath.add(a, b)
+      .catch(function(error) {
+        if (error.message.search('invalid JUMP') == -1) throw error
+      })
+      .then(done);
+  });
+
+  it("should throw an error on multiplication overflow", function(done) {
+    var a = 115792089237316195423570985008687907853269984665640564039457584007913129639933;
+    var b = 2;
+    return safeMath.multiply(a, b)
+      .catch(function(error) {
+        if (error.message.search('invalid JUMP') == -1) throw error
+      })
+      .then(done);
+  });
+
+});

+ 0 - 25
test/TestOwnable.sol

@@ -1,25 +0,0 @@
-pragma solidity ^0.4.4;
-import "truffle/Assert.sol";
-import "truffle/DeployedAddresses.sol";
-import "../contracts/Ownable.sol";
-
-contract TestOwnable {
-  Ownable ownable = new Ownable();
-
-  function testHasOwner() {
-    Assert.isNotZero(ownable.owner(), "Ownable should have an owner upon creation.");
-  }
-
-  function testChangesOwner() {
-    address originalOwner = ownable.owner();
-    ownable.transfer(0x0);
-    Assert.notEqual(originalOwner, ownable.owner(), "Ownable should change owners after transfer.");
-  }
-
-  function testOnlyOwnerCanChangeOwner() {
-    Ownable deployedOwnable = Ownable(DeployedAddresses.Ownable());
-    address originalOwner = deployedOwnable.owner();
-    deployedOwnable.transfer(0x0);
-    Assert.equal(originalOwner, deployedOwnable.owner(), "Ownable should prevent non-owners from transfering");
-  }
-}

+ 0 - 10
truffle.js

@@ -1,14 +1,4 @@
 module.exports = {
-  build: {
-    "index.html": "index.html",
-    "app.js": [
-      "javascripts/app.js"
-    ],
-    "app.css": [
-      "stylesheets/app.css"
-    ],
-    "images/": "images/"
-  },
   rpc: {
     host: "localhost",
     port: 8545