Reworked caught cheating method

Reworked caught cheating method

Now there's an incentive for the one who's caught cheating to still
keep it off the blockchain

import "Rules.sol";
import "TicTacToeAdjudicator.sol";

/* Board state values are as follows:
 *  0 | 1 | 2
 *  ---------
 *  3 | 4 | 5
 *  ---------
 *  6 | 7 | 8
 *
 * 9: 4 if last player was O, 1 if the last player was X
 */
contract TicTacToeRules is Rules {

    uint constant BLANK = 0;
    uint constant X = 1;
    uint constant O = 4;

    address addressX;
    address addressO;
    uint timeout;

    /**
     * Creates a new TicTacToeRules
     * _addressX: the address of X
     * _addressO: the address of O
     * _timeout: the timeout before state can be closed
     */
    function TicTacToeRules(address _addressX, address _addressO, uint _timeout) {
        addressX = _addressX;
        addressO = _addressO;
        timeout = _timeout;
    }

    function createAdjudicator() internal returns (Adjudicator newAdjudicator) {
        newAdjudicator = new TicTacToeAdjudicator(addressX, addressO, timeout);
        delete timeout;
    }

    // Converts a grid coordinate to an index value
    function gridToIndex(uint x, uint y) constant internal returns (uint) {
        return x + 3*y;
    }

    /**
     * Send a state directly to the underlying state channel.
     * Allows for transactions to be closed without any adjudication fees.
     *
     * state: the state that will be sent
     * nonce: the nonce that will be sent
     * the rest are signature values for X and O, respectively
     * returns: true if state sent sucessfully, otherwise false
     */
    function sendState(
        bytes state,
        uint nonce,
        uint8 vX,
        bytes32 rX,
        bytes32 sX,
        uint8 vO,
        bytes32 rO,
        bytes32 sO
    ) external returns (bool) {
        uint8[] memory v = new uint8[](2);
        bytes32[] memory r = new bytes32[](2);
        bytes32[] memory s = new bytes32[](2);

        v[0] = vX;
        v[1] = vO;
        r[0] = rX;
        r[1] = rO;
        s[0] = sX;
        s[1] = sO;

        return adjudicator.close(2, state, nonce, this, v, r, s);
    }

    /**
     * Sends a unilateral ruling (0 signatures required) to underlying adjudicator.
     *
     * uintState: the state which will be sent
     * nonce: the nonce which will be sent
     * returns: true if the state was sent successfully, otherwise false
     */
    function unilateralRuling(uint8 uintState, uint nonce) internal returns (bool) {
        bytes memory state = new bytes(1);
        state[0] = byte(uintState);
        adjudicator.close(0, state, nonce, this, new uint8[](1), new bytes32[](1), new bytes32[](1));
    }

    /**
     * Sends a board to be adjudicated upon.
     *
     * board: the board to be adjudicated upon
     * nonce: the nonce that will be used
     * v, r, s: X's signature if last player was X, O's signature if last player was O
     * returns: true if adjudication was sucessful, otherwise false
     */
    function sendBoard(
        bytes10 board,
        uint nonce,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external returns (bool) {
        uint x;
        uint y;
        uint i;
        uint8 uintState = uint(board[9]) == X ? 0x28 : 0x14;// by default, the person who didn't play will lose all deposits

        if (
            !((uint(board[9]) == X && addressX == ecrecover(sha3(board, nonce, this), v, r, s))
            || (uint(board[9]) == O && addressO == ecrecover(sha3(board, nonce, this), v, r, s)))
        ) {
            return false;
        }

        // do something about what happens if you send old boards???

        // checking wins
        // checking |
        for (x = 0; x < 3; x++) {
            i = 0;
            for (y = 0; y < 3; y++) {
                i += uint(board[gridToIndex(x, y)]);
            }
            if (i == X * 3) {
                return unilateralRuling(uintState | 0x01 , nonce);// give X the bet winnings
            } else if (i == O * 3) {
                return unilateralRuling(uintState | 0x02, nonce);// give O the bet winnings
            }
        }

        // checking -
        for (y = 0; y < 3; y++) {
            i = 0;
            for (x = 0; x < 3; x++) {
                i += uint(board[gridToIndex(x, y)]);
            }
            if (i == X * 3) {
                return unilateralRuling(uintState | 0x01, nonce);
            } else if (i == O * 3) {
                return unilateralRuling(uintState | 0x02, nonce);
            }
        }

        // checking \
        i = 0;
        for (x = 0; x < 3; x++) {
            i += uint(board[gridToIndex(x, x)]);
        }
        if (i == X * 3) {
            return unilateralRuling(uintState | 0x01, nonce);
        } else if (i == O * 3) {
            return unilateralRuling(uintState | 0x02, nonce);
        }

        // checking /
        i = 0;
        for (x = 0; x < 3; x++) {
            i += uint(board[gridToIndex(x, 2 - x)]);
        }
        if (i == X * 3) {
            return unilateralRuling(uintState | 0x01, nonce);
        } else if (i == O * 3) {
            return unilateralRuling(uintState | 0x02, nonce);
        }

        // check if tie
        for (i = 0; i < 9; i++) {
            if (uint(board[i]) == BLANK) {
                // last player wins
                return unilateralRuling(uintState | uint(board[9]) == X ? 0x01 : 0x02, nonce);// bets sent to last player
            }
        }
        // it is a tie
        return unilateralRuling(uintState, nonce);// if tie, bets returned
    }

    /**
     * Punishes a sender for sending an errornous board.
     *
     * oldBoard: the old board to be compared against
     * oldNonce: the old nonce to verify the old board
     * oldV, oldR, oldS: the signature for oldBoard, from the last player
     * newBoard: the new board which has an error
     * newNonce: the new nonce of newBoard
     * newV, newR, newS: the signatures for newBoard, from the last player
     */
    function badBoardSent(
        bytes10 oldBoard,
        uint oldNonce,
        uint8 oldV,
        bytes32 oldR,
        bytes32 oldS,
        bytes10 newBoard,
        uint newNonce,
        uint8 newV,
        bytes32 newR,
        bytes32 newS
    ) external returns (bool) {
        // verify the integrity of oldBoard
        if (
            !((uint(oldBoard[9]) == X && addressX == ecrecover(sha3(oldBoard, oldNonce, this), oldV, oldR, oldS))
            || (uint(oldBoard[9]) == O && addressO == ecrecover(sha3(oldBoard, oldNonce, this), oldV, oldR, oldS)))
        ) {
            return false;
        }

        // verify the integrity of newBoard
        if (
            !((uint(newBoard[9]) == X && addressX == ecrecover(sha3(newBoard, newNonce, this), newV, newR, newS))
            || (uint(newBoard[9]) == O && addressO == ecrecover(sha3(newBoard, newNonce, this), newV, newR, newS)))
        ) {
            return false;
        }

        bool notChanged = true;
        for (uint i = 0; i < 9; i++) {
            if (oldBoard[i] == newBoard[i]) {
                break;
            }
            if ((uint(newBoard[i]) == X || uint(newBoard[i]) == O) && (uint(oldBoard[i]) == BLANK) && notChanged && (newBoard[i] == newBoard[9])) {
                notChanged = false;
                break;
            }
            // shenanigans
            return unilateralRuling(uint(newBoard[9]) == X ? 0x5E : 0x6D, newNonce);
        }
        if (notChanged) {
            // shenanigans
            return unilateralRuling(uint(newBoard[9]) == X ? 0x5E : 0x6D, newNonce);
        } else {
            // nothing fishy
            return false;
        }
    }

    /**
     * Lets the contract know that you have not disconnected.
     * Will modify the state such that the disconnect deposits will be
     * refunded and both party's adjudication deposits will be lost.
     *
     * returns: true if sucessful, otherwise false
     */
    function checkIn() external returns (bool) {
        uint8 uintState = uint8(adjudicator.getStateAt(0));
        if (uintState & 0x40 != 0x00 || uintState & 0x0C != 0x00) {
            return false;
        }
        return unilateralRuling(uintState & 0xCF | 0x0C, adjudicator.getNonce());
    }
}

import "Rules.sol";
import "TicTacToeAdjudicator.sol";

/* Board state values are as follows:
 *  0 | 1 | 2
 *  ---------
 *  3 | 4 | 5
 *  ---------
 *  6 | 7 | 8
 *
 * 9: 4 if last player was O, 1 if the last player was X
 */
contract TicTacToeRules is Rules {

    uint constant BLANK = 0;
    uint constant X = 1;
    uint constant O = 4;

    address addressX;
    address addressO;
    uint timeout;

    /**
     * Creates a new TicTacToeRules
     * _addressX: the address of X
     * _addressO: the address of O
     * _timeout: the timeout before state can be closed
     */
    function TicTacToeRules(address _addressX, address _addressO, uint _timeout) {
        addressX = _addressX;
        addressO = _addressO;
        timeout = _timeout;
    }

    function createAdjudicator() internal returns (Adjudicator newAdjudicator) {
        newAdjudicator = new TicTacToeAdjudicator(addressX, addressO, timeout);
        delete timeout;
    }

    // Converts a grid coordinate to an index value
    function gridToIndex(uint x, uint y) constant internal returns (uint) {
        return x + 3*y;
    }

    /**
     * Send a state directly to the underlying state channel.
     * Allows for transactions to be closed without any adjudication fees.
     *
     * state: the state that will be sent
     * nonce: the nonce that will be sent
     * the rest are signature values for X and O, respectively
     * returns: true if state sent sucessfully, otherwise false
     */
    function sendState(
        bytes state,
        uint nonce,
        uint8 vX,
        bytes32 rX,
        bytes32 sX,
        uint8 vO,
        bytes32 rO,
        bytes32 sO
    ) external returns (bool) {
        uint8[] memory v = new uint8[](2);
        bytes32[] memory r = new bytes32[](2);
        bytes32[] memory s = new bytes32[](2);

        v[0] = vX;
        v[1] = vO;
        r[0] = rX;
        r[1] = rO;
        s[0] = sX;
        s[1] = sO;

        return adjudicator.close(2, state, nonce, this, v, r, s);
    }

    /**
     * Sends a unilateral ruling (0 signatures required) to underlying adjudicator.
     *
     * uintState: the state which will be sent
     * nonce: the nonce which will be sent
     * returns: true if the state was sent successfully, otherwise false
     */
    function unilateralRuling(uint8 uintState, uint nonce) internal returns (bool) {
        bytes memory state = new bytes(1);
        state[0] = byte(uintState);
        adjudicator.close(0, state, nonce, this, new uint8[](1), new bytes32[](1), new bytes32[](1));
    }

    /**
     * Sends a board to be adjudicated upon.
     *
     * board: the board to be adjudicated upon
     * nonce: the nonce that will be used
     * v, r, s: X's signature if last player was X, O's signature if last player was O
     * returns: true if adjudication was sucessful, otherwise false
     */
    function sendBoard(
        bytes10 board,
        uint nonce,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external returns (bool) {
        uint x;
        uint y;
        uint i;
        uint8 uintState = uint(board[9]) == X ? 0x28 : 0x14;// by default, the person who didn't play will lose all deposits

        if (
            !((uint(board[9]) == X && addressX == ecrecover(sha3(board, nonce, this), v, r, s))
            || (uint(board[9]) == O && addressO == ecrecover(sha3(board, nonce, this), v, r, s)))
        ) {
            return false;
        }

        // do something about what happens if you send old boards???

        // checking wins
        // checking |
        for (x = 0; x < 3; x++) {
            i = 0;
            for (y = 0; y < 3; y++) {
                i += uint(board[gridToIndex(x, y)]);
            }
            if (i == X * 3) {
                return unilateralRuling(uintState | 0x01 , nonce);// give X the bet winnings
            } else if (i == O * 3) {
                return unilateralRuling(uintState | 0x02, nonce);// give O the bet winnings
            }
        }

        // checking -
        for (y = 0; y < 3; y++) {
            i = 0;
            for (x = 0; x < 3; x++) {
                i += uint(board[gridToIndex(x, y)]);
            }
            if (i == X * 3) {
                return unilateralRuling(uintState | 0x01, nonce);
            } else if (i == O * 3) {
                return unilateralRuling(uintState | 0x02, nonce);
            }
        }

        // checking \
        i = 0;
        for (x = 0; x < 3; x++) {
            i += uint(board[gridToIndex(x, x)]);
        }
        if (i == X * 3) {
            return unilateralRuling(uintState | 0x01, nonce);
        } else if (i == O * 3) {
            return unilateralRuling(uintState | 0x02, nonce);
        }

        // checking /
        i = 0;
        for (x = 0; x < 3; x++) {
            i += uint(board[gridToIndex(x, 2 - x)]);
        }
        if (i == X * 3) {
            return unilateralRuling(uintState | 0x01, nonce);
        } else if (i == O * 3) {
            return unilateralRuling(uintState | 0x02, nonce);
        }

        // check if tie
        for (i = 0; i < 9; i++) {
            if (uint(board[i]) == BLANK) {
                // last player wins
                return unilateralRuling(uintState | uint(board[9]) == X ? 0x01 : 0x02, nonce);// bets sent to last player
            }
        }
        // it is a tie
        return unilateralRuling(uintState, nonce);// if tie, bets returned
    }

    /**
     * Punishes a sender for sending an errornous board.
     *
     * oldBoard: the old board to be compared against
     * oldNonce: the old nonce to verify the old board
     * oldV, oldR, oldS: the signature for oldBoard, from the last player
     * newBoard: the new board which has an error
     * newNonce: the new nonce of newBoard
     * newV, newR, newS: the signatures for newBoard, from the last player
     */
    function badBoardSent(
        bytes10 oldBoard,
        uint oldNonce,
        uint8 oldV,
        bytes32 oldR,
        bytes32 oldS,
        bytes10 newBoard,
        uint newNonce,
        uint8 newV,
        bytes32 newR,
        bytes32 newS
    ) external returns (bool) {
        // verify the integrity of oldBoard
        if (
            !((uint(oldBoard[9]) == X && addressX == ecrecover(sha3(oldBoard, oldNonce, this), oldV, oldR, oldS))
            || (uint(oldBoard[9]) == O && addressO == ecrecover(sha3(oldBoard, oldNonce, this), oldV, oldR, oldS)))
        ) {
            return false;
        }

        // verify the integrity of newBoard
        if (
            !((uint(newBoard[9]) == X && addressX == ecrecover(sha3(newBoard, newNonce, this), newV, newR, newS))
            || (uint(newBoard[9]) == O && addressO == ecrecover(sha3(newBoard, newNonce, this), newV, newR, newS)))
        ) {
            return false;
        }

        bool notChanged = true;
        for (uint i = 0; i < 9; i++) {
            if (oldBoard[i] == newBoard[i]) {
                break;
            }
            if ((uint(newBoard[i]) == X || uint(newBoard[i]) == O) && (uint(oldBoard[i]) == BLANK) && notChanged && (newBoard[i] == newBoard[9])) {
                notChanged = false;
                break;
            }
            // shenanigans
            return unilateralRuling(uint(newBoard[9]) == X ? 0x56 : 0x69, newNonce);
        }
        if (notChanged) {
            // shenanigans
            return unilateralRuling(uint(newBoard[9]) == X ? 0x56 : 0x69, newNonce);
        } else {
            // nothing fishy
            return false;
        }
    }

    /**
     * Lets the contract know that you have not disconnected.
     * Will modify the state such that the disconnect deposits will be
     * refunded and both party's adjudication deposits will be lost.
     *
     * returns: true if sucessful, otherwise false
     */
    function checkIn() external returns (bool) {
        uint8 uintState = uint8(adjudicator.getStateAt(0));
        if (uintState & 0x40 != 0x00 || uintState & 0x0C != 0x00) {
            return false;
        }
        return unilateralRuling(uintState & 0xCF | 0x0C, adjudicator.getNonce());
    }
}


IBondingManager: pendingBlockRewardCut -> pendingRewardCut

pragma solidity ^0.4.17;

/*
 * @title Interface for BondingManager
 * TODO: switch to interface type
 */
contract IBondingManager {
    event TranscoderUpdate(address indexed transcoder, uint256 pendingRewardCut, uint256 pendingFeeShare, uint256 pendingPricePerSegment);
    event TranscoderEvicted(address indexed transcoder);
    event TranscoderResigned(address indexed transcoder);
    event TranscoderSlashed(address indexed transcoder, address finder, uint256 penalty, uint256 finderReward);
    event Reward(address indexed transcoder, uint256 amount);
    event Bond(address indexed delegate, address indexed delegator);
    event Unbond(address indexed delegate, address indexed delegator);
    event WithdrawStake(address indexed delegator);
    event WithdrawFees(address indexed delegator);

    // External functions
    function setActiveTranscoders() external;
    function updateTranscoderWithFees(address _transcoder, uint256 _fees, uint256 _round) external;
    function slashTranscoder(address _transcoder, address _finder, uint256 _slashAmount, uint256 _finderFee) external;
    function electActiveTranscoder(uint256 _maxPricePerSegment, bytes32 _blockHash, uint256 _round) external view returns (address);

    // Public functions
    function transcoderTotalStake(address _transcoder) public view returns (uint256);
    function activeTranscoderTotalStake(address _transcoder, uint256 _round) public view returns (uint256);
    function isRegisteredTranscoder(address _transcoder) public view returns (bool);
    function getTotalBonded() public view returns (uint256);
}

pragma solidity ^0.4.17;

/*
 * @title Interface for BondingManager
 * TODO: switch to interface type
 */
contract IBondingManager {
    event TranscoderUpdate(address indexed transcoder, uint256 pendingBlockRewardCut, uint256 pendingFeeShare, uint256 pendingPricePerSegment);
    event TranscoderEvicted(address indexed transcoder);
    event TranscoderResigned(address indexed transcoder);
    event TranscoderSlashed(address indexed transcoder, address finder, uint256 penalty, uint256 finderReward);
    event Reward(address indexed transcoder, uint256 amount);
    event Bond(address indexed delegate, address indexed delegator);
    event Unbond(address indexed delegate, address indexed delegator);
    event WithdrawStake(address indexed delegator);
    event WithdrawFees(address indexed delegator);

    // External functions
    function setActiveTranscoders() external;
    function updateTranscoderWithFees(address _transcoder, uint256 _fees, uint256 _round) external;
    function slashTranscoder(address _transcoder, address _finder, uint256 _slashAmount, uint256 _finderFee) external;
    function electActiveTranscoder(uint256 _maxPricePerSegment, bytes32 _blockHash, uint256 _round) external view returns (address);

    // Public functions
    function transcoderTotalStake(address _transcoder) public view returns (uint256);
    function activeTranscoderTotalStake(address _transcoder, uint256 _round) public view returns (uint256);
    function isRegisteredTranscoder(address _transcoder) public view returns (bool);
    function getTotalBonded() public view returns (uint256);
}


Fix EnumerableSetMock for 2.5.rc1 (#2069)

* Drafted Enumerable.sol.

* Drafted test framework.

* Tweaked the tests to follow oz structure.

* Coded EnumerableSet.

* Moved EnumerableSet to `utils`.

* Fixed linting.

* Improved comments.

* Tweaked contract description.

* Renamed struct to AddressSet.

* Relaxed version pragma to 0.5.0

* Removed events.

* Revert on useless operations.

* Small comment.

* Created AddressSet factory method.

* Failed transactions return false.

* Transactions now return false on failure.

* Remove comments from mock

* Rename mock functions

* Adapt tests to code style, use test-helpers

* Fix bug in remove, improve tests.

* Add changelog entry

* Add entry on Utils doc

* Add optimization for removal of last slot

* Update docs

* Fix headings of utilities documentation

* Simplified mock.

* Fixed comment.

* Revert "Fixed comment."

This reverts commit 39627f9a6f90d48be20ca1449fe03e1699b48173.

* Revert "Simplified mock."

This reverts commit 67468e464b038736251f18e1dc2e368c9091a87a.

* Simplified mock.

Co-authored-by: Nicolás Venturo <0078fd35ad62344ea7bbfaf1f53ddeb19569ffff@gmail.com>
(cherry picked from commit 8975289c6b85caeedae815ebada00c6236a4ecce)

pragma solidity ^0.5.0;

import "../utils/EnumerableSet.sol";

contract EnumerableSetMock{
    using EnumerableSet for EnumerableSet.AddressSet;

    event TransactionResult(bool result);

    EnumerableSet.AddressSet private set;

    constructor() public {
        set = EnumerableSet.newAddressSet();
    }

    function contains(address value) public view returns (bool) {
        return set.contains(value);
    }

    function add(address value) public {
        bool result = set.add(value);
        emit TransactionResult(result);
    }

    function remove(address value) public {
        bool result = set.remove(value);
        emit TransactionResult(result);
    }

    function enumerate() public view returns (address[] memory) {
        return set.enumerate();
    }
}

pragma solidity ^0.5.0;

import "../utils/EnumerableSet.sol";

contract EnumerableSetMock{
    using EnumerableSet for EnumerableSet.AddressSet;

    event TransactionResult(bool result);

    EnumerableSet.AddressSet private set;

    constructor() public {
        set = EnumerableSet.newAddressSet();
    }

    function contains(address value) public view returns (bool) {
        return EnumerableSet.contains(set, value);
    }

    function add(address value) public {
        bool result = EnumerableSet.add(set, value);
        emit TransactionResult(result);
    }

    function remove(address value) public {
        bool result = EnumerableSet.remove(set, value);
        emit TransactionResult(result);
    }

    function enumerate() public view returns (address[] memory) {
        return EnumerableSet.enumerate(set);
    }
}


ownable: add a notice on renounceOwnership (#937)

* ownable: add a notice on renounceOwnership

* Apply the suggestion by @shrugs

pragma solidity ^0.4.23;

/**
 * @title Ownable
 * @dev The Ownable contract has an owner address, and provides basic authorization control
 * functions, this simplifies the implementation of "user permissions".
 */
contract Ownable {
  address public owner;

  event OwnershipRenounced(address indexed previousOwner);
  event OwnershipTransferred(
    address indexed previousOwner,
    address indexed newOwner
  );

  /**
   * @dev The Ownable constructor sets the original `owner` of the contract to the sender
   * account.
   */
  constructor() public {
    owner = msg.sender;
  }

  /**
   * @dev Throws if called by any account other than the owner.
   */
  modifier onlyOwner() {
    require(msg.sender == owner);
    _;
  }

  /**
   * @dev Allows the current owner to relinquish control of the contract.
   * @notice Renouncing to ownership will leave the contract without an owner.
   * It will not be possible to call the functions with the `onlyOwner`
   * modifier anymore.
   */
  function renounceOwnership() public onlyOwner {
    emit OwnershipRenounced(owner);
    owner = address(0);
  }

  /**
   * @dev Allows the current owner to transfer control of the contract to a newOwner.
   * @param _newOwner The address to transfer ownership to.
   */
  function transferOwnership(address _newOwner) public onlyOwner {
    _transferOwnership(_newOwner);
  }

  /**
   * @dev Transfers control of the contract to a newOwner.
   * @param _newOwner The address to transfer ownership to.
   */
  function _transferOwnership(address _newOwner) internal {
    require(_newOwner != address(0));
    emit OwnershipTransferred(owner, _newOwner);
    owner = _newOwner;
  }
}

pragma solidity ^0.4.23;

/**
 * @title Ownable
 * @dev The Ownable contract has an owner address, and provides basic authorization control
 * functions, this simplifies the implementation of "user permissions".
 */
contract Ownable {
  address public owner;

  event OwnershipRenounced(address indexed previousOwner);
  event OwnershipTransferred(
    address indexed previousOwner,
    address indexed newOwner
  );

  /**
   * @dev The Ownable constructor sets the original `owner` of the contract to the sender
   * account.
   */
  constructor() public {
    owner = msg.sender;
  }

  /**
   * @dev Throws if called by any account other than the owner.
   */
  modifier onlyOwner() {
    require(msg.sender == owner);
    _;
  }

  /**
   * @dev Allows the current owner to relinquish control of the contract.
   */
  function renounceOwnership() public onlyOwner {
    emit OwnershipRenounced(owner);
    owner = address(0);
  }

  /**
   * @dev Allows the current owner to transfer control of the contract to a newOwner.
   * @param _newOwner The address to transfer ownership to.
   */
  function transferOwnership(address _newOwner) public onlyOwner {
    _transferOwnership(_newOwner);
  }

  /**
   * @dev Transfers control of the contract to a newOwner.
   * @param _newOwner The address to transfer ownership to.
   */
  function _transferOwnership(address _newOwner) internal {
    require(_newOwner != address(0));
    emit OwnershipTransferred(owner, _newOwner);
    owner = _newOwner;
  }
}


adding abs value function

adding abs value function

pragma solidity ^0.4.0;

// TODO BUILD TEST!
library MathLib {

    function multiply(uint256 a, uint256 b) internal constant returns (uint256) {
        uint256 c = a * b;
        assert(a == 0 || c / a == b);
        return c;
    }

    function subtract(uint256 a, uint256 b) internal constant returns (uint256) {
        assert(b <= a);
        return a - b;
    }

    function add(uint256 a, uint256 b) internal constant returns (uint256) {
        uint256 c = a + b;
        assert(c >= a);
        return c;
    }

    function sign(int a) internal constant returns (int8) {
        if(a > 0) {
            return 1;
        } else if (a < 0) {
            return -1;
        }
        return 0;
    }

    function abs(int a) returns (int) {
        return uint(a);
    }

    function isSameSign(int a, int b) internal constant returns (bool) {
        return ( a == b || a * b > 0);
    }

}

pragma solidity ^0.4.0;

// TODO BUILD TEST!
library MathLib {

    function multiply(uint256 a, uint256 b) internal constant returns (uint256) {
        uint256 c = a * b;
        assert(a == 0 || c / a == b);
        return c;
    }

    function subtract(uint256 a, uint256 b) internal constant returns (uint256) {
        assert(b <= a);
        return a - b;
    }

    function add(uint256 a, uint256 b) internal constant returns (uint256) {
        uint256 c = a + b;
        assert(c >= a);
        return c;
    }

    function sign(int a) internal constant returns (int8) {
        if(a > 0) {
            return 1;
        } else if (a < 0) {
            return -1;
        }
        return 0;
    }

    function isSameSign(int a, int b) internal constant returns (bool) {
        return ( a == b || a * b > 0);
    }

}


Add event for addition and removal of whitelisted contracts

/*
    Copyright 2017 Phillip A. Elsasser

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
*/

pragma solidity 0.4.18;

import "./MarketContract.sol";
import "zeppelin-solidity/contracts/ownership/Ownable.sol";

/// @title MarketContractRegistry
/// @author Phil Elsasser <phil@marketprotcol.io>
contract MarketContractRegistry is Ownable {

    mapping(address => bool) isWhiteListed;
    address[] addressWhiteList;            // record of currently deployed addresses;

    // events
    event AddressAddedToWhitelist(address indexed contractAddress);
    event AddressRemovedFromWhitelist(address indexed contractAddress);

    /// @notice determines if an address is a valid MarketContract
    /// @return false if the address is not white listed.
    function isAddressWhiteListed(address contractAddress) external view returns (bool) {
        return isWhiteListed[contractAddress];
    }

    /// @notice all currently whitelisted addresses
    /// returns array of addresses
    function getAddressWhiteList() external view returns (address[]) {
        return addressWhiteList;
    }

    /// @dev allows for the owner to remove a white listed contract, eventually ownership could transition to
    /// a decentralized smart contract of community members to vote
    /// @param contractAddress contract to removed from white list
    /// @param whiteListIndex of the contractAddress in the addressWhiteList to be removed.
    function removeContractFromWhiteList(address contractAddress, uint whiteListIndex) external onlyOwner returns (bool) {
        require(isWhiteListed[contractAddress]);
        require(addressWhiteList[whiteListIndex] == contractAddress);
        isWhiteListed[contractAddress] = false;

        // push the last item in array to replace the address we are removing and then trim the array.
        addressWhiteList[whiteListIndex] = addressWhiteList[addressWhiteList.length - 1];
        addressWhiteList.length -= 1;
        AddressRemovedFromWhitelist(contractAddress);
    }

    /// @dev allows for the owner to add a white listed contract, eventually ownership could transition to
    /// a decentralized smart contract of community members to vote
    /// @param contractAddress contract to removed from white list
    function addAddressToWhiteList(address contractAddress) external onlyOwner {
        require(!isWhiteListed[contractAddress]);
        require(MarketContract(contractAddress).isCollateralPoolContractLinked());
        isWhiteListed[contractAddress] = true;
        addressWhiteList.push(contractAddress);
        AddressAddedToWhitelist(contractAddress);
    }
}

/*
    Copyright 2017 Phillip A. Elsasser

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
*/

pragma solidity 0.4.18;

import "./MarketContract.sol";
import "zeppelin-solidity/contracts/ownership/Ownable.sol";

/// @title MarketContractRegistry
/// @author Phil Elsasser <phil@marketprotcol.io>
contract MarketContractRegistry is Ownable {

    mapping(address => bool) isWhiteListed;
    address[] addressWhiteList;            // record of currently deployed addresses;

    /// @notice determines if an address is a valid MarketContract
    /// @return false if the address is not white listed.
    function isAddressWhiteListed(address contractAddress) external view returns (bool) {
        return isWhiteListed[contractAddress];
    }

    /// @notice all currently whitelisted addresses
    /// returns array of addresses
    function getAddressWhiteList() external view returns (address[]) {
        return addressWhiteList;
    }

    /// @dev allows for the owner to remove a white listed contract, eventually ownership could transition to
    /// a decentralized smart contract of community members to vote
    /// @param contractAddress contract to removed from white list
    /// @param whiteListIndex of the contractAddress in the addressWhiteList to be removed.
    function removeContractFromWhiteList(address contractAddress, uint whiteListIndex) external onlyOwner returns (bool) {
        require(isWhiteListed[contractAddress]);
        require(addressWhiteList[whiteListIndex] == contractAddress);
        isWhiteListed[contractAddress] = false;

        // push the last item in array to replace the address we are removing and then trim the array.
        addressWhiteList[whiteListIndex] = addressWhiteList[addressWhiteList.length - 1];
        addressWhiteList.length -= 1;
    }

    /// @dev allows for the owner to add a white listed contract, eventually ownership could transition to
    /// a decentralized smart contract of community members to vote
    /// @param contractAddress contract to removed from white list
    function addAddressToWhiteList(address contractAddress) external onlyOwner {
        require(!isWhiteListed[contractAddress]);
        require(MarketContract(contractAddress).isCollateralPoolContractLinked());
        isWhiteListed[contractAddress] = true;
        addressWhiteList.push(contractAddress);
    }
}


Simplify contract.

Simplify contract.

/**
 * @title AccountKeyValue
 * @author Jonathan Brown <jbrown@bluedroplet.com>
 */
contract AccountKeyValue {

  mapping (address => mapping (string => bytes)) values;

  event logUpdate(address indexed account, string key) anonymous;

  function valueGet(address account, string key) constant returns (bytes) {
    return values[account][key];
  }

  function valueSet(string key, bytes value) {
    values[msg.sender][key] = value;
    logUpdate(msg.sender, key);
  }

  function valueDelete(string key) {
    delete values[msg.sender][key];
    logUpdate(msg.sender, key);
  }

}

/**
 * @title AccountKeyValue
 * @author Jonathan Brown <jbrown@bluedroplet.com>
 */
contract AccountKeyValue {

  mapping (address => mapping (bytes32 => bytes)) values;

  // TODO: add c4 after https://github.com/ethereum/solidity/issues/120
  event Update(string indexed c1, string indexed c2, string indexed c3) anonymous;

  function keyHash(string c1, string c2, string c3, string c4, string c5) internal returns (bytes32) {
    return sha3(c1, '.', c2, '.', c3, '.', c4, '.', c5);
  }

  function getValue(address account, string c1, string c2, string c3, string c4, string c5) constant returns (bytes) {
    return values[account][keyHash(c1, c2, c3, c4, c5)];
  }

  function setValue(bytes value, string c1, string c2, string c3, string c4, string c5) {
    values[msg.sender][keyHash(c1, c2, c3, c4, c5)] = value;
    Update(c1, c2, c3);
  }

  function deleteValue(string c1, string c2, string c3, string c4, string c5) {
    delete values[msg.sender][keyHash(c1, c2, c3, c4, c5)];
    Update(c1, c2, c3);
  }

}


add msg.value for the addCustomer function

pragma solidity ^0.4.8;

import "./SafeMath.sol";

contract DetherTx {
  struct Details {
      // if possible check if it is an uniq username
      string username;
      uint price;
      uint balance;
      uint volumeTrade;
      uint nbTrade;
      string localizationGpsX;
      string localizationGpsY;
      uint commentIpfsId;
  }

  address[] public listAdressesUsers;

  mapping(address => Details) public users;

  event Transfer (address indexed _from, address indexed _to, uint256 _value);

  function DetherTx() {
  }

  function sendCoin (address receiver, uint amount) returns(bool sufficient) {
    if (users[msg.sender].balance < amount) return false;
    users[msg.sender].balance = SafeMath.safeSub(users[msg.sender].balance, amount);
    users[msg.sender].volumeTrade = SafeMath.safeAdd(users[msg.sender].volumeTrade, amount);
    users[receiver].volumeTrade = SafeMath.safeAdd(users[receiver].volumeTrade, amount);
    ++users[receiver].nbTrade;
    ++users[msg.sender].nbTrade;
    uint amountWithoutFees = SafeMath.safeSub(amount, (amount * 1/100));
    users[receiver].balance = SafeMath.safeAdd(users[receiver].balance, amountWithoutFees);
    Transfer(msg.sender, receiver, amountWithoutFees);

    return true;
  }

  function getBalance () constant returns(uint) {
    return users[msg.sender].balance;
  }

  function getVolume () constant returns(uint) {
    return users[msg.sender].volumeTrade;
  }

  function getNbTrade () constant returns(uint) {
    return users[msg.sender].nbTrade;
  }

  function deposit () payable returns (uint) {
    return  users[msg.sender].balance += msg.value;
    //return SafeMath.safeAdd(users[msg.sender].balance,msg.value );
  }

  /// add and change the wallet of a passager
  function addAccount
  (
    string _username,
    uint _price,
    string _localizationGpsX,
    string _localizationGpsY,
    uint _commentIpfsId
  ) payable returns (
    string,
    uint,
    string,
    string,
    uint
  ) {
     Details details = users[msg.sender];
     details.username = _username;
     details.price = _price;
     details.balance += msg.value;
     details.volumeTrade = 0;
     details.nbTrade = 0;
     details.localizationGpsX = _localizationGpsX;
     details.localizationGpsY = _localizationGpsY;
     details.commentIpfsId = _commentIpfsId;

     ++listAdressesUsers.length;
     listAdressesUsers[listAdressesUsers.length-1] = msg.sender;

     return (
       _username,
       _price
       _localizationGpsX,
       _localizationGpsY,
       _commentIpfsId
     );
  }

  function withdraw (uint _amount) {
    if (users[msg.sender].balance < _amount) throw;
    // It is important to set this to zero because the recipient
    // can call this function again as part of the receiving call
    // before `send` returns.

    //users[msg.sender].balance -= _amount;
    users[msg.sender].balance = SafeMath.safeSub(users[msg.sender].balance,_amount);

    var amount = _amount;

    if(!msg.sender.send(amount)) throw;
  }

  function getAddressesAccounts () constant returns (address[]) {
    return listAdressesUsers;
  }

  function getAccount (address _user) constant returns (
      uint,
      uint,
      uint,
      uint,
      string,
      string,
      uint
    ) {
    return (
      users[_user].price,
      users[_user].balance,
      users[_user].volumeTrade,
      users[_user].nbTrade,
      users[_user].localizationGpsX,
      users[_user].localizationGpsY,
      users[_user].commentIpfsId
    );
  }

  // fallback
  function () payable {}
}

pragma solidity ^0.4.8;

import "./SafeMath.sol";

contract DetherTx {
  struct Details {
      // if possible check if it is an uniq username
      string username;
      uint price;
      uint balance;
      uint volumeTrade;
      uint nbTrade;
      string localizationGpsX;
      string localizationGpsY;
      uint commentIpfsId;
  }

  address[] public listAdressesUsers;

  mapping(address => Details) public users;

  event Transfer (address indexed _from, address indexed _to, uint256 _value);

  function DetherTx() {
  }

  function sendCoin (address receiver, uint amount) returns(bool sufficient) {
    if (users[msg.sender].balance < amount) return false;
    users[msg.sender].balance = SafeMath.safeSub(users[msg.sender].balance, amount);
    users[msg.sender].volumeTrade = SafeMath.safeAdd(users[msg.sender].volumeTrade, amount);
    users[receiver].volumeTrade = SafeMath.safeAdd(users[receiver].volumeTrade, amount);
    ++users[receiver].nbTrade;
    ++users[msg.sender].nbTrade;
    uint amountWithoutFees = SafeMath.safeSub(amount, (amount * 1/100));
    users[receiver].balance = SafeMath.safeAdd(users[receiver].balance, amountWithoutFees);
    Transfer(msg.sender, receiver, amountWithoutFees);

    return true;
  }

  function getBalance () constant returns(uint) {
    return users[msg.sender].balance;
  }

  function getVolume () constant returns(uint) {
    return users[msg.sender].volumeTrade;
  }

  function getNbTrade () constant returns(uint) {
    return users[msg.sender].nbTrade;
  }

  function deposit () payable returns (uint) {
    return  users[msg.sender].balance += msg.value ;
    //return SafeMath.safeAdd(users[msg.sender].balance,msg.value );
  }

  /// add and change the wallet of a passager
  function addAccount
  (
    string _username,
    uint _price,
    string _localizationGpsX,
    string _localizationGpsY,
    uint _commentIpfsId
  ) returns (
    string,
    uint,
    string,
    string,
    uint
  ) {
     Details details = users[msg.sender];
     details.username = _username;
     details.price = _price;
     details.balance = 0;
     details.volumeTrade = 0;
     details.nbTrade = 0;
     details.localizationGpsX = _localizationGpsX;
     details.localizationGpsY = _localizationGpsY;
     details.commentIpfsId = _commentIpfsId;

     ++listAdressesUsers.length;
     listAdressesUsers[listAdressesUsers.length-1] = msg.sender;

     return (
       _username,
       _price
       _localizationGpsX,
       _localizationGpsY,
       _commentIpfsId
     );
  }

  function withdraw (uint _amount) {
    if (users[msg.sender].balance < _amount) throw;
    // It is important to set this to zero because the recipient
    // can call this function again as part of the receiving call
    // before `send` returns.

    //users[msg.sender].balance -= _amount;
    users[msg.sender].balance = SafeMath.safeSub(users[msg.sender].balance,_amount);

    var amount = _amount;

    if(!msg.sender.send(amount)) throw;
  }

  function getAddressesAccounts () constant returns (address[]) {
    return listAdressesUsers;
  }

  function getAccount (address _user) constant returns (
      uint,
      uint,
      uint,
      uint,
      string,
      string,
      uint
    ) {
    return (
      users[_user].price,
      users[_user].balance,
      users[_user].volumeTrade,
      users[_user].nbTrade,
      users[_user].localizationGpsX,
      users[_user].localizationGpsY,
      users[_user].commentIpfsId
    );
  }

  // fallback
  function () payable {}
}


Shifted assessment protocol from one big thing to a series of 1 on 1 assessments. Made corresponding changes in the setPotentialAssessor and confirmAssessor functions. Will kill jared eventually.

contract Master
{
  //Initialize master data store
  mapping (address => uint) tokenBalance;
  mapping (address => string) tagName;
  mapping (string => address) tagAddressFromName;
  mapping (address => address[]) achievements;
  mapping (address => bool) availability;
  mapping (address => address) users;

  event TagCreation
  ( string _tagName,
    address _tagAddress,
    address[] _parents);

  function Master()
  {
    tokenBalance[address(this)] = 1;
    address[] memory a;
    uint useless = addTag("account", a);
  }

  function mapTokenBalance(address user, uint balance)
  {
    if(tagAddressFromName[tagName[msg.sender]] == 0)
    {
      tokenBalance[user] = balance;
    }
  }
  function mapTagName(address tagAddress, string name)
  {
    tagName[tagAddress] = name;
  }
  function mapTagAddressFromName(string name, address tagAddress)
  {
    tagAddressFromName[name] = tagAddress;
  }
  function mapAchievement(address user, address achievment)
  {
    achievements[user].push(achievment);
  }
  function mapAvailability(address user, bool available)
  {
    availability[user] = available;
  }

  function getTokenBalance(address user) returns(uint)
  {
    return tokenBalance[user];
  }
  function getTagName(address tagAddress) returns(string)
  {
    return tagName[tagAddress];
  }
  function getTagAddressFromName(string name) returns(address)
  {
    return tagAddressFromName[name];
  }
  function getAchievement(address user) returns(address[])
  {
    return achievements[user];
  }
  function getNumberOfachievments(address user) returns(uint)
  {
    return achievements[user].length;
  }
  function getAvailability(address user) returns(bool)
  {
    return availability[user] = true;
  }
  function getTagDescription(string nameOfTag) returns(string tagDescription)
  {
    return Tag(tagAddressFromName[nameOfTag]).getDescription();
  }

  function addUser()
  {
    User newUser = new User(msg.sender, address(this));
    Tag(tagAddressFromName["account"]).startAssessment(address(newUser),5);
  }

  function addTag(string name, address[] parentList, string description) returns(uint) //Creates a new tag contract
  {
    uint response = 0;
    address[] parents;
    if(tokenBalance[msg.sender] < 1)
    {
      response += 1;
    }
    if(tagAddressFromName[name] == 0)
    {
      response += 10;
    }
    if(response==0)
    {
      for(uint i=0; i<= parentList.length; i++) //adds all the given parents
      {
        if(parentList[i]==0)
        {
          response += 100*(10**i);
        }
        else
        {
          parents.push(parentList[i]);
        }
      }
      Tag newTag = new Tag(name, parents, address(this), description);
      address newTagAddress = address(newTag);
      tagName[newTagAddress] = name;
      tagAddressFromName[name] = newTagAddress;
      tokenBalance[msg.sender] -= 1;
      TagCreation(name, newTagAddress, parents);
    }
    return response;
  }
}

//Defines the meta-contract for a Tag
contract Tag
{
  address[] parentTags;
  address master;
  string name;
  string description;
  address[] owners; //Those who have earned the tag
  mapping(address => address[]) assessmentHistory; //All assessments completed
  mapping(address => uint) scores; //All positive assessements scores
  event CompletedAssessment
  ( address _assessee,
    bool _pass,
    uint _score,
    address _assessment);

  function Tag(string tagName, address[] parents, address masterAddress, string tagDescription)
  {
    name = tagName;
    parentTags = parents;
    master = masterAddress;
    description = tagDescription;
  }

  function getDescription() returns(string)
  {
    return description;
  }

  function getOwners() returns(address[])
  {
    return owners;
  }

  function getOwnerLength() returns(uint)
  {
    return owners.length;
  }

  function getOwner(uint index) returns(address)
  {
      return owners[index];
  }

  function getParents() returns(address[])
  {
    return parentTags;
  }

  function getParentsLength() returns(uint)
  {
    return parentTags.length;
  }

  function getParent(uint index) returns(address)
  {
      return parentTags[index];
  }

  function setAssessorPool(address tagAddress, address assessment)
  {
    for(uint i = 0; i < Tag(tagAddress).getOwnerLength() && Assessment(assessment).getAssessmentPoolSize() != 0; i++)
    {
      if(Assessment(assessment).getAssessorPoolLength() < Tag(tagAddress).getOwnerLength()/10)
      {
        address random = Tag(tagAddress).getOwner(getRandom(Tag(tagAddress).getOwnerLength()-1));
        if(Master(master).getAvailability(random) == true)
        {
          Assessment(assessment).addToAssessorPool(random);
          Assessment(assessment).setAssessmentPoolSize(Assessment(assessment).getAssessmentPoolSize() -1);
        }
      }
      else
      {
        for(uint j = 0; j < Tag(tagAddress).getParentsLength(); j++)
        {
          setAssessorPool(Tag(tagAddress).getParent(j), assessment);
        }
      }
      if(Assessment(assessment).getAssessmentPoolSize() <= 0)
      {
        Assessment(assessment).setPotentialAssessors(Assessment(assessment).getNumberOfAssessors());
      }
    }
  }

  function startAssessment(address assessee, uint size)
  {
    Assessment newAssessment = new Assessment(assessee, address(this), master);
    newAssessment.setNumberOfAssessors(size);
    newAssessment.setAssessmentPoolSize(size*20);
    setAssessorPool(address(this), address(newAssessment));
  }

  function finishAssessment(bool pass, uint score, address assessee, address assessment)
  {
    if(pass == true)
    {
      owners.push(assessee);
      scores[assessee] = score;
      Master(master).mapAchievement(assessee,address(this));
    }
    if(pass == false && address(this) == Master(master).getTagAddressFromName("account"))
    {
      User(assessee).suicide();
    }
    assessmentHistory[assessee].push(assessment);
    CompletedAssessment(assessee, pass, score, assessment);
  }
  function getRandom(uint i) returns(uint)
  {
    return 12;
  }
}

//Defines the meta-contract for an assessment
contract Assessment
{
  address assessee; //We need a better word for this
  address[] assessorPool;
  mapping (address => uint) assessors;
  address[] potentialAssessors;
  address[] finalAssessors;
  address tag;
  address master;
  uint poolSizeRemaining;
  uint numberOfAssessors;
  struct Results
  {
    bool pass;
    uint score;
  }
  mapping(address => string) assessmentTasks; //Given by the assessors as IPFS hashes
  mapping(address => string) assessmentResponses; //Given by the assessee as IPFS hashes
  mapping(address => Results) assessmentResults; //Pass/Fail and Score given by assessors
  uint finalScore;
  bool finalResult;
  uint taskCreationTime;
  uint taskCompletionTime;
  uint referenceTime;
  uint numberCancelled;

  function Assessment(address assesseeAddress, address tagAddress, address masterAddress, uint timeForTaskCreation)
  {
    assessee = assesseeAddress;
    tag = tagAddress;
    master = masterAddress;
    startReferenceTime = block.timestamp;
    taskCreationTime = timeForTaskCreation;
  }

  function setNumberOfAssessors(uint number)
  {
    numberOfAssessors = number;
  }

  function getNumberOfAssessors() returns(uint)
  {
    return numberOfAssessors;
  }

  function setAssessmentPoolSize(uint sizeRemaining)
  {
    poolSizeRemaining = sizeRemaining;
  }

  function getAssessmentPoolSize() returns(uint)
  {
    return poolSizeRemaining;
  }

  function addToAssessorPool(address potentialAddress)
  {
    assessorPool.push(potentialAddress);
  }

  function setPotentialAssessor()
  {
    bool potentialAssessorSet = false;
    while(potentialAssessorSet == false)
    {
      address randomAssessor = assessorPool[getRandom(assessorPool.length)];
      if(assessors[randomAssessor] == 0)
      {
        assessors[randomAssessor] = 3;
        potentialAssessors.push(randomAssessor);
        potentialAssessorSet = true;
        User(randomAssessor).notification("Called As A Potential Assessor",tag, 1);
      }
    }
    referenceTime = now;
  }

  function getAssessorPoolLength() returns(uint)
  {
      return assessorPool.length;
  }

  function getRandom(uint i) returns(uint)
  {
    return 12;
  }

  function setTask(string data)
  {
    if(assessors[msg.sender] == 1 && now - taskSettingReferenceTime <= 3600)
    {
      assessmentTasks[msg.sender] = data;
      assessors[msg.sender] = 4;
      User(msg.sender).notification("Task Data Inputted", tag, 5);
      User(assessee).notification("New Task Available", tag, 7)
    }
    if(now - taskSettingReferenceTime > 3600)
    {
      bool invalidAssessment = false;
      for(uint i = 0; i < finalAssessors.length; i++)
      {
        if(assessors[finalAssessors[i]]!=4)
        {
          User(finalAssessors[i]).notification("Did Not Submit Task On Time", tag, 6);
          Master(master).mapTokenBalance(finalAssessors[i], Master(master).getTokenBalance(finalAssessors[i]) - 1);
          User(finalAssessors[i]).setReputation(User(finalAssessors[i]).getReputation() + 1);
          invalidAssessment = true;
        }
      }
      if(invalidAssessment = true)
      {
        cancelAssessment();
      }
    }
    uint totalStatus
    for(uint i = 0; i < finalAssessors.length; i++)
    {
      totalStatus += assessors[finalAssessors[i]];
    }
    if(totalStatus/4 == numberOfAssessors)
    {
      referenceTime = now;
    }
  }

  function cancelAssessment()
  {
    User(assessee).notification("Assessment Cancled", tag, 8);
    for(uint i = 0; i < finalAssessors.length; i++)
    {
      User(finalAssessors[i]).notification("Assessment Cancled", tag, 8);
    }
    selfdestruct(master);
  }

  function getTask(address assessorAddress) returns(string)
  {
    return assessmentTasks[assessorAddress];
  }

  function setResponse(address assesseeAddress, string data)
  {
    assessmentResponses[assesseeAddress] = data;
  }

  function getResponse(address assesseeAddress) returns(string)
  {
    return assessmentResponses[assesseeAddress];
  }

  function setResult(bool pass, uint score)
  {
    Results memory results;
    results.pass = pass;
    results.score = score;
    assessmentResults[msg.sender] = results;
  }

  function assess()
  {

  }

  function calculateResult()
  {

  }

  function confirmAssessor(uint confirm, bool timeKnow)
  {
    if(numberCancelled >= numberOfAssessors)
    {
      cancelAssessment();
    }
    if(assessors[potentialAssessors[potentialAssessors.length - 1]] != 0 && now - referenceTime <= 180)
    {
      assessors[potentialAssessors[potentialAssessors.length - 1]] = confirm;
      if(confirm == 1)
      {
        User(potentialAssessors[potentialAssessors.length -1]).notification("The Time Allocated For Setting The Assessment Task Is:" + taskCreationTime, tag, 2);
        referenceTime = now;
      }
      if(confirm == 2 || confirm == 4)
      {
        User(potentialAssessors[potentialAssessors.length -1]).notification("Confirmed As Not Assessing", tag, 3);
        numberCancelled ++;
        setPotentialAssessor();
      }
      if(confirm == 5)
      {
        finalAssessors.push(potentialAssessors[potentialAssessors.length -1]);
        User(potentialAssessors[potentialAssessors.length -1]).notification("Confirmed As Assessing", tag, 9);
        referenceTime = now;
      }
    }
    if(now - confirmationReferenceTime > 180)
    {
      if(timeKnow == false && assessors[potentialAssessors[potentialAssessors.length -1]]==3)
      {
      User(potentialAssessors[potentialAssessors.length -1]).notification("Did Not Respond In Time To Be Assessor", tag, 4);
      Master(master).mapTokenBalance(potentialAssessors[potentialAssessors.length -1],
        Master(master).getTokenBalance(potentialAssessors[potentialAssessors.length -1]) - 1);
      setPotentialAssessor();
      }
      if(timeKnow == true && assessors[potentialAssessors[potentialAssessors.length -1]]==1)
      {
        User(potentialAssessors[potentialAssessors.length -1]).notification("Did Not Respond In Time To Be Assessor", tag, 4);
        setPotentialAssessor();
      }
    }
  }

  function returnResults()
  {
    Tag(tag).finishAssessment(finalResult, finalScore, assessee, address(this));
  }

  function cashout()
  {

  }
}

contract User
{
  address user;
  address master;
  address[] acheivements;
  string userData;
  uint reputation;

  event Notification
  ( string _description,
    address _sender,
    address _user,
    address _tag,
    uint _code);

  function User(address userAddress, address masterAddress)
  {
    user = userAddress;
    master = masterAddress;
    reputation = 1;
  }

  function getReputation() returns uint
  {
    return reputation;
  }

  function setReputation(uint newReputation)
  {
    reputation = newReputation;
  }

  function notification(string description, address tag, uint code)
  {
    Notification(description, msg.sender, address(this), tag, code);
  }

  function setUserData(string hash)
  {
    userData = hash;
  }

  function getUserData() returns(string)
  {
    return userData;
  }

  function suicide()
  {
    selfdestruct(master);
  }
}

contract Master
{
  //Initialize master data store
  mapping (address => uint) tokenBalance;
  mapping (address => string) tagName;
  mapping (string => address) tagAddressFromName;
  mapping (address => address[]) achievements;
  mapping (address => bool) availability;
  mapping (address => address) users;

  event TagCreation
  ( string _tagName,
    address _tagAddress,
    address[] _parents);

  function Master()
  {
    tokenBalance[address(this)] = 1;
    address[] memory a;
    uint useless = addTag("account", a);
  }

  function mapTokenBalance(address user, uint balance)
  {
    if(tagAddressFromName[tagName[msg.sender]] == 0)
    {
      tokenBalance[user] = balance;
    }
  }
  function mapTagName(address tagAddress, string name)
  {
    tagName[tagAddress] = name;
  }
  function mapTagAddressFromName(string name, address tagAddress)
  {
    tagAddressFromName[name] = tagAddress;
  }
  function mapAchievement(address user, address achievment)
  {
    achievements[user].push(achievment);
  }
  function mapAvailability(address user, bool available)
  {
    availability[user] = available;
  }

  function getTokenBalance(address user) returns(uint)
  {
    return tokenBalance[user];
  }
  function getTagName(address tagAddress) returns(string)
  {
    return tagName[tagAddress];
  }
  function getTagAddressFromName(string name) returns(address)
  {
    return tagAddressFromName[name];
  }
  function getAchievement(address user) returns(address[])
  {
    return achievements[user];
  }
  function getNumberOfachievments(address user) returns(uint)
  {
    return achievements[user].length;
  }
  function getAvailability(address user) returns(bool)
  {
    return availability[user] = true;
  }
  function getTagDescription(string nameOfTag) returns(string tagDescription)
  {
    return Tag(tagAddressFromName[nameOfTag]).getDescription();
  }

  function addUser()
  {
    User newUser = new User(msg.sender, address(this));
    Tag(tagAddressFromName["account"]).startAssessment(address(newUser),5);
  }

  function addTag(string name, address[] parentList, string description) returns(uint) //Creates a new tag contract
  {
    uint response = 0;
    address[] parents;
    if(tokenBalance[msg.sender] < 1)
    {
      response += 1;
    }
    if(tagAddressFromName[name] == 0)
    {
      response += 10;
    }
    if(response==0)
    {
      for(uint i=0; i<= parentList.length; i++) //adds all the given parents
      {
        if(parentList[i]==0)
        {
          response += 100*(10**i);
        }
        else
        {
          parents.push(parentList[i]);
        }
      }
      Tag newTag = new Tag(name, parents, address(this), description);
      address newTagAddress = address(newTag);
      tagName[newTagAddress] = name;
      tagAddressFromName[name] = newTagAddress;
      tokenBalance[msg.sender] -= 1;
      TagCreation(name, newTagAddress, parents);
    }
    return response;
  }
}

//Defines the meta-contract for a Tag
contract Tag
{
  address[] parentTags;
  address master;
  string name;
  string description;
  address[] owners; //Those who have earned the tag
  mapping(address => address[]) assessmentHistory; //All assessments completed
  mapping(address => uint) scores; //All positive assessements scores
  event CompletedAssessment
  ( address _assessee,
    bool _pass,
    uint _score,
    address _assessment);

  function Tag(string tagName, address[] parents, address masterAddress, string tagDescription)
  {
    name = tagName;
    parentTags = parents;
    master = masterAddress;
    description = tagDescription;
  }

  function getDescription() returns(string)
  {
    return description;
  }

  function getOwners() returns(address[])
  {
    return owners;
  }

  function getOwnerLength() returns(uint)
  {
    return owners.length;
  }

  function getOwner(uint index) returns(address)
  {
      return owners[index];
  }

  function getParents() returns(address[])
  {
    return parentTags;
  }

  function getParentsLength() returns(uint)
  {
    return parentTags.length;
  }

  function getParent(uint index) returns(address)
  {
      return parentTags[index];
  }

  function setAssessorPool(address tagAddress, address assessment)
  {
    for(uint i = 0; i < Tag(tagAddress).getOwnerLength() && Assessment(assessment).getAssessmentPoolSize() != 0; i++)
    {
      if(Assessment(assessment).getAssessorPoolLength() < Tag(tagAddress).getOwnerLength()/10)
      {
        address random = Tag(tagAddress).getOwner(getRandom(Tag(tagAddress).getOwnerLength()-1));
        if(Master(master).getAvailability(random) == true)
        {
          Assessment(assessment).addToAssessorPool(random);
          Assessment(assessment).setAssessmentPoolSize(Assessment(assessment).getAssessmentPoolSize() -1);
        }
      }
      else
      {
        for(uint j = 0; j < Tag(tagAddress).getParentsLength(); j++)
        {
          setAssessorPool(Tag(tagAddress).getParent(j), assessment);
        }
      }
      if(Assessment(assessment).getAssessmentPoolSize() <= 0)
      {
        Assessment(assessment).setPotentialAssessors(Assessment(assessment).getNumberOfAssessors());
      }
    }
  }

  function startAssessment(address assessee, uint size)
  {
    Assessment newAssessment = new Assessment(assessee, address(this), master);
    newAssessment.setNumberOfAssessors(size);
    newAssessment.setAssessmentPoolSize(size*20);
    setAssessorPool(address(this), address(newAssessment));
  }

  function finishAssessment(bool pass, uint score, address assessee, address assessment)
  {
    if(pass == true)
    {
      owners.push(assessee);
      scores[assessee] = score;
      Master(master).mapAchievement(assessee,address(this));
    }
    if(pass == false && address(this) == Master(master).getTagAddressFromName("account"))
    {
      User(assessee).suicide();
    }
    assessmentHistory[assessee].push(assessment);
    CompletedAssessment(assessee, pass, score, assessment);
  }
  function getRandom(uint i) returns(uint)
  {
    return 12;
  }
}

//Defines the meta-contract for an assessment
contract Assessment
{
  address assessee; //We need a better word for this
  address[] assessorPool;
  mapping (address => uint) assessors;
  address[] potentialAssessors;
  address[] finalAssessors;
  address tag;
  address master;
  uint poolSizeRemaining;
  uint numberOfAssessors;
  struct Results
  {
    bool pass;
    uint score;
  }
  mapping(address => string) assessmentTasks; //Given by the assessors as IPFS hashes
  mapping(address => string) assessmentResponses; //Given by the assessee as IPFS hashes
  mapping(address => Results) assessmentResults; //Pass/Fail and Score given by assessors
  uint finalScore;
  bool finalResult;
  uint startReferenceTime;
  uint confirmationReferenceTime;
  uint taskSettingReferenceTime;
  uint responseSettingReferenceTime;
  uint assessmentReferenceTime;

  function Assessment(address assesseeAddress, address tagAddress, address masterAddress)
  {
    assessee = assesseeAddress;
    tag = tagAddress;
    master = masterAddress;
    startReferenceTime = block.timestamp;
  }

  function setNumberOfAssessors(uint number)
  {
    numberOfAssessors = number;
  }

  function getNumberOfAssessors() returns(uint)
  {
    return numberOfAssessors;
  }

  function setAssessmentPoolSize(uint sizeRemaining)
  {
    poolSizeRemaining = sizeRemaining;
  }

  function getAssessmentPoolSize() returns(uint)
  {
    return poolSizeRemaining;
  }

  function addToAssessorPool(address potentialAddress)
  {
    assessorPool.push(potentialAddress);
  }

  function setPotentialAssessors(uint numberOfAssessorsNeeded)
  {
    for(uint i = 0; i < numberOfAssessorsNeeded; i++)
    {
      address randomAssessor = assessorPool[getRandom(assessorPool.length)];
      if(assessors[randomAssessor] == 0 && 100/User(randomAssessor).getReputation() >= getRandom(100))
      {
        assessors[randomAssessor] = 3;
        potentialAssessors.push(randomAssessor);
        User(randomAssessor).notification("Called As A Potential Assessor",tag, 1);
      }
    }
    confirmationReferenceTime = now;
  }

  function getAssessorPoolLength() returns(uint)
  {
      return assessorPool.length;
  }

  function getRandom(uint i) returns(uint)
  {
    return 12;
  }

  function setTask(string data)
  {
    if(assessors[msg.sender] == 1 && now - taskSettingReferenceTime <= 3600)
    {
      assessmentTasks[msg.sender] = data;
      assessors[msg.sender] = 4;
      User(msg.sender).notification("Task Data Inputted", tag, 5);
      User(assessee).notification("New Task Available", tag, 7)
    }
    if(now - taskSettingReferenceTime > 3600)
    {
      bool invalidAssessment = false;
      for(uint i = 0; i < finalAssessors.length; i++)
      {
        if(assessors[finalAssessors[i]]!=4)
        {
          User(finalAssessors[i]).notification("Did Not Submit Task On Time", tag, 6);
          Master(master).mapTokenBalance(finalAssessors[i], Master(master).getTokenBalance(finalAssessors[i]) - 1);
          User(finalAssessors[i]).setReputation(User(finalAssessors[i]).getReputation() + 1);
          invalidAssessment = true;
        }
      }
      if(invalidAssessment = true)
      {
        cancelAssessment();
      }
    }
    uint totalStatus
    for(uint i = 0; i < finalAssessors.length; i++)
    {
      totalStatus += assessors[finalAssessors[i]];
    }
    if(totalStatus/4 == numberOfAssessors)
    {
      referenceTime = now;
    }
  }

  function cancelAssessment()
  {
    User(assessee).notification("Assessment Cancled", tag, 8);
    for(uint i = 0; i < finalAssessors.length; i++)
    {
      User(finalAssessors[i]).notification("Assessment Cancled", tag, 8);
    }
    selfdestruct(master);
  }

  function getTask(address assessorAddress) returns(string)
  {
    return assessmentTasks[assessorAddress];
  }

  function setResponse(address assesseeAddress, string data)
  {
    assessmentResponses[assesseeAddress] = data;
  }

  function getResponse(address assesseeAddress) returns(string)
  {
    return assessmentResponses[assesseeAddress];
  }

  function setResult(bool pass, uint score)
  {
    Results memory results;
    results.pass = pass;
    results.score = score;
    assessmentResults[msg.sender] = results;
  }

  function assess()
  {

  }

  function calculateResult()
  {

  }

  function confirmAssessor(uint confirm)
  {
    if(assessors[msg.sender] != 0 && now - confirmationReferenceTime <= 180)
    {
      assessors[msg.sender] = confirm;
      if(confirm == 1)
      {
        finalAssessors.push(msg.sender);
        User(msg.sender).notification("Confirmed As Assessing", tag, 2);
      }
      if(confirm == 2)
      {
        User(msg.sender).notification("Confirmed As Not Assessing", tag, 3);
      }
    }
    if(now - confirmationReferenceTime > 180)
    {
      for(uint i = 0; i < potentialAssessors.length; i++)
      {
        if(assessors[msg.sender]==3)
        {
          User(msg.sender).notification("Did Not Respond In Time To Be Assessor", tag, 4);
          Master(master).mapTokenBalance(msg.sender, Master(master).getTokenBalance(msg.sender) - 1);
        }
      }
      if(numberOfAssessors - finalAssessors.length != 0)
      {
        uint remaining = numberOfAssessors - finalAssessors.length;
        delete potentialAssessors;
        referenceTime = now;
        setPotentialAssessors(remaining);
      }
    }
    if(numberOfAssessors - finalAssessors.length == 0)
    {
      taskSettingReferenceTime = now;
    }
  }

  function returnResults()
  {
    Tag(tag).finishAssessment(finalResult, finalScore, assessee, address(this));
  }

  function cashout()
  {

  }
}

contract User
{
  address user;
  address master;
  address[] acheivements;
  string userData;
  uint reputation;

  event Notification
  ( string _description,
    address _sender,
    address _user,
    address _tag,
    uint _code);

  function User(address userAddress, address masterAddress)
  {
    user = userAddress;
    master = masterAddress;
    reputation = 1;
  }

  function getReputation() returns uint
  {
    return reputation;
  }

  function setReputation(uint newReputation)
  {
    reputation = newReputation;
  }

  function notification(string description, address tag, uint code)
  {
    Notification(description, msg.sender, address(this), tag, code);
  }

  function setUserData(string hash)
  {
    userData = hash;
  }

  function getUserData() returns(string)
  {
    return userData;
  }

  function suicide()
  {
    selfdestruct(master);
  }
}


Update the use of call() with selector only. (#1033)

pragma solidity ^0.4.24;

contract ReentrancyAttack {

  function callSender(bytes4 data) public {
    // solium-disable-next-line security/no-low-level-calls
    require(msg.sender.call(abi.encodeWithSelector(data)));
  }

}

pragma solidity ^0.4.24;

contract ReentrancyAttack {

  function callSender(bytes4 data) public {
    // solium-disable-next-line security/no-low-level-calls
    require(msg.sender.call(data));
  }

}


remove notes

remove notes

pragma solidity ^0.4.4;

// Vending machine to sell X number of tokens for approx Y number of ETH.
// As purchases are made, the owned ERC20 tokens will be sent out to purchaser.
// Purchases will be priced based on the purchase "Generation" the vending machine is in.
// As more purchases are made the Generation gets incremented.
// Each generation will sell the tokens for twice as much as the previous generation.
contract VendingMachine is Ownable {

    // The contract where the tokens are held by this contract until they are sold.
    ERC20 public token;

    // Total Amount of tokens to sell to purchasers
    uint public amountToSell = 21000000;

    // Total amount of tokens that have been sold so far.  Starts at 0.
    uint public amountSold = 0;

    // Initial price that each ETH sent in will get back in tokens.
    uint public initialPricePerEth = 10000;

    // Constructor initalized with the token contract that it will be selling.
    function VendingMachine(ERC20 tokenContract){
        token = tokenContract;
    }

    function calculateSaleAmount(uint alreadySold, uint ethAmount) uint{
        // First get the amount of tokens sold from the beginning of this generation.
        // Calculate the price per ETH of the current generation
        // Calculate how mant tokens they are trying to buy
        // If they are buying past the current generation, then figure out how much they purchase in the next generation.
    }

    // When this function is called, it will send the originator X tokens.
    // X is determined by the price calculated based on the current generation of sales.
    function PurchaseTokens payable(){

        // Updatete the total amount sold

        // Send the tokens to the sender's account
    }

    // This function allows the owner to withdraw any ETH that was sent in via purchases.
    function WithdrawEth(uint amount) onlyOwner {
        // Send out what they are requesting to withdraw
        msg.sender.send(amount);
    }
}

Example:

I want to sell 10 tokens for 10 ETH, but I want the first token sole to be super cheap

First token sells for 0.1 ETH and last sells for 0.9 ETH

0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
1


add refundETH event

add refundETH event

pragma solidity ^0.4.8;
import "./SafeMath.sol";
import "./RLC.sol";

/*
  Crowdsale Smart Contract for the iEx.ec project

  This smart contract collects ETH and BTC, and in return emits RLC tokens to the backers

  Thanks to BeyondTheVoid and TokenMarket who helped us shaping this code.

 */

// TODO
// Comment vont faire les gars qui ont investit en BTC avant le min cap pour recuperer leur rlc?
// add lockable to RLC transfer only for owner
// add emergency stop

// TEST:
// test differente timeframe
// test multiple invest
// test claim ETH

contract Crowdsale is SafeMath {

  	struct Backer {
  	  uint weiReceived;	// Amount of ETH given
	  string btc_address;  //store the btc address for full tracability
	  uint satoshiReceived;	// Amount of BTC given
	  uint rlcToSend;   	// rlc to distribute when the min cap is reached
	  uint rlcSent;
	}

	RLC 	public rlc;         // RLC contract reference
	address public owner;       // Contract owner (iEx.ec team)
	address public multisigETH; // Multisig contract that will receive the ETH
	address public BTCproxy;	// addess of the BTC Proxy

	uint public RLCPerETH;      // Number of RLC per ETH
	uint public RLCPerSATOSHI;  // Number of RLC per SATOSHI
	uint public ETHReceived;    // Number of ETH received
	uint public BTCReceived;    // Number of BTC received
	uint public RLCSentToETH;   // Number of RLC sent to ETH contributors
	uint public RLCSentToBTC;   // Number of RLC sent to BTC contributors
	uint public RLCEmitted;		// Number of RLC emitted
	uint public startBlock;     // Crowdsale start block
	uint public endBlock;       // Crowdsale end block
	uint public minCap;         // Minimum number of RLC to sell
	uint public maxCap;         // Maximum number of RLC to sell
	bool public maxCapReached;  // Max cap has been reached
	uint public minInvestETH;   // Minimum amount to invest
	uint public minInvestBTC;   // Minimum amount to invest
	bool public crowdsaleClosed;// Is crowdsale still on going

	address public bounty;		// address at which the bounty RLC will be sent
	address public reserve; 	// address at which the contingency reserve will be sent
	address public team;		// address at which the team RLC will be sent

	uint public rlc_bounty;		// amount of bounties RLC
	uint public rlc_reserve;	// amount of the contingency reserve
	uint public rlc_team;		// amount of the team RLC

	mapping(address => Backer) public backers; //backersETH indexed by their ETH address
	//mapping(address => BackerBTC) public backersBTC; //backersBTC indexed by their (BTC,ETH) address

    // Auth modifier, if the msg.sender isn't the expected address, throw.
	modifier onlyBy(address a){
	    if (msg.sender != a) throw;
	    _;
	}

	modifier minCapNotReached() {
		if ((now<endBlock) || isMinCapReached() || (now > endBlock + 15 days)) throw;
		_;
	}

	event ReceivedETH(address addr, uint value);
	event ReceivedBTC(address addr, string from, uint value);
	event RefundBTC(string to, uint value);
	event RefundETH(address to, uint value);
	event Logs(address indexed from, uint amount, string value);
	// Constructor of the contract.
	function Crowdsale(address _token, address _btcproxy) {

	  //set the different variables
	  owner = msg.sender;
	  BTCproxy = _btcproxy; // to change
	  //RLC = Token(0x0a8f269d52fad5f0f6297a264f48cbb290c68130); 	// RLC contract address
	  rlc = RLC(_token); 	// RLC contract address
	  multisigETH = 0x8cd6B3D8713df6aA35894c8beA200c27Ebe92550;
	  RLCSentToETH = 0;
	  minInvestETH = 100 finney; // 0.1 ether
	  minInvestBTC = 100000;     // approx 1 USD or 0.00100000 BTC
	  startBlock = now ;            // now (testnet)
	  endBlock =  now + 30 days;    // ever (testnet) startdate + 30 days
	  //RLCPerBTC = 50000000000000;         // 5000 RLC par BTC == 50,000 RLC per satoshi
	  RLCPerETH = 5000000000000;          // FIXME
	  RLCPerSATOSHI = 50000;         // 5000 RLC par BTC == 50,000 RLC per satoshi
	  minCap=12000000000000000;
	  maxCap=60000000000000000;
	  rlc_bounty=1700000000000000;
	  rlc_reserve=17000000000000000;
	  rlc_team=12000000000000000;
	  RLCEmitted = rlc_bounty + rlc_reserve + rlc_team;
	}

	/*
	* The fallback function corresponds to a donation in ETH
	*/
	function() payable	{
	  receiveETH(msg.sender);
	}

	/*
	*	Receives a payment in ETH
	*/
	function receiveETH(address beneficiary) payable {
// TODO check for msg.value coherent ?

	  //don't accept funding under a predefined treshold
	  if (msg.value < minInvestETH) throw;

	  // check if we are in the correct time slot
	  if ((now < startBlock) || (now > endBlock )) throw;

	  //compute the number of RLC to send
	  uint rlcToSend = bonus((msg.value*RLCPerETH)/(1 ether));
	  //uint rlcToSend = bonus((msg.value*RLCPerFINNEY)/(1 finney));

	  // check if we are not reaching the maxCap by accepting this payment
	  if ((rlcToSend + RLCSentToETH + RLCSentToBTC) > maxCap) throw;

	  //update the backer
	  Backer backer = backers[beneficiary];

	  if (!transferRLC(beneficiary, rlcToSend)) throw;     // Do the transfer right now

	  backer.rlcSent = safeAdd(backer.rlcSent, rlcToSend);
	  backer.weiReceived = safeAdd(backer.weiReceived, msg.value); // Update the total wei collcted during the crowdfunding
	  ETHReceived = safeAdd(ETHReceived, msg.value); // Update the total wei collcted during the crowdfunding
	  RLCSentToETH = safeAdd(RLCSentToETH, rlcToSend);

	  emitRLC(rlcToSend);
	  // send the corresponding contribution event
	  ReceivedETH(beneficiary,ETHReceived);
	}

	/*
	* receives a payment in BTC
	*/

	// Refund BTC in JS if function throw

	function receiveBTC(address beneficiary, string btc_address, uint value) onlyBy(BTCproxy){
	  //don't accept funding under a predefined treshold
	  if (value < minInvestBTC) throw;

	  // if we are in the correct time slot
	  if ((now < startBlock) || (now > endBlock )) throw;

	  //compute the number of RLC to send
	  uint rlcToSend = bonus((value*RLCPerSATOSHI));

	  // check if we are not reaching the maxCap
	  if ((rlcToSend + RLCSentToETH + RLCSentToBTC) > maxCap) throw;

	  //update the backer
	  Backer backer = backers[beneficiary];

	  // if the min cap is reached, token transfer happens immediately possibly along
	  // with the previous payment
	  if (!transferRLC(beneficiary, rlcToSend)) throw;     // Do the transfer right now

	  backer.rlcSent = safeAdd(backer.rlcSent , rlcToSend);
	  backer.btc_address = btc_address;
	  backer.satoshiReceived = safeAdd(backer.satoshiReceived, value);
	  BTCReceived =  safeAdd(BTCReceived, value);// Update the total satoshi collcted during the crowdfunding
	  RLCSentToBTC = safeAdd(RLCSentToBTC, rlcToSend);
	  emitRLC(rlcToSend);

	  ReceivedBTC(beneficiary, btc_address, BTCReceived);
	}

	function isMinCapReached() returns (bool) {
		return (RLCSentToETH + RLCSentToBTC ) > minCap;
	}

	function isMaxCapReached() returns (bool) {
		return (RLCSentToETH + RLCSentToBTC ) == maxCap;
	}

	// Compute the variable part
	function emitRLC(uint amount) internal {
		Logs(msg.sender ,amount, "emitRLC");
		rlc_bounty+=amount/10;      // bounty is 10% of the crowdsale
		rlc_team+=amount/20;        // team is 5% of the crowdsale
		rlc_reserve+=amount/10; 	// contingency is 10% of the crowdsale
		RLCEmitted+=amount + amount/4;	// adjust the total number of RLC emitted
	}

	/*
	  Compute the RLC bonus according to the investment period
	*/
	function bonus(uint amount) returns (uint) {
	  if (now < (startBlock + 10 days)) return (amount + amount/5);  // bonus 20%
	  if (now < startBlock + 20 days) return (amount + amount/10);  // bonus 10%
	  return amount;
	}

	/*
	 * Transfer RLC to backers
	 * Assumes that the owner of the token contract and the crowdsale contract is the same
	 */
	function transferRLC(address to, uint amount) internal returns (bool) {
	  return rlc.transfer(to, amount);
	}

	/*
	 * When mincap is not reach backer can call the approveAndCall function of the RLC token contract
	 * whith this crowdsale contract on parameter with all the RLC they get in order to be refund
	 */

    function receiveApproval(address _from, uint256 _value, address _token, string _extraData, string _extraData2) minCapNotReached {
        if (msg.sender != rlc) throw;
        if (bytes(_extraData).length != 0) throw;  // no extradata needed
        if (bytes(_extraData2).length!= 0) throw;  // no extradata needed
        if (_value != backer[_from].rlcSent) throw; // compare value from backer balance
        if (!rlc.transferFrom(_from, address(this), _value)) throw ; // get the token back to the crowdsale contract
		uint ETHToSend = backers[_from].weiReceived;
		backers[_from].weiReceived=0;
		uint BTCToSend = backers[_from].satoshiReceived;
		backers[_from].satoshiReceived = 0;
		if (ETHToSend > 0) {
			if (_from.send(ETHToSend)) {
					RefundETH(_from,ETHToSend);
				} else {
					backers[_from].weiReceived = ETHToSend;
				}
		}
		if (BTCToSend > 0)
			RefundBTC(backersBTC[msg.sender].btc_address ,valueToSend); // event message to manually refund BTC
    }

	/*
	* After the end of the crowdsale let user reclaimed their RLC if minCap has not been reached.
	* It must be sent from the backer address

	function claimRLC() {
		if ((now<endBlock) || isMinCapReached() || (now > endBlock + 15 days)) throw;
		uint amount=backersETH[msg.sender].rlcToSend;
		if (amount !=0 ) {
			backersETH[msg.sender].rlcToSend=0;
			if (!rlc.transfer(msg.sender,amount)) throw;
			//transfer the corresponding amount to the multisig address
			uint weitosend = backersETH[msg.sender].weiReceived;
			backersETH[msg.sender].weiReceived=0;
			if (!multisigETH.send(backersETH[msg.sender].weiReceived)) throw;
		} else {
			amount = backersBTC[msg.sender].rlcToSend;
			backersBTC[msg.sender].rlcToSend=0;
			backersBTC[msg.sender].satoshiReceived=0;
			if (!rlc.transfer(msg.sender,amount)) throw;
		}
	}
	*/

	/*
	* After the end of the crowdsale let user reclaimed their ETH if minCap has not been reached.
	* It must be sent from the backer address

	function claimETH() {
		//check if we are in the correct time frame
		if ((now<endBlock) || isMinCapReached() || (now > endBlock + 15 days)) throw;
		uint valToSend = backersETH[msg.sender].weiReceived;
		backersETH[msg.sender].weiReceived=0;
		backersETH[msg.sender].rlcToSend=0;
		if (!msg.sender.send(valToSend)) throw;
	}
	*/
	/*
	* After the end of the crowdsale let user reclaimetheir BTC if minCap has not been reached.
	* It must be sent from the backer address

	function claimBTC() {
		if ((now<endBlock) || isMinCapReached() || (now > endBlock + 15 days)) throw;
		uint valueToSend = backersBTC[msg.sender].satoshiReceived;
		backersBTC[msg.sender].satoshiReceived=0;
		//reverse sold RLC to the team
		backersETH[msg.sender].rlcToSend=0;
		RefundBTC(backersBTC[msg.sender].btc_address ,valueToSend);
	}
	*/
	/*
	* Update the rate RLC per ETH, computed externally by using the BTCETH index
	*/
	function setRLCPerETH(uint rate) onlyBy(BTCproxy) {
		RLCPerETH=rate;
	}

	/*
	* Finalize the crowdsale, should be called after the refund period
	*/
	function finalize() onlyBy(owner) {
		if ((now > endBlock + 10 days ) && (now < endBlock + 60 days)) throw;
		//moves the remaining ETH to the multisig address
		if (!multisigETH.send(this.balance)) throw;
		//moves RLC to the team, reserve and bounty address
	    if (!transferRLC(team,rlc_team)) throw;
	    if (!transferRLC(reserve,rlc_reserve)) throw;
	    if (!transferRLC(bounty,rlc_bounty)) throw;
	    rlc.burn(rlc.totalSupply() - RLCEmitted);
		crowdsaleClosed = true;
	}
}

pragma solidity ^0.4.8;
import "./SafeMath.sol";
import "./RLC.sol";

/*
  Crowdsale Smart Contract for the iEx.ec project

  This smart contract collects ETH and BTC, and in return emits RLC tokens to the backers

  Thanks to BeyondTheVoid and TokenMarket who helped us shaping this code.

 */

// TODO
// Comment vont faire les gars qui ont investit en BTC avant le min cap pour recuperer leur rlc?
// add lockable to RLC transfer only for owner
// add emergency stop

// TEST:
// test differente timeframe
// test multiple invest
// test claim ETH

contract Crowdsale is SafeMath {

  	struct Backer {
  	  uint weiReceived;	// Amount of ETH given
	  string btc_address;  //store the btc address for full tracability
	  uint satoshiReceived;	// Amount of BTC given
	  uint rlcToSend;   	// rlc to distribute when the min cap is reached
	  uint rlcSent;
	}

	RLC 	public rlc;         // RLC contract reference
	address public owner;       // Contract owner (iEx.ec team)
	address public multisigETH; // Multisig contract that will receive the ETH
	address public BTCproxy;	// addess of the BTC Proxy

	uint public RLCPerETH;      // Number of RLC per ETH
	uint public RLCPerSATOSHI;  // Number of RLC per SATOSHI
	uint public ETHReceived;    // Number of ETH received
	uint public BTCReceived;    // Number of BTC received
	uint public RLCSentToETH;   // Number of RLC sent to ETH contributors
	uint public RLCSentToBTC;   // Number of RLC sent to BTC contributors
	uint public RLCEmitted;		// Number of RLC emitted
	uint public startBlock;     // Crowdsale start block
	uint public endBlock;       // Crowdsale end block
	uint public minCap;         // Minimum number of RLC to sell
	uint public maxCap;         // Maximum number of RLC to sell
	bool public maxCapReached;  // Max cap has been reached
	uint public minInvestETH;   // Minimum amount to invest
	uint public minInvestBTC;   // Minimum amount to invest
	bool public crowdsaleClosed;// Is crowdsale still on going

	address public bounty;		// address at which the bounty RLC will be sent
	address public reserve; 	// address at which the contingency reserve will be sent
	address public team;		// address at which the team RLC will be sent

	uint public rlc_bounty;		// amount of bounties RLC
	uint public rlc_reserve;	// amount of the contingency reserve
	uint public rlc_team;		// amount of the team RLC

	mapping(address => Backer) public backers; //backersETH indexed by their ETH address
	//mapping(address => BackerBTC) public backersBTC; //backersBTC indexed by their (BTC,ETH) address

    // Auth modifier, if the msg.sender isn't the expected address, throw.
	modifier onlyBy(address a){
	    if (msg.sender != a) throw;
	    _;
	}

	modifier minCapNotReached() {
		if ((now<endBlock) || isMinCapReached() || (now > endBlock + 15 days)) throw;
		_;
	}

	event ReceivedETH(address addr, uint value);
	event ReceivedBTC(address addr, string from, uint value);
	event RefundBTC(string to, uint value);
	event Logs(address indexed from, uint amount, string value);
	// Constructor of the contract.
	function Crowdsale(address _token, address _btcproxy) {

	  //set the different variables
	  owner = msg.sender;
	  BTCproxy = _btcproxy; // to change
	  //RLC = Token(0x0a8f269d52fad5f0f6297a264f48cbb290c68130); 	// RLC contract address
	  rlc = RLC(_token); 	// RLC contract address
	  multisigETH = 0x8cd6B3D8713df6aA35894c8beA200c27Ebe92550;
	  RLCSentToETH = 0;
	  minInvestETH = 100 finney; // 0.1 ether
	  minInvestBTC = 100000;     // approx 1 USD or 0.00100000 BTC
	  startBlock = now ;            // now (testnet)
	  endBlock =  now + 30 days;    // ever (testnet) startdate + 30 days
	  //RLCPerBTC = 50000000000000;         // 5000 RLC par BTC == 50,000 RLC per satoshi
	  RLCPerETH = 5000000000000;          // FIXME
	  RLCPerSATOSHI = 50000;         // 5000 RLC par BTC == 50,000 RLC per satoshi
	  minCap=12000000000000000;
	  maxCap=60000000000000000;
	  rlc_bounty=1700000000000000;
	  rlc_reserve=17000000000000000;
	  rlc_team=12000000000000000;
	  RLCEmitted = rlc_bounty + rlc_reserve + rlc_team;
	}

	/*
	* The fallback function corresponds to a donation in ETH
	*/
	function() payable	{
	  receiveETH(msg.sender);
	}

	/*
	*	Receives a payment in ETH
	*/
	function receiveETH(address beneficiary) payable {
// TODO check for msg.value coherent ?

	  //don't accept funding under a predefined treshold
	  if (msg.value < minInvestETH) throw;

	  // check if we are in the correct time slot
	  if ((now < startBlock) || (now > endBlock )) throw;

	  //compute the number of RLC to send
	  uint rlcToSend = bonus((msg.value*RLCPerETH)/(1 ether));
	  //uint rlcToSend = bonus((msg.value*RLCPerFINNEY)/(1 finney));

	  // check if we are not reaching the maxCap by accepting this payment
	  if ((rlcToSend + RLCSentToETH + RLCSentToBTC) > maxCap) throw;

	  //update the backer
	  Backer backer = backers[beneficiary];

	  if (!transferRLC(beneficiary, rlcToSend)) throw;     // Do the transfer right now

	  backer.rlcSent = safeAdd(backer.rlcSent, rlcToSend);
	  backer.weiReceived = safeAdd(backer.weiReceived, msg.value); // Update the total wei collcted during the crowdfunding
	  ETHReceived = safeAdd(ETHReceived, msg.value); // Update the total wei collcted during the crowdfunding
	  RLCSentToETH = safeAdd(RLCSentToETH, rlcToSend);

	  emitRLC(rlcToSend);
	  // send the corresponding contribution event
	  ReceivedETH(beneficiary,ETHReceived);
	}

	/*
	* receives a payment in BTC
	*/

	// Refund BTC in JS if function throw

	function receiveBTC(address beneficiary, string btc_address, uint value) onlyBy(BTCproxy){
	  //don't accept funding under a predefined treshold
	  if (value < minInvestBTC) throw;

	  // if we are in the correct time slot
	  if ((now < startBlock) || (now > endBlock )) throw;

	  //compute the number of RLC to send
	  uint rlcToSend = bonus((value*RLCPerSATOSHI));

	  // check if we are not reaching the maxCap
	  if ((rlcToSend + RLCSentToETH + RLCSentToBTC) > maxCap) throw;

	  //update the backer
	  Backer backer = backers[beneficiary];

	  // if the min cap is reached, token transfer happens immediately possibly along
	  // with the previous payment
	  if (!transferRLC(beneficiary, rlcToSend)) throw;     // Do the transfer right now

	  backer.rlcSent = safeAdd(backer.rlcSent , rlcToSend);
	  backer.btc_address = btc_address;
	  backer.satoshiReceived = safeAdd(backer.satoshiReceived, value);
	  BTCReceived =  safeAdd(BTCReceived, value);// Update the total satoshi collcted during the crowdfunding
	  RLCSentToBTC = safeAdd(RLCSentToBTC, rlcToSend);
	  emitRLC(rlcToSend);

	  ReceivedBTC(beneficiary, btc_address, BTCReceived);
	}

	function isMinCapReached() returns (bool) {
		return (RLCSentToETH + RLCSentToBTC ) > minCap;
	}

	function isMaxCapReached() returns (bool) {
		return (RLCSentToETH + RLCSentToBTC ) == maxCap;
	}

	// Compute the variable part
	function emitRLC(uint amount) internal {
		Logs(msg.sender ,amount, "emitRLC");
		rlc_bounty+=amount/10;      // bounty is 10% of the crowdsale
		rlc_team+=amount/20;        // team is 5% of the crowdsale
		rlc_reserve+=amount/10; 	// contingency is 10% of the crowdsale
		RLCEmitted+=amount + amount/4;	// adjust the total number of RLC emitted
	}

	/*
	  Compute the RLC bonus according to the investment period
	*/
	function bonus(uint amount) returns (uint) {
	  if (now < (startBlock + 10 days)) return (amount + amount/5);  // bonus 20%
	  if (now < startBlock + 20 days) return (amount + amount/10);  // bonus 10%
	  return amount;
	}

	/*
	 * Transfer RLC to backers
	 * Assumes that the owner of the token contract and the crowdsale contract is the same
	 */
	function transferRLC(address to, uint amount) internal returns (bool) {
	  return rlc.transfer(to, amount);
	}

	/*
	 * When mincap is not reach backer can call the approveAndCall function of the RLC token contract
	 * whith this crowdsale contract on parameter with all the RLC they get in order to be refund
	 */

    function receiveApproval(address _from, uint256 _value, address _token, string _extraData, string _extraData2) minCapNotReached {
        if (msg.sender != rlc) throw;
        if (bytes(_extraData).length != 0) throw;  // no extradata needed
        if (bytes(_extraData2).length!= 0) throw;  // no extradata needed
        if (_value != backer[_from].rlcSent) throw; // compare value from backer balance
        if (!rlc.transferFrom(_from, this, _value)) throw ; // get the token back to the crowdsale contract
		uint ETHToSend = backers[_from].weiReceived;
		backers[_from].weiReceived=0;
		uint BTCToSend = backers[_from].satoshiReceived;
		backers[_from].satoshiReceived = 0;
		if (!_from.send(ETHToSend)) throw;
		if (BTCToSend > 0)
			RefundBTC(backersBTC[msg.sender].btc_address ,valueToSend); // event message to manually refund BTC
    }

	/*
	* After the end of the crowdsale let user reclaimed their RLC if minCap has not been reached.
	* It must be sent from the backer address

	function claimRLC() {
		if ((now<endBlock) || isMinCapReached() || (now > endBlock + 15 days)) throw;
		uint amount=backersETH[msg.sender].rlcToSend;
		if (amount !=0 ) {
			backersETH[msg.sender].rlcToSend=0;
			if (!rlc.transfer(msg.sender,amount)) throw;
			//transfer the corresponding amount to the multisig address
			uint weitosend = backersETH[msg.sender].weiReceived;
			backersETH[msg.sender].weiReceived=0;
			if (!multisigETH.send(backersETH[msg.sender].weiReceived)) throw;
		} else {
			amount = backersBTC[msg.sender].rlcToSend;
			backersBTC[msg.sender].rlcToSend=0;
			backersBTC[msg.sender].satoshiReceived=0;
			if (!rlc.transfer(msg.sender,amount)) throw;
		}
	}
	*/

	/*
	* After the end of the crowdsale let user reclaimed their ETH if minCap has not been reached.
	* It must be sent from the backer address

	function claimETH() {
		//check if we are in the correct time frame
		if ((now<endBlock) || isMinCapReached() || (now > endBlock + 15 days)) throw;
		uint valToSend = backersETH[msg.sender].weiReceived;
		backersETH[msg.sender].weiReceived=0;
		backersETH[msg.sender].rlcToSend=0;
		if (!msg.sender.send(valToSend)) throw;
	}
	*/
	/*
	* After the end of the crowdsale let user reclaimetheir BTC if minCap has not been reached.
	* It must be sent from the backer address

	function claimBTC() {
		if ((now<endBlock) || isMinCapReached() || (now > endBlock + 15 days)) throw;
		uint valueToSend = backersBTC[msg.sender].satoshiReceived;
		backersBTC[msg.sender].satoshiReceived=0;
		//reverse sold RLC to the team
		backersETH[msg.sender].rlcToSend=0;
		RefundBTC(backersBTC[msg.sender].btc_address ,valueToSend);
	}
	*/
	/*
	* Update the rate RLC per ETH, computed externally by using the BTCETH index
	*/
	function setRLCPerETH(uint rate) onlyBy(BTCproxy) {
		RLCPerETH=rate;
	}

	/*
	* Finalize the crowdsale, should be called after the refund period
	*/
	function finalize() onlyBy(owner) {
		if ((now > endBlock + 10 days ) && (now < endBlock + 60 days)) throw;
		//moves the remaining ETH to the multisig address
		if (!multisigETH.send(this.balance)) throw;
		//moves RLC to the team, reserve and bounty address
	    if (!transferRLC(team,rlc_team)) throw;
	    if (!transferRLC(reserve,rlc_reserve)) throw;
	    if (!transferRLC(bounty,rlc_bounty)) throw;
	    rlc.burn(rlc.totalSupply() - RLCEmitted);
		crowdsaleClosed = true;
	}
}


rollback Migration.sol

rollback Migration.sol

pragma solidity ^0.4.4;

contract Migrations {
    address public owner;
    uint public last_completed_migration;

    modifier restricted() {
        if (msg.sender == owner) _;
    }

    function Migrations() {
        owner = msg.sender;
    }

    function setCompleted(uint completed) restricted {
        last_completed_migration = completed;
    }

    function upgrade(address new_address) restricted {
        Migrations upgraded = Migrations(new_address);
        upgraded.setCompleted(last_completed_migration);
    }
}

error: pathspec 'contracts/Migration.sol' did not match any file(s) known to git


Make registry function public so that they appear in the abi

pragma solidity ^0.4.8;

import "./lib/Owned.sol";

contract Registery is Owned {

  mapping (string => address) registery;

  function register(string name, address addr) public owner_only {
    registery[name] = addr;
  }

  function remove(string name) public owner_only {
    delete registery[name];
  }

  function lookup(string name) constant public returns (address) {
    return registery[name];
  }

}

pragma solidity ^0.4.8;

import "./lib/Owned.sol";

contract Registery is Owned {

  mapping (string => address) registery;

  function register(string name, address addr) external owner_only {
    registery[name] = addr;
  }

  function remove(string name) external owner_only {
    delete registery[name];
  }

  function lookup(string name) constant external returns (address) {
    return registery[name];
  }

}