fix Project contructor

fix Project contructor

pragma solidity ^0.4.11;

import 'zeppelin-solidity/contracts/ownership/Ownable.sol';
import 'zeppelin-solidity/contracts/math/SafeMath.sol';
import 'zeppelin-solidity/contracts/token/ERC20.sol';

import "./impact/ImpactRegistry.sol";
import "../ContractProvider.sol";

contract Project is Ownable {
    using SafeMath for uint256;

    string public name;
    address public judgeAddress;
    address public beneficiaryAddress;
    address public IMPACT_REGISTRY_ADDRESS;
    address public CONTRACT_PROVIDER_ADDRESS;

    /* This creates a map with donations per user */
    mapping (address => uint) accountBalances;

    /* Additional structure to help to iterate over donations */
    address[] accountIndex;

    /* Total amount of all of the donations */
    uint public total;

    /* This generates a public event on the blockchain that will notify clients */
    event OutcomeEvent(string id, uint value);
    event DonationEvent(address indexed from, uint value);

    function Project(string _name) {
        name = _name;
    }

    function setJudge(address _judgeAddress) onlyOwner {
        judgeAddress = _judgeAddress;
    }

    function setBeneficiary(address _beneficiaryAddress) onlyOwner {
        beneficiaryAddress = _beneficiaryAddress;
    }

    function setImpactRegistry(address impactRegistryAddress) onlyOwner {
        IMPACT_REGISTRY_ADDRESS = impactRegistryAddress;
    }

    function setContractProvider(address _contractProvider) onlyOwner {
        CONTRACT_PROVIDER_ADDRESS = _contractProvider;
    }

    function notify(address _from, uint _amount) onlyOwner {
        registerDonation(_from, _amount);
    }

    function registerDonation(address _from, uint _amount) internal {
        total = total.add(_amount);
        ImpactRegistry(IMPACT_REGISTRY_ADDRESS).registerDonation(_from, _amount);
        DonationEvent(_from, _amount);
    }

    function donateFromWallet(ERC20 _token, uint _amount) {
        _token.transferFrom(msg.sender, address(this), _amount);
        registerDonation(msg.sender, _amount);
    }

    function fund(uint _value) onlyOwner {
        total = total.add(_value);
    }

    function unlockOutcome(string _name, uint _value) {
        require (msg.sender == judgeAddress);
        require (_value <= total);

        address tokenAddress = ContractProvider(CONTRACT_PROVIDER_ADDRESS).contracts("digitalGBP");
        ERC20(tokenAddress).transfer(beneficiaryAddress, _value);
        total = total.sub(_value);

        ImpactRegistry(IMPACT_REGISTRY_ADDRESS).registerOutcome(_name, _value);

        OutcomeEvent(_name, _value);
    }

    function payBack(address account) onlyOwner {
        uint balance = getBalance(account);
        if (balance > 0) {
            address tokenAddress = ContractProvider(CONTRACT_PROVIDER_ADDRESS).contracts("digitalGBP");
            ERC20(tokenAddress).transfer(account, balance);
            total = total.sub(accountBalances[account]);
            ImpactRegistry(IMPACT_REGISTRY_ADDRESS).payBack(account);
        }
    }

    function getBalance(address donor) constant returns(uint) {
        return ImpactRegistry(IMPACT_REGISTRY_ADDRESS).getBalance(donor);
    }

    /* Extra security measure to save funds in case of critical error or attack */
    function escape(address escapeAddress) onlyOwner {
        address tokenAddress = ContractProvider(CONTRACT_PROVIDER_ADDRESS).contracts("digitalGBP");
        ERC20(tokenAddress).transfer(escapeAddress, total);
        total = 0;
    }
}

pragma solidity ^0.4.11;

import 'zeppelin-solidity/contracts/ownership/Ownable.sol';
import 'zeppelin-solidity/contracts/math/SafeMath.sol';
import 'zeppelin-solidity/contracts/token/ERC20.sol';

import "./impact/ImpactRegistry.sol";
import "../ContractProvider.sol";

contract Project is Ownable {
    using SafeMath for uint256;

    string public name;
    address public judgeAddress;
    address public beneficiaryAddress;
    address public IMPACT_REGISTRY_ADDRESS;
    address public CONTRACT_PROVIDER_ADDRESS;

    /* This creates a map with donations per user */
    mapping (address => uint) accountBalances;

    /* Additional structure to help to iterate over donations */
    address[] accountIndex;

    /* Total amount of all of the donations */
    uint public total;

    /* This generates a public event on the blockchain that will notify clients */
    event OutcomeEvent(string id, uint value);
    event DonationEvent(address indexed from, uint value);

    function Charity(string _name) {
        name = _name;
    }

    function setJudge(address _judgeAddress) onlyOwner {
        judgeAddress = _judgeAddress;
    }

    function setBeneficiary(address _beneficiaryAddress) onlyOwner {
        beneficiaryAddress = _beneficiaryAddress;
    }

    function setImpactRegistry(address impactRegistryAddress) onlyOwner {
        IMPACT_REGISTRY_ADDRESS = impactRegistryAddress;
    }

    function setContractProvider(address _contractProvider) onlyOwner {
        CONTRACT_PROVIDER_ADDRESS = _contractProvider;
    }

    function notify(address _from, uint _amount) onlyOwner {
        registerDonation(_from, _amount);
    }

    function registerDonation(address _from, uint _amount) internal {
        total = total.add(_amount);
        ImpactRegistry(IMPACT_REGISTRY_ADDRESS).registerDonation(_from, _amount);
        DonationEvent(_from, _amount);
    }

    function donateFromWallet(ERC20 _token, uint _amount) {
        _token.transferFrom(msg.sender, address(this), _amount);
        registerDonation(msg.sender, _amount);
    }

    function fund(uint _value) onlyOwner {
        total = total.add(_value);
    }

    function unlockOutcome(string _name, uint _value) {
        require (msg.sender == judgeAddress);
        require (_value <= total);

        address tokenAddress = ContractProvider(CONTRACT_PROVIDER_ADDRESS).contracts("digitalGBP");
        ERC20(tokenAddress).transfer(beneficiaryAddress, _value);
        total = total.sub(_value);

        ImpactRegistry(IMPACT_REGISTRY_ADDRESS).registerOutcome(_name, _value);

        OutcomeEvent(_name, _value);
    }

    function payBack(address account) onlyOwner {
        uint balance = getBalance(account);
        if (balance > 0) {
            address tokenAddress = ContractProvider(CONTRACT_PROVIDER_ADDRESS).contracts("digitalGBP");
            ERC20(tokenAddress).transfer(account, balance);
            total = total.sub(accountBalances[account]);
            ImpactRegistry(IMPACT_REGISTRY_ADDRESS).payBack(account);
        }
    }

    function getBalance(address donor) constant returns(uint) {
        return ImpactRegistry(IMPACT_REGISTRY_ADDRESS).getBalance(donor);
    }

    /* Extra security measure to save funds in case of critical error or attack */
    function escape(address escapeAddress) onlyOwner {
        address tokenAddress = ContractProvider(CONTRACT_PROVIDER_ADDRESS).contracts("digitalGBP");
        ERC20(tokenAddress).transfer(escapeAddress, total);
        total = 0;
    }
}


Add value of Ether to transfer to eval()

import "BulletinBoard.sol";

/**
 * This contract performs an "eval" on arbitrary contracts but only with the
 * consent of all participants named.
 */
contract UnanimousConsent {

	enum ConsentState {
		NONE,
		CONSENTED,
		EXECUTED
	}

	// Records the current state of consent for a given hash and address
	mapping (bytes32 =>
			mapping (address => ConsentState)) consentStates;

	// Holds all of the participants in the current UnanimousConsent contract
	address[] participants;

	// Holds the BulletinBoard for counterfactual addressing
	BulletinBoard public bulletinBoard;

	modifier onlySelf {
		if (msg.sender == address(this)) {
			_
		} else {
			throw;
		}
	}

	/**
	 * Creates a new UnanimousConsent contract.
	 *
	 * _participants: The initial participants in the contract
	 */
	function UnanimousConsent(address[] _participants) {
		participants = _participants;
		bulletinBoard = new BulletinBoard(this);
	}

	/**
	 * Evaluates arbitrary functions of contracts, but only with universal
	 * consent. Note that any `eval` sub-calls should `throw` in the event that
	 * there is a contract execution failure (such as if a precondition isn't
	 * met or if a verification of some sort fails) to prevent this call from
	 * finishing.
	 *
	 * _calledContracts: The addresses of the called contracts
	 * _methodSignatures: The method signatures of the functions
	 * _argumentLengths: The lengths of the arguments for each function call
	 * _arguments: The arguments of all function calls concatenated
	 * _values: Amount of Ether to send for each respective call
	 */
	function eval(
		address[] _calledContracts,
		bytes4[] _methodSignatures,
		uint[] _argumentLengths,
		bytes32[] _arguments,
		uint[] _values
	) {
		if (
			_calledContracts.length != _methodSignatures.length ||
			_calledContracts.length != _argumentLengths.length ||
			_calledContracts.length != _values.length
		) {
			throw;
		}

		uint i;
		uint j;
		bytes32 hash = sha3(_calledContracts, _methodSignatures, _argumentLengths, _arguments, _values);

		for (i = 0; i < participants.length; i++) {
			if (consentStates[hash][participants[i]] == ConsentState.CONSENTED) {
				consentStates[hash][participants[i]] = ConsentState.EXECUTED;
			} else {
				throw;
			}
		}

		uint argumentsIndex = 0;
		for (i = 0; i < _calledContracts.length; i++) {

			bytes32[] memory arguments = new bytes32[](_argumentLengths[i]);
			for (j = 0; j < _argumentLengths[i]; j++) {
				arguments[j] = _arguments[argumentsIndex++];
			}

			if (!_calledContracts[i].call.value(_values[i])(_methodSignatures[i], arguments[i])) {
				throw;
			}
		}
	}

	/**
	 * Provides consent for the hash of an execution call for the sender of the
	 * message.
	 *
	 * _hash: The hash of the execution call
	 *
	 * returns: `true` if successful, otherwise `false`
	 */
	function consent(bytes32 _hash) returns (bool) {
		if (consentStates[_hash][msg.sender] == ConsentState.NONE) {
			consentStates[_hash][msg.sender] = ConsentState.CONSENTED;
			return true;
		} else {
			return false;
		}
	}

	/**
	 * Sends the Ether stored in the currenct contract. Intended to only be
	 * called by this contract's `eval`.
	 *
	 * _recipient: The recipient of the Ether.
	 * _amount: The amount of Ether to send.
	 */
	function sendEther(address _recipient, uint _amount) external onlySelf {
		if (!_recipient.send(_amount)) {
			throw;
		}
	}

	/**
	 * Changes the participants in the current contract. Intended to only be
	 * called by this contract's `eval`.
	 *
	 * _participants: The new participants in the contract
	 */
	function changeParticipants(address[] _participants) external onlySelf {
		participants = _participants;
	}

	/**
	 * Cleans up previously approved consents. Intended to only be called by
	 * this contract's `eval`.
	 *
	 * _hashes: The list of hashes to clean
	 * _participants: The list of address whose hashes should be cleaned
	 */
	function clean(bytes32[] _hashes, address[] _participants) external onlySelf {
		for (uint i = 0; i < _hashes.length; i++) {
			for (uint j = 0; j < _participants.length; j++) {
				delete consentStates[_hashes[i]][_participants[j]];
			}
		}
	}

	/**
	 * Kills the current contract. Intended to only be called by this contract's
	 * eval.
	 *
	 * _recipient: The recipient of funds from the `selfdestruct` call
	 */
	function kill(address _recipient) external onlySelf {
		selfdestruct(_recipient);
	}
}

import "BulletinBoard.sol";

/**
 * This contract performs an "eval" on arbitrary contracts but only with the
 * consent of all participants named.
 */
contract UnanimousConsent {

	enum ConsentState {
		NONE,
		CONSENTED,
		EXECUTED
	}

	// Records the current state of consent for a given hash and address
	mapping (bytes32 =>
			mapping (address => ConsentState)) consentStates;

	// Holds all of the participants in the current UnanimousConsent contract
	address[] participants;

	// Holds the BulletinBoard for counterfactual addressing
	BulletinBoard public bulletinBoard;

	modifier onlySelf {
		if (msg.sender == address(this)) {
			_
		} else {
			throw;
		}
	}

	/**
	 * Creates a new UnanimousConsent contract.
	 *
	 * _participants: The initial participants in the contract
	 */
	function UnanimousConsent(address[] _participants) {
		participants = _participants;
		bulletinBoard = new BulletinBoard(this);
	}

	/**
	 * Evaluates arbitrary functions of contracts, but only with universal
	 * consent. Note that any `eval` sub-calls should `throw` in the event that
	 * there is a contract execution failure (such as if a precondition isn't
	 * met or if a verification of some sort fails) to prevent this call from
	 * finishing.
	 *
	 * _calledContracts: The addresses of the called contracts
	 * _methodSignatures: The method signatures of the functions
	 * _argumentLengths: The lengths of the arguments for each function call
	 * _arguments: The arguments of all function calls concatenated
	 */
	function eval(
		address[] _calledContracts,
		bytes4[] _methodSignatures,
		uint[] _argumentLengths,
		bytes32[] _arguments
	) {
		if (
			_calledContracts.length != _methodSignatures.length ||
			_calledContracts.length != _argumentLengths.length
		) {
			throw;
		}

		uint i;
		uint j;
		bytes32 hash = sha3(_calledContracts, _methodSignatures, _argumentLengths, _arguments);

		for (i = 0; i < participants.length; i++) {
			if (consentStates[hash][participants[i]] == ConsentState.CONSENTED) {
				consentStates[hash][participants[i]] = ConsentState.EXECUTED;
			} else {
				throw;
			}
		}

		uint argumentsIndex = 0;
		for (i = 0; i < _calledContracts.length; i++) {

			bytes32[] memory arguments = new bytes32[](_argumentLengths[i]);
			for (j = 0; j < _argumentLengths[i]; j++) {
				arguments[j] = _arguments[argumentsIndex++];
			}

			if (!_calledContracts[i].call(_methodSignatures[i], arguments[i])) {
				throw;
			}
		}
	}

	/**
	 * Provides consent for the hash of an execution call for the sender of the
	 * message.
	 *
	 * _hash: The hash of the execution call
	 *
	 * returns: `true` if successful, otherwise `false`
	 */
	function consent(bytes32 _hash) returns (bool) {
		if (consentStates[_hash][msg.sender] == ConsentState.NONE) {
			consentStates[_hash][msg.sender] = ConsentState.CONSENTED;
			return true;
		} else {
			return false;
		}
	}

	/**
	 * Sends the Ether stored in the currenct contract. Intended to only be
	 * called by this contract's `eval`.
	 *
	 * _recipient: The recipient of the Ether.
	 * _amount: The amount of Ether to send.
	 */
	function sendEther(address _recipient, uint _amount) external onlySelf {
		if (!_recipient.send(_amount)) {
			throw;
		}
	}

	/**
	 * Changes the participants in the current contract. Intended to only be
	 * called by this contract's `eval`.
	 *
	 * _participants: The new participants in the contract
	 */
	function changeParticipants(address[] _participants) external onlySelf {
		participants = _participants;
	}

	/**
	 * Cleans up previously approved consents. Intended to only be called by
	 * this contract's `eval`.
	 *
	 * _hashes: The list of hashes to clean
	 * _participants: The list of address whose hashes should be cleaned
	 */
	function clean(bytes32[] _hashes, address[] _participants) external onlySelf {
		for (uint i = 0; i < _hashes.length; i++) {
			for (uint j = 0; j < _participants.length; j++) {
				delete consentStates[_hashes[i]][_participants[j]];
			}
		}
	}

	/**
	 * Kills the current contract. Intended to only be called by this contract's
	 * eval.
	 *
	 * _recipient: The recipient of funds from the `selfdestruct` call
	 */
	function kill(address _recipient) external onlySelf {
		selfdestruct(_recipient);
	}
}


Fix incorrect action checking semantics

Fix incorrect action checking semantics

import "BulletinBoard.sol";

/**
 * This contract performs an "eval" on arbitrary contracts but only with the
 * consent of all participants named.
 */
contract UnanimousConsent {

	enum ConsentState {
		NONE,
		CONSENTED,
		EXECUTED
	}

	struct Action {
		address target;
		uint value;
		bytes calldata;
		bool initialized;
	}

	// Records the current state of consent for a given hash and address
	mapping (bytes32 =>
			mapping (address => ConsentState)) consentStates;

	// Contains all of the sent execution actions
	mapping (bytes32 => Action) actions;

	// Holds all of the participants in the current UnanimousConsent contract
	address[] participants;

	// Holds the BulletinBoard for counterfactual addressing
	BulletinBoard public bulletinBoard;

	modifier onlySelf {
		if (msg.sender == address(this)) {
			_
		} else {
			throw;
		}
	}

	/**
	 * Creates a new UnanimousConsent contract.
	 *
	 * _participants: The initial participants in the contract
	 */
	function UnanimousConsent(address[] _participants) {
		participants = _participants;
		bulletinBoard = new BulletinBoard(this);
	}

	/**
	 * Adds an `Action` to potentially be executed.
	 *
	 * _target: The target of the execution call
	 * _value: The amount of Ether to send
	 * _calldata: The calldata associated with the call
	 */
	function addAction(address _target, uint _value, bytes _calldata) external {
		Action memory action = Action(_target, _value, _calldata, true);
		actions[sha3(action)] = action;// hashing a struct is broken
	}

	/**
	 * Evaluates arbitrary functions of contracts, but only with universal
	 * consent. Note that any `eval` sub-calls should `throw` in the event that
	 * there is a contract execution failure (such as if a precondition isn't
	 * met or if a verification of some sort fails) to prevent this call from
	 * finishing.
	 *
	 * _actionHashes: The hashes of the `Action` that have been submitted
	 */
	function eval(bytes32[] _actionHashes) {
		uint i;
		bytes32 hash = sha3(_actionHashes);

		for (i = participants.length; i > 0; i--) {
			if (consentStates[hash][participants[i-1]] == ConsentState.CONSENTED) {
				consentStates[hash][participants[i-1]] = ConsentState.EXECUTED;
			} else {
				throw;
			}
		}

		for (i = 0; i < _actionHashes.length; i++) {
			Action memory action = actions[_actionHashes[i]];
			if (!(action.initialized && action.target.call.value(action.value)(action.calldata))) {
				throw;
			}
		}
	}

	/**
	 * Provides consent for the hash of an execution call for the sender of the
	 * message.
	 *
	 * _hash: The hash of the execution call
	 *
	 * returns: `true` if successful, otherwise `false`
	 */
	function consent(bytes32 _hash) returns (bool) {
		if (consentStates[_hash][msg.sender] == ConsentState.NONE) {
			consentStates[_hash][msg.sender] = ConsentState.CONSENTED;
			return true;
		} else {
			return false;
		}
	}

	/**
	 * Changes the participants in the current contract. Intended to only be
	 * called by this contract's `eval`.
	 *
	 * _participants: The new participants in the contract
	 */
	function changeParticipants(address[] _participants) external onlySelf {
		participants = _participants;
	}

	/**
	 * Removes a group of `Action` that have been submitted. Intended to be
	 * called by this contract's `eval`.
	 *
	 * _actionHashes: The hashes of the `Action` that have been submitted
	 */
	function cleanActions(bytes32[] _actionHashes) external onlySelf {
		for (uint i = _actionHashes.length; i > 0; i--) {
			delete actions[_actionHashes[i-1]];
		}
	}

	/**
	 * Cleans up previously approved consents. Intended to only be called by
	 * this contract's `eval`.
	 *
	 * _hashes: The list of hashes to clean
	 * _participants: The list of address whose hashes should be cleaned
	 */
	function clean(bytes32[] _hashes, address[] _participants) external onlySelf {
		for (uint i = _hashes.length; i > 0; i--) {
			for (uint j = _participants.length; j > 0; j--) {
				delete consentStates[_hashes[i-1]][_participants[j-1]];
			}
		}
	}

	/**
	 * Kills the current contract. Intended to only be called by this contract's
	 * eval.
	 *
	 * _recipient: The recipient of funds from the `selfdestruct` call
	 */
	function kill(address _recipient) external onlySelf {
		selfdestruct(_recipient);
	}
}

import "BulletinBoard.sol";

/**
 * This contract performs an "eval" on arbitrary contracts but only with the
 * consent of all participants named.
 */
contract UnanimousConsent {

	enum ConsentState {
		NONE,
		CONSENTED,
		EXECUTED
	}

	struct Action {
		address target;
		uint value;
		bytes calldata;
		bool initialized;
	}

	// Records the current state of consent for a given hash and address
	mapping (bytes32 =>
			mapping (address => ConsentState)) consentStates;

	// Contains all of the sent execution actions
	mapping (bytes32 => Action) actions;

	// Holds all of the participants in the current UnanimousConsent contract
	address[] participants;

	// Holds the BulletinBoard for counterfactual addressing
	BulletinBoard public bulletinBoard;

	modifier onlySelf {
		if (msg.sender == address(this)) {
			_
		} else {
			throw;
		}
	}

	/**
	 * Creates a new UnanimousConsent contract.
	 *
	 * _participants: The initial participants in the contract
	 */
	function UnanimousConsent(address[] _participants) {
		participants = _participants;
		bulletinBoard = new BulletinBoard(this);
	}

	/**
	 * Adds an `Action` to potentially be executed.
	 *
	 * _target: The target of the execution call
	 * _value: The amount of Ether to send
	 * _calldata: The calldata associated with the call
	 */
	function addAction(address _target, uint _value, bytes _calldata) external {
		Action memory action = Action(_target, _value, _calldata, true);
		actions[sha3(action)] = action;// hashing a struct is broken
	}

	/**
	 * Evaluates arbitrary functions of contracts, but only with universal
	 * consent. Note that any `eval` sub-calls should `throw` in the event that
	 * there is a contract execution failure (such as if a precondition isn't
	 * met or if a verification of some sort fails) to prevent this call from
	 * finishing.
	 *
	 * _actionHashes: The hashes of the `Action` that have been submitted
	 */
	function eval(bytes32[] _actionHashes) {
		uint i;
		bytes32 hash = sha3(_actionHashes);

		for (i = participants.length; i > 0; i--) {
			if (consentStates[hash][participants[i-1]] == ConsentState.CONSENTED) {
				consentStates[hash][participants[i-1]] = ConsentState.EXECUTED;
			} else {
				throw;
			}
		}

		for (i = 0; i < _actionHashes.length; i++) {
			Action memory action = actions[_actionHashes[i]];
			if (action.initialized && !action.target.call.value(action.value)(action.calldata)) {
				throw;
			}
		}
	}

	/**
	 * Provides consent for the hash of an execution call for the sender of the
	 * message.
	 *
	 * _hash: The hash of the execution call
	 *
	 * returns: `true` if successful, otherwise `false`
	 */
	function consent(bytes32 _hash) returns (bool) {
		if (consentStates[_hash][msg.sender] == ConsentState.NONE) {
			consentStates[_hash][msg.sender] = ConsentState.CONSENTED;
			return true;
		} else {
			return false;
		}
	}

	/**
	 * Changes the participants in the current contract. Intended to only be
	 * called by this contract's `eval`.
	 *
	 * _participants: The new participants in the contract
	 */
	function changeParticipants(address[] _participants) external onlySelf {
		participants = _participants;
	}

	/**
	 * Removes a group of `Action` that have been submitted. Intended to be
	 * called by this contract's `eval`.
	 *
	 * _actionHashes: The hashes of the `Action` that have been submitted
	 */
	function cleanActions(bytes32[] _actionHashes) external onlySelf {
		for (uint i = _actionHashes.length; i > 0; i--) {
			delete actions[_actionHashes[i-1]];
		}
	}

	/**
	 * Cleans up previously approved consents. Intended to only be called by
	 * this contract's `eval`.
	 *
	 * _hashes: The list of hashes to clean
	 * _participants: The list of address whose hashes should be cleaned
	 */
	function clean(bytes32[] _hashes, address[] _participants) external onlySelf {
		for (uint i = _hashes.length; i > 0; i--) {
			for (uint j = _participants.length; j > 0; j--) {
				delete consentStates[_hashes[i-1]][_participants[j-1]];
			}
		}
	}

	/**
	 * Kills the current contract. Intended to only be called by this contract's
	 * eval.
	 *
	 * _recipient: The recipient of funds from the `selfdestruct` call
	 */
	function kill(address _recipient) external onlySelf {
		selfdestruct(_recipient);
	}
}


Update GenericMock

Update GenericMock

pragma solidity ^0.4.17;

/*
 * @title A mock contract that can set/return mock values and execute functions
 * on target contracts
 */
contract GenericMock {
    struct MockValue {
        uint256 uint256Value;
        bytes32 bytes32Value;
        bool boolValue;
        MockValueType valueType;
        bool set;
    }

    enum MockValueType { Uint256, Bytes32, Bool }

    // Track function selectors and mapped mock values
    mapping (bytes4 => MockValue) mockValues;

    /*
     * @dev Call a function on a target address using provided calldata for a function
     * @param _target Target contract to call with data
     * @param _data Transaction data to be used to call the target contract
     */
    function execute(address _target, bytes _data) external returns (bool) {
        return _target.call(_data);
    }

    /*
     * @dev Set a mock uint256 value for a function
     * @param _func Function selector (bytes4(keccak256(FUNCTION_SIGNATURE)))
     * @param _value Mock uint256 value
     */
    function setMockUint256(bytes4 _func, uint256 _value) external returns (bool) {
        mockValues[_func].valueType = MockValueType.Uint256;
        mockValues[_func].uint256Value = _value;
        mockValues[_func].set = true;
    }

    /*
     * @dev Set a mock bytes32 value for a function
     * @param _func Function selector (bytes4(keccak256(FUNCTION_SIGNATURE)))
     * param _value Mock bytes32 value
     */
    function setMockBytes32(bytes4 _func, bytes32 _value) external {
        mockValues[_func].valueType = MockValueType.Bytes32;
        mockValues[_func].bytes32Value = _value;
        mockValues[_func].set = true;
    }

    /*
     * @dev Set a mock bool value for a function
     * @param _func Function selector (bytes4(keccak256(FUNCTION_SIGNATURE)))
     * @param _value Mock bool value
     */
    function setMockBool(bytes4 _func, bool _value) external {
        mockValues[_func].valueType = MockValueType.Bool;
        mockValues[_func].boolValue = _value;
        mockValues[_func].set = true;
    }

    /*
     * @dev Return mock value for a functione
     */
    function() public {
        bytes4 func;
        assembly { func := calldataload(0) }

        if (!mockValues[func].set) {
            // If mock value not set, default to return a bool with value false
            mLoadAndReturn(false);
        } else {
            if (mockValues[func].valueType == MockValueType.Uint256) {
                mLoadAndReturn(mockValues[func].uint256Value);
            } else if (mockValues[func].valueType == MockValueType.Bytes32) {
                mLoadAndReturn(mockValues[func].bytes32Value);
            } else if (mockValues[func].valueType == MockValueType.Bool) {
                mLoadAndReturn(mockValues[func].boolValue);
            }
        }
    }

    /*
     * @dev Load a uint256 value into memory and return it
     * @param _value Uint256 value
     */
    function mLoadAndReturn(uint256 _value) private pure {
        assembly {
            let memOffset := mload(0x40)
            mstore(0x40, add(memOffset, 32))
            mstore(memOffset, _value)
            return(memOffset, 32)
        }
    }

    /*
     * @dev Load a bytes32 value into memory and return it
     * @param _value Bytes32 value
     */
    function mLoadAndReturn(bytes32 _value) private pure {
        assembly {
            let memOffset := mload(0x40)
            mstore(0x40, add(memOffset, 32))
            mstore(memOffset, _value)
            return(memOffset, 32)
        }
    }

    /*
     * @dev Load a bool value into memory and return it
     * @param _value Bool value
     */
    function mLoadAndReturn(bool _value) private pure {
        assembly {
            let memOffset := mload(0x40)
            mstore(0x40, add(memOffset, 32))
            mstore(memOffset, _value)
            return(memOffset, 32)
        }
    }
}

pragma solidity ^0.4.17;

/*
 * @title A mock contract that can set/return mock values and execute functions
 * on target contracts
 */
contract GenericMock {
    struct MockValue {
        uint256 uint256Value;
        bytes32 bytes32Value;
        bool boolValue;
        MockValueType valueType;
    }

    enum MockValueType { Uint256, Bytes32, Bool, None }

    // Track function selectors and mapped mock values
    mapping (bytes4 => MockValue) mockValues;

    /*
     * @dev Call a function on a target address using provided calldata for a function
     * @param _target Target contract to call with data
     * @param _data Transaction data to be used to call the target contract
     */
    function execute(address _target, bytes _data) external returns (bool) {
        return _target.call(_data);
    }

    /*
     * @dev Set a mock uint256 value for a function
     * @param _func Function selector (bytes4(keccak256(FUNCTION_SIGNATURE)))
     * @param _value Mock uint256 value
     */
    function setMockUint256(bytes4 _func, uint256 _value) external returns (bool) {
        mockValues[_func].valueType = MockValueType.Uint256;
        mockValues[_func].uint256Value = _value;
    }

    /*
     * @dev Set a mock bytes32 value for a function
     * @param _func Function selector (bytes4(keccak256(FUNCTION_SIGNATURE)))
     * param _value Mock bytes32 value
     */
    function setMockBytes32(bytes4 _func, bytes32 _value) external {
        mockValues[_func].valueType = MockValueType.Bytes32;
        mockValues[_func].bytes32Value = _value;
    }

    /*
     * @dev Set a mock bool value for a function
     * @param _func Function selector (bytes4(keccak256(FUNCTION_SIGNATURE)))
     * @param _value Mock bool value
     */
    function setMockBool(bytes4 _func, bool _value) external {
        mockValues[_func].valueType = MockValueType.Bool;
        mockValues[_func].boolValue = _value;
    }

    /*
     * @dev Return mock value for a functione
     */
    function() public {
        bytes4 func;
        assembly { func := calldataload(0) }

        if (mockValues[func].valueType == MockValueType.Uint256) {
            mLoadAndReturn(mockValues[func].uint256Value);
        } else if (mockValues[func].valueType == MockValueType.Bytes32) {
            mLoadAndReturn(mockValues[func].bytes32Value);
        } else if (mockValues[func].valueType == MockValueType.Bool) {
            mLoadAndReturn(mockValues[func].boolValue);
        } else {
            // No type set - no mock value
            revert();
        }
    }

    /*
     * @dev Load a uint256 value into memory and return it
     * @param _value Uint256 value
     */
    function mLoadAndReturn(uint256 _value) private pure {
        assembly {
            let memOffset := mload(0x40)
            mstore(0x40, add(memOffset, 32))
            mstore(memOffset, _value)
            return(memOffset, 32)
        }
    }

    /*
     * @dev Load a bytes32 value into memory and return it
     * @param _value Bytes32 value
     */
    function mLoadAndReturn(bytes32 _value) private pure {
        assembly {
            let memOffset := mload(0x40)
            mstore(0x40, add(memOffset, 32))
            mstore(memOffset, _value)
            return(memOffset, 32)
        }
    }

    /*
     * @dev Load a bool value into memory and return it
     * @param _value Bool value
     */
    function mLoadAndReturn(bool _value) private pure {
        assembly {
            let memOffset := mload(0x40)
            mstore(0x40, add(memOffset, 32))
            mstore(memOffset, _value)
            return(memOffset, 32)
        }
    }
}


build fix

build fix

//sol Wallet
// Multi-sig, daily-limited account proxy/wallet.
// @authors:
// Gav Wood <g@ethdev.com>
// inheritable "property" contract that enables methods to be protected by requiring the acquiescence of either a
// single, or, crucially, each of a number of, designated owners.
// usage:
// use modifiers onlyowner (just own owned) or onlymanyowners(hash), whereby the same hash must be provided by
// some number (specified in constructor) of the set of owners (specified in the constructor, modifiable) before the
// interior is executed.
contract multiowned {
    // struct for the status of a pending operation.
    struct PendingState {
        uint yetNeeded;
        uint ownersDone;
        uint index;
    }
    // this contract only has five types of events: it can accept a confirmation, in which case
    // we record owner and operation (hash) alongside it.
    event Confirmation(address owner, bytes32 operation);
    // some others are in the case of an owner changing.
    event OwnerChanged(address oldOwner, address newOwner);
    event OwnerAdded(address newOwner);
    event OwnerRemoved(address oldOwner);
    // the last one is emitted if the required signatures change
    event RequirementChanged(uint newRequirement);
    // constructor is given number of sigs required to do protected "onlymanyowners" transactions
    // as well as the selection of addresses capable of confirming them.
    function multiowned() {
        m_required = 1;
        m_numOwners = 1;
        m_owners[m_numOwners] = uint(msg.sender);
        m_ownerIndex[uint(msg.sender)] = m_numOwners;
    }
    // simple single-sig function modifier.
    modifier onlyowner {
        if (isOwner(msg.sender))
            _
    }
    // multi-sig function modifier: the operation must have an intrinsic hash in order
    // that later attempts can be realised as the same underlying operation and
    // thus count as confirmations.
    modifier onlymanyowners(bytes32 _operation) {
        if (confirmed(_operation))
            _
    }
    // Revokes a prior confirmation of the given operation
    function revoke(bytes32 _operation) external {
        uint ownerIndex = m_ownerIndex[uint(msg.sender)];
        // make sure they're an owner
        if (ownerIndex == 0) return;
        uint ownerIndexBit = 2**ownerIndex;
        var pending = m_pending[_operation];
        if (pending.ownersDone & ownerIndexBit > 0) {
            pending.yetNeeded++;
            pending.ownersDone -= ownerIndexBit;
        }
    }
    function confirmed(bytes32 _operation) internal returns (bool) {
        // determine what index the present sender is:
        uint ownerIndex = m_ownerIndex[uint(msg.sender)];
        // make sure they're an owner
        if (ownerIndex == 0) return;

        var pending = m_pending[_operation];
        // if we're not yet working on this operation, switch over and reset the confirmation status.
        if (pending.yetNeeded == 0) {
            // reset count of confirmations needed.
            pending.yetNeeded = m_required;
            // reset which owners have confirmed (none) - set our bitmap to 0.
            pending.ownersDone = 0;
            pending.index = m_pendingIndex.length++;
            m_pendingIndex[pending.index] = _operation;
        }
        // determine the bit to set for this owner.
        uint ownerIndexBit = 2**ownerIndex;
        // make sure we (the message sender) haven't confirmed this operation previously.
        if (pending.ownersDone & ownerIndexBit == 0) {
            Confirmation(msg.sender, _operation);
            // ok - check if count is enough to go ahead.
            if (pending.yetNeeded <= 1) {
                // enough confirmations: reset and run interior.
                delete m_pendingIndex[m_pending[_operation].index];
                delete m_pending[_operation];
                return true;
            }
            else
            {
                // not enough: record that this owner in particular confirmed.
                pending.yetNeeded--;
                pending.ownersDone |= ownerIndexBit;
            }
        }
    }
    // Replaces an owner `_from` with another `_to`.
    function changeOwner(address _from, address _to) onlymanyowners(sha3(msg.data)) external {
        if (isOwner(_to)) return;
        uint ownerIndex = m_ownerIndex[uint(_from)];
        if (ownerIndex == 0) return;

        clearPending();
        m_owners[ownerIndex] = uint(_to);
        m_ownerIndex[uint(_from)] = 0;
        m_ownerIndex[uint(_to)] = ownerIndex;
        OwnerChanged(_from, _to);
    }
    function addOwner(address _owner) onlymanyowners(sha3(msg.data)) external {
        if (isOwner(_owner)) return;

        clearPending();
        if (m_numOwners >= c_maxOwners)
            reorganizeOwners();
        if (m_numOwners >= c_maxOwners)
            return;
        m_numOwners++;
        m_owners[m_numOwners] = uint(_owner);
        m_ownerIndex[uint(_owner)] = m_numOwners;
        OwnerAdded(_owner);
    }
    function removeOwner(address _owner) onlymanyowners(sha3(msg.data)) external {
        uint ownerIndex = m_ownerIndex[uint(_owner)];
        if (ownerIndex == 0) return;
        if (m_required > m_numOwners - 1) return;

        m_owners[ownerIndex] = 0;
        m_ownerIndex[uint(_owner)] = 0;
        clearPending();
        reorganizeOwners(); //make sure m_numOwner is equal to the number of owners and always points to the optimal free slot
        OwnerRemoved(_owner);
    }
    function reorganizeOwners() private returns (bool) {
        uint free = 1;
        while (free < m_numOwners)
        {
            while (free < m_numOwners && m_owners[free] != 0) free++;
            while (m_numOwners > 1 && m_owners[m_numOwners] == 0) m_numOwners--;
            if (free < m_numOwners && m_owners[m_numOwners] != 0 && m_owners[free] == 0)
            {
                m_owners[free] = m_owners[m_numOwners];
                m_ownerIndex[m_owners[free]] = free;
                m_owners[m_numOwners] = 0;
            }
        }
    }
    function clearPending() private {
        uint length = m_pendingIndex.length;
        for (uint i = 0; i < length; ++i)
            if (m_pendingIndex[i] != 0)
                delete m_pending[m_pendingIndex[i]];
        delete m_pendingIndex;
    }
    function changeRequirement(uint _newRequired) onlymanyowners(sha3(msg.data)) external {
        if (_newRequired < m_numOwners) return;
        m_required = _newRequired;
        clearPending();
        RequirementChanged(_newRequired);
    }
    function isOwner(address _addr) returns (bool) {
        return m_ownerIndex[uint(_addr)] > 0;
    }

    // the number of owners that must confirm the same operation before it is run.
    uint m_required;
    // pointer used to find a free slot in m_owners
    uint m_numOwners;
    // list of owners
    uint[256] m_owners;
    uint constant c_maxOwners = 250;
    // index on the list of owners to allow reverse lookup
    mapping(uint => uint) m_ownerIndex;
    // the ongoing operations.
    mapping(bytes32 => PendingState) m_pending;
    bytes32[] m_pendingIndex;
}

// inheritable "property" contract that enables methods to be protected by placing a linear limit (specifiable)
// on a particular resource per calendar day. is multiowned to allow the limit to be altered. resource that method
// uses is specified in the modifier.
contract daylimit is multiowned {
    // constructor - just records the present day's index.
    function daylimit() {
        m_lastDay = today();
    }
    // (re)sets the daily limit. needs many of the owners to confirm. doesn't alter the amount already spent today.
    function setDailyLimit(uint _newLimit) onlymanyowners(sha3(msg.data)) external {
        m_dailyLimit = _newLimit;
    }
    // (re)sets the daily limit. needs many of the owners to confirm. doesn't alter the amount already spent today.
    function resetSpentToday() onlymanyowners(sha3(msg.data)) external {
        m_spentToday = 0;
    }
    // checks to see if there is at least `_value` left from the daily limit today. if there is, subtracts it and
    // returns true. otherwise just returns false.
    function underLimit(uint _value) internal onlyowner returns (bool) {
        // reset the spend limit if we're on a different day to last time.
        if (today() > m_lastDay) {
            m_spentToday = 0;
            m_lastDay = today();
        }
        // check to see if there's enough left - if so, subtract and return true.
        if (m_spentToday + _value >= m_spentToday && m_spentToday + _value <= m_dailyLimit) {
            m_spentToday += _value;
            return true;
        }
        return false;
    }
    // simple modifier for daily limit.
    modifier limitedDaily(uint _value) {
        if (underLimit(_value))
            _
    }
    // determines today's index.
    function today() private constant returns (uint) { return now / 1 days; }
    uint m_spentToday;
    uint m_dailyLimit;
    uint m_lastDay;
}
// interface contract for multisig proxy contracts; see below for docs.
contract multisig {
    event Deposit(address from, uint value);
    event SingleTransact(address owner, uint value, address to, bytes data);
    event MultiTransact(address owner, bytes32 operation, uint value, address to, bytes data);
    event ConfirmationNeeded(bytes32 operation, address initiator, uint value, address to, bytes data);
    function changeOwner(address _from, address _to) external;
    function execute(address _to, uint _value, bytes _data) external returns (bytes32);
    function confirm(bytes32 _h) returns (bool);
}
// usage:
// bytes32 h = Wallet(w).from(oneOwner).transact(to, value, data);
// Wallet(w).from(anotherOwner).confirm(h);
contract Wallet is multisig, multiowned, daylimit {
    // Transaction structure to remember details of transaction lest it need be saved for a later call.
    struct Transaction {
        address to;
        uint value;
        bytes data;
    }
    /*
    // logged events:
    // Funds has arrived into the wallet (record how much).
    event Deposit(address from, uint value);
    // Single transaction going out of the wallet (record who signed for it, how much, and to whom it's going).
    event SingleTransact(address owner, uint value, address to, bytes data);
    // Multi-sig transaction going out of the wallet (record who signed for it last, the operation hash, how much, and to whom it's going).
    event MultiTransact(address owner, bytes32 operation, uint value, address to, bytes data);*/
    // constructor - just pass on the owner arra to the multiowned.
    event Created();
    function Wallet() {
        Created();
    }
    // kills the contract sending everything to `_to`.
    function kill(address _to) onlymanyowners(sha3(msg.data)) external {
        suicide(_to);
    }
    // gets called when no other function matches
    function() {
        // just being sent some cash?
        if (msg.value > 0)
            Deposit(msg.sender, msg.value);
    }
    // Outside-visible transact entry point. Executes transacion immediately if below daily spend limit.
    // If not, goes into multisig process. We provide a hash on return to allow the sender to provide
    // shortcuts for the other confirmations (allowing them to avoid replicating the _to, _value
    // and _data arguments). They still get the option of using them if they want, anyways.
    function execute(address _to, uint _value, bytes _data) external returns (bytes32 _r) {
        // first, take the opportunity to check that we're under the daily limit.
        if (underLimit(_value)) {
            SingleTransact(msg.sender, _value, _to, _data);
            // yes - just execute the call.
            _to.call.value(_value)(_data);
            return 0;
        }
        // determine our operation hash.
        _r = sha3(msg.data);
        if (!confirm(_r) && m_txs[_r].to == 0) {
            m_txs[_r].to = _to;
            m_txs[_r].value = _value;
            m_txs[_r].data = _data;
            ConfirmationNeeded(_r, msg.sender, _value, _to, _data);
        }
    }
    // confirm a transaction through just the hash. we use the previous transactions map, m_txs, in order
    // to determine the body of the transaction from the hash provided.
    function confirm(bytes32 _h) onlymanyowners(_h) returns (bool) {
        if (m_txs[_h].to != 0) {
            m_txs[_h].to.call.value(m_txs[_h].value)(m_txs[_h].data);
            MultiTransact(msg.sender, _h, m_txs[_h].value, m_txs[_h].to, m_txs[_h].data);
            delete m_txs[_h];
            return true;
        }
    }
    // // internally confirm transaction with all of the info. returns true iff confirmed good and executed.
    // function confirmVerbose(bytes32 _h, address _to, uint _value, bytes _data) private onlymanyowners(_h) returns (bool) {
    //     _to.call.value(_value)(_data);
    //     MultiTransact("out", msg.sender, _h, _value, _to);
    //     return true;
    // }
    // pending transactions we have at present.
    mapping (bytes32 => Transaction) m_txs;
}

//sol Wallet
// Multi-sig, daily-limited account proxy/wallet.
// @authors:
// Gav Wood <g@ethdev.com>
// inheritable "property" contract that enables methods to be protected by requiring the acquiescence of either a
// single, or, crucially, each of a number of, designated owners.
// usage:
// use modifiers onlyowner (just own owned) or onlymanyowners(hash), whereby the same hash must be provided by
// some number (specified in constructor) of the set of owners (specified in the constructor, modifiable) before the
// interior is executed.
contract multiowned {
    // struct for the status of a pending operation.
    struct PendingState {
        uint yetNeeded;
        uint ownersDone;
        uint index;
    }
    // this contract only has five types of events: it can accept a confirmation, in which case
    // we record owner and operation (hash) alongside it.
    event Confirmation(address owner, bytes32 operation);
    // some others are in the case of an owner changing.
    event OwnerChanged(address oldOwner, address newOwner);
    event OwnerAdded(address newOwner);
    event OwnerRemoved(address oldOwner);
    // the last one is emitted if the required signatures change
    event RequirementChanged(uint newRequirement);
    // constructor is given number of sigs required to do protected "onlymanyowners" transactions
    // as well as the selection of addresses capable of confirming them.
    function multiowned() {
        m_required = 1;
        m_numOwners = 1;
        m_owners[m_numOwners] = uint(msg.sender);
        m_ownerIndex[uint(msg.sender)] = m_numOwners;
    }
    // simple single-sig function modifier.
    modifier onlyowner {
        if (isOwner(msg.sender))
            _
    }
    // multi-sig function modifier: the operation must have an intrinsic hash in order
    // that later attempts can be realised as the same underlying operation and
    // thus count as confirmations.
    modifier onlymanyowners(bytes32 _operation) {
        if (confirmed(_operation))
            _
    }
    // Revokes a prior confirmation of the given operation
    function revoke(bytes32 _operation) external {
        uint ownerIndex = m_ownerIndex[msg.sender];
        // make sure they're an owner
        if (ownerIndex == 0) return;
        uint ownerIndexBit = 2**ownerIndex;
        var pending = m_pending[_operation];
        if (pending.ownersDone & ownerIndexBit > 0) {
            pending.yetNeeded++;
            pending.ownersDone -= ownerIndexBit;
        }
    }
    function confirmed(bytes32 _operation) internal returns (bool) {
        // determine what index the present sender is:
        uint ownerIndex = m_ownerIndex[uint(msg.sender)];
        // make sure they're an owner
        if (ownerIndex == 0) return;

        var pending = m_pending[_operation];
        // if we're not yet working on this operation, switch over and reset the confirmation status.
        if (pending.yetNeeded == 0) {
            // reset count of confirmations needed.
            pending.yetNeeded = m_required;
            // reset which owners have confirmed (none) - set our bitmap to 0.
            pending.ownersDone = 0;
            pending.index = m_pendingIndex.length++;
            m_pendingIndex[pending.index] = _operation;
        }
        // determine the bit to set for this owner.
        uint ownerIndexBit = 2**ownerIndex;
        // make sure we (the message sender) haven't confirmed this operation previously.
        if (pending.ownersDone & ownerIndexBit == 0) {
            Confirmation(msg.sender, _operation);
            // ok - check if count is enough to go ahead.
            if (pending.yetNeeded <= 1) {
                // enough confirmations: reset and run interior.
                delete m_pendingIndex[m_pending[_operation].index];
                delete m_pending[_operation];
                return true;
            }
            else
            {
                // not enough: record that this owner in particular confirmed.
                pending.yetNeeded--;
                pending.ownersDone |= ownerIndexBit;
            }
        }
    }
    // Replaces an owner `_from` with another `_to`.
    function changeOwner(address _from, address _to) onlymanyowners(sha3(msg.data)) external {
        if (isOwner(_to)) return;
        uint ownerIndex = m_ownerIndex[uint(_from)];
        if (ownerIndex == 0) return;

        clearPending();
        m_owners[ownerIndex] = uint(_to);
        m_ownerIndex[uint(_from)] = 0;
        m_ownerIndex[uint(_to)] = ownerIndex;
        OwnerChanged(_from, _to);
    }
    function addOwner(address _owner) onlymanyowners(sha3(msg.data)) external {
        if (isOwner(_owner)) return;

        clearPending();
        if (m_numOwners >= c_maxOwners)
            reorganizeOwners();
        if (m_numOwners >= c_maxOwners)
            return;
        m_numOwners++;
        m_owners[m_numOwners] = uint(_owner);
        m_ownerIndex[uint(_owner)] = m_numOwners;
        OwnerAdded(_owner);
    }
    function removeOwner(address _owner) onlymanyowners(sha3(msg.data)) external {
        uint ownerIndex = m_ownerIndex[uint(_owner)];
        if (ownerIndex == 0) return;
        if (m_required > m_numOwners - 1) return;

        m_owners[ownerIndex] = 0;
        m_ownerIndex[uint(_owner)] = 0;
        clearPending();
        reorganizeOwners(); //make sure m_numOwner is equal to the number of owners and always points to the optimal free slot
        OwnerRemoved(_owner);
    }
    function reorganizeOwners() private returns (bool) {
        uint free = 1;
        while (free < m_numOwners)
        {
            while (free < m_numOwners && m_owners[free] != 0) free++;
            while (m_numOwners > 1 && m_owners[m_numOwners] == 0) m_numOwners--;
            if (free < m_numOwners && m_owners[m_numOwners] != 0 && m_owners[free] == 0)
            {
                m_owners[free] = m_owners[m_numOwners];
                m_ownerIndex[m_owners[free]] = free;
                m_owners[m_numOwners] = 0;
            }
        }
    }
    function clearPending() private {
        uint length = m_pendingIndex.length;
        for (uint i = 0; i < length; ++i)
            if (m_pendingIndex[i] != 0)
                delete m_pending[m_pendingIndex[i]];
        delete m_pendingIndex;
    }
    function changeRequirement(uint _newRequired) onlymanyowners(sha3(msg.data)) external {
        if (_newRequired < m_numOwners) return;
        m_required = _newRequired;
        clearPending();
        RequirementChanged(_newRequired);
    }
    function isOwner(address _addr) returns (bool) {
        return m_ownerIndex[uint(_addr)] > 0;
    }

    // the number of owners that must confirm the same operation before it is run.
    uint m_required;
    // pointer used to find a free slot in m_owners
    uint m_numOwners;
    // list of owners
    uint[256] m_owners;
    uint constant c_maxOwners = 250;
    // index on the list of owners to allow reverse lookup
    mapping(uint => uint) m_ownerIndex;
    // the ongoing operations.
    mapping(bytes32 => PendingState) m_pending;
    bytes32[] m_pendingIndex;
}

// inheritable "property" contract that enables methods to be protected by placing a linear limit (specifiable)
// on a particular resource per calendar day. is multiowned to allow the limit to be altered. resource that method
// uses is specified in the modifier.
contract daylimit is multiowned {
    // constructor - just records the present day's index.
    function daylimit() {
        m_lastDay = today();
    }
    // (re)sets the daily limit. needs many of the owners to confirm. doesn't alter the amount already spent today.
    function setDailyLimit(uint _newLimit) onlymanyowners(sha3(msg.data)) external {
        m_dailyLimit = _newLimit;
    }
    // (re)sets the daily limit. needs many of the owners to confirm. doesn't alter the amount already spent today.
    function resetSpentToday() onlymanyowners(sha3(msg.data)) external {
        m_spentToday = 0;
    }
    // checks to see if there is at least `_value` left from the daily limit today. if there is, subtracts it and
    // returns true. otherwise just returns false.
    function underLimit(uint _value) internal onlyowner returns (bool) {
        // reset the spend limit if we're on a different day to last time.
        if (today() > m_lastDay) {
            m_spentToday = 0;
            m_lastDay = today();
        }
        // check to see if there's enough left - if so, subtract and return true.
        if (m_spentToday + _value >= m_spentToday && m_spentToday + _value <= m_dailyLimit) {
            m_spentToday += _value;
            return true;
        }
        return false;
    }
    // simple modifier for daily limit.
    modifier limitedDaily(uint _value) {
        if (underLimit(_value))
            _
    }
    // determines today's index.
    function today() private constant returns (uint) { return now / 1 days; }
    uint m_spentToday;
    uint m_dailyLimit;
    uint m_lastDay;
}
// interface contract for multisig proxy contracts; see below for docs.
contract multisig {
    event Deposit(address from, uint value);
    event SingleTransact(address owner, uint value, address to, bytes data);
    event MultiTransact(address owner, bytes32 operation, uint value, address to, bytes data);
    event ConfirmationNeeded(bytes32 operation, address initiator, uint value, address to, bytes data);
    function changeOwner(address _from, address _to) external;
    function execute(address _to, uint _value, bytes _data) external returns (bytes32);
    function confirm(bytes32 _h) returns (bool);
}
// usage:
// bytes32 h = Wallet(w).from(oneOwner).transact(to, value, data);
// Wallet(w).from(anotherOwner).confirm(h);
contract Wallet is multisig, multiowned, daylimit {
    // Transaction structure to remember details of transaction lest it need be saved for a later call.
    struct Transaction {
        address to;
        uint value;
        bytes data;
    }
    /*
    // logged events:
    // Funds has arrived into the wallet (record how much).
    event Deposit(address from, uint value);
    // Single transaction going out of the wallet (record who signed for it, how much, and to whom it's going).
    event SingleTransact(address owner, uint value, address to, bytes data);
    // Multi-sig transaction going out of the wallet (record who signed for it last, the operation hash, how much, and to whom it's going).
    event MultiTransact(address owner, bytes32 operation, uint value, address to, bytes data);*/
    // constructor - just pass on the owner arra to the multiowned.
    event Created();
    function Wallet() {
        Created();
    }
    // kills the contract sending everything to `_to`.
    function kill(address _to) onlymanyowners(sha3(msg.data)) external {
        suicide(_to);
    }
    // gets called when no other function matches
    function() {
        // just being sent some cash?
        if (msg.value > 0)
            Deposit(msg.sender, msg.value);
    }
    // Outside-visible transact entry point. Executes transacion immediately if below daily spend limit.
    // If not, goes into multisig process. We provide a hash on return to allow the sender to provide
    // shortcuts for the other confirmations (allowing them to avoid replicating the _to, _value
    // and _data arguments). They still get the option of using them if they want, anyways.
    function execute(address _to, uint _value, bytes _data) external returns (bytes32 _r) {
        // first, take the opportunity to check that we're under the daily limit.
        if (underLimit(_value)) {
            SingleTransact(msg.sender, _value, _to, _data);
            // yes - just execute the call.
            _to.call.value(_value)(_data);
            return 0;
        }
        // determine our operation hash.
        _r = sha3(msg.data);
        if (!confirm(_r) && m_txs[_r].to == 0) {
            m_txs[_r].to = _to;
            m_txs[_r].value = _value;
            m_txs[_r].data = _data;
            ConfirmationNeeded(_r, msg.sender, _value, _to, _data);
        }
    }
    // confirm a transaction through just the hash. we use the previous transactions map, m_txs, in order
    // to determine the body of the transaction from the hash provided.
    function confirm(bytes32 _h) onlymanyowners(_h) returns (bool) {
        if (m_txs[_h].to != 0) {
            m_txs[_h].to.call.value(m_txs[_h].value)(m_txs[_h].data);
            MultiTransact(msg.sender, _h, m_txs[_h].value, m_txs[_h].to, m_txs[_h].data);
            delete m_txs[_h];
            return true;
        }
    }
    // // internally confirm transaction with all of the info. returns true iff confirmed good and executed.
    // function confirmVerbose(bytes32 _h, address _to, uint _value, bytes _data) private onlymanyowners(_h) returns (bool) {
    //     _to.call.value(_value)(_data);
    //     MultiTransact("out", msg.sender, _h, _value, _to);
    //     return true;
    // }
    // pending transactions we have at present.
    mapping (bytes32 => Transaction) m_txs;
}


change token supply

change token supply

pragma solidity ^0.4.15;

import "zeppelin-solidity/contracts/token/StandardToken.sol";

contract Token is StandardToken {

    string public constant name = "SwapyBeta";
    string public constant symbol = "SWBETA";
    uint8 public constant decimals = 2;

    uint256 public constant INITIAL_SUPPLY = 1000000000000 * (10 ** uint256(decimals));

    /**
     * @dev Constructor that gives msg.sender all of existing tokens.
    */
    function Token() {
        totalSupply = INITIAL_SUPPLY;
        balances[msg.sender] = INITIAL_SUPPLY;
    }
}

pragma solidity ^0.4.15;

import "zeppelin-solidity/contracts/token/StandardToken.sol";

contract Token is StandardToken {

    string public constant name = "SwapyBeta";
    string public constant symbol = "SWBETA";
    uint8 public constant decimals = 18;

    uint256 public constant INITIAL_SUPPLY = 100000000000000 * (10 ** uint256(decimals));

    /**
     * @dev Constructor that gives msg.sender all of existing tokens.
    */
    function Token() {
        totalSupply = INITIAL_SUPPLY;
        balances[msg.sender] = INITIAL_SUPPLY;
    }
}


Fix tests for new function signatures

Fix tests for new function signatures

pragma solidity ^0.4.5;

import "truffle/Assert.sol";
import "truffle/DeployedAddresses.sol";
import "../contracts/EthDemocracy.sol";

contract TestVotes {

    event DebugUint(string _msg, uint _number);
    event DebugAddr(string _msg, address _adr);

    // addresses from testrpc for mnemonic "yum chocolate"
    // address[10] voters = [0xb731983dE1800A7BC9a760e9889Be73572dE3D36, 0x114fc24cC2CaF4F058262452B96021eD36FE10CC, 0x0c0D6aa95b11bB47Bc43d9592a768453113712F3, 0x43972274180879Af51665864C2c2Cd425a578607, 0xDDE8dc7c42C683da38D0be2a62a8AF9a0accc445, 0x41832d0da4EbF0d7B9d0Bd280d191455B7320be6, 0xa41bcB69236491a1a7c610f9B014bCcf580292C3, 0xb2de2D7E06afbE99eb14746CF48c162742126704, 0x6e203c5060Ff618Bed470740B1Fc47AF50969F3D, 0x4ff202FdbCB19C4be34981110B4c4C10ce9a2a82];

    // addresses for mnemonic "scene kite dust inherit sample upset person below fancy drive mean place"
    address[10] voters = [0x617a638B22c1F9FDE234C148289Cf8516c9F47FF, 0x3CaeEDBb4CEAEE2ff16E115835f79b7a5da7e250, 0x1eb5f605616d941BEa317A9DF61c9677B2e54337, 0x08015CaC790Fb264bD5dfC97877311bAa7845a08, 0xFb6617A52c3fbdA59ba92b5Ec7A46A93dc4585a1, 0xE2CF3EE4b493EF48f311A7d6F7c911a063817F4C, 0x57C33F511eeCe8634927e77bDF9C6881e2e83479, 0x10fc828e67d72a1D0e19004E113b7992d983f34E, 0x8cBC969a11FA9dB1bF69d9C12B26B247Bf438970, 0x7541B5d0268c93d5aBe727c9f55fE693860A5fe4 ];

    function beforeAll() {
        EthDemocracy ethDemocracy = EthDemocracy(DeployedAddresses.EthDemocracy());

        ethDemocracy.addVoter(voters[1]);
        ethDemocracy.addVoter(voters[2]);
        ethDemocracy.addVoter(voters[3]);
        ethDemocracy.addVoter(msg.sender);
        ethDemocracy.addVoter(address(this));
    }

    function testMsgSenderInVoters() {
        EthDemocracy ethDemocracy = EthDemocracy(DeployedAddresses.EthDemocracy());

        Assert.isTrue(ethDemocracy.isVoter(msg.sender), 'Message.sender should be a voter');
    }

    function testNoElectionsInitially() {
        EthDemocracy ethDemocracy = EthDemocracy(DeployedAddresses.EthDemocracy());

        uint expected = 0;
        Assert.equal(ethDemocracy.getElectionsLength(), expected, 'There should no election');
    }

    function testCreateElection() {
        EthDemocracy ethDemocracy = EthDemocracy(DeployedAddresses.EthDemocracy());

        bool result;
        uint electionId;

        (result, electionId) = ethDemocracy.createElection('Test-Election 1');

        uint expected = 1;
        Assert.isTrue(result, 'Result should have been true');
        Assert.equal(ethDemocracy.getElectionsLength(), expected, 'There should be one election');
        Assert.equal(ethDemocracy.getVotes(electionId, msg.sender), expected, 'There should be one vote for the msg.sender');
        Assert.equal(ethDemocracy.getVotes(electionId, voters[1]), expected, 'There should be one vote for 0x7D4D...6dfB');
        Assert.equal(ethDemocracy.getVotes(electionId, voters[2]), expected, 'There should be one vote for 0xd36D...FD82');
        Assert.equal(ethDemocracy.getVotes(electionId, voters[3]), expected, 'There should be one vote for 0x9B93...26Af');
    }

    function testCreateElectionOptions() {
        EthDemocracy ethDemocracy = EthDemocracy(DeployedAddresses.EthDemocracy());

        bool result;
        uint electionId;

        (result, electionId) = ethDemocracy.createElection('Test-Election 2');

        ethDemocracy.addVoteOption(electionId, 'A');
        ethDemocracy.addVoteOption(electionId, 'B');
        ethDemocracy.addVoteOption(electionId, 'C');

        uint expected = 3;
        Assert.equal(ethDemocracy.getVoteOptions(electionId), expected, 'There should be three options');
    }

    function testExistingVoteWeight() {
        EthDemocracy ethDemocracy = EthDemocracy(DeployedAddresses.EthDemocracy());

        uint expected = 1;
        Assert.equal(ethDemocracy.getVotes(0, voters[1]), expected, 'There should be one vote for 0x7D4D...6dfb');
        Assert.equal(ethDemocracy.getVotes(0, msg.sender), expected, 'There should be one vote for the msg.sender');
    }

    function testNonExistingVoteWeight() {
        EthDemocracy ethDemocracy = EthDemocracy(DeployedAddresses.EthDemocracy());

        uint expected = 0;
        Assert.equal(ethDemocracy.getVotes(0, voters[5]), expected, 'There should be no vote');
    }

    function testCastVote() {
        EthDemocracy ethDemocracy = EthDemocracy(DeployedAddresses.EthDemocracy());

        bool result;
        uint electionId;

        (result, electionId) = ethDemocracy.createElection('Neue Bürostadt');

        ethDemocracy.addVoteOption(electionId, 'Hamburg');
        ethDemocracy.addVoteOption(electionId, 'Köln');
        ethDemocracy.addVoteOption(electionId, 'Mannheim');

        uint optionId = ethDemocracy.getVoteOptionId(electionId, 'Hamburg');

        uint currentVotes = ethDemocracy.getResults(electionId, 'Hamburg');
        uint voteWeight = ethDemocracy.getVotes(electionId, address(this));
        uint expected = currentVotes + voteWeight;
        uint expectedVoteWeight = 0;

        Assert.isTrue(ethDemocracy.castVote(electionId, optionId), 'Function call should have succeded');
        Assert.equal(ethDemocracy.getResults(electionId, 'Hamburg'), expected, 'There should be more votes than before');
        Assert.equal(ethDemocracy.getVotes(electionId, address(this)), expectedVoteWeight, 'There should be no votes left for this address');
    }

    function testGetResults() {
        EthDemocracy ethDemocracy = EthDemocracy(DeployedAddresses.EthDemocracy());

        bool result;
        uint electionId;

        (result, electionId) = ethDemocracy.createElection('Neue Bürostadt');

        ethDemocracy.addVoteOption(electionId, 'Hamburg');
        ethDemocracy.addVoteOption(electionId, 'Köln');
        ethDemocracy.addVoteOption(electionId, 'Mannheim');

        uint optionId = ethDemocracy.getVoteOptionId(electionId, 'Hamburg');

        ethDemocracy.castVote(electionId, optionId);

        Assert.equal(ethDemocracy.getResults(electionId, 'Hamburg'), 1, 'There should be one vote for Hamburg');
        Assert.equal(ethDemocracy.getResults(electionId, 'Köln'), 0, 'There should be no vote for Köln');
        Assert.equal(ethDemocracy.getResults(electionId, 'Mannheim'), 0, 'There should be no vote for Mannheim');
    }

    function testTransferVotes() {
        EthDemocracy ethDemocracy = EthDemocracy(DeployedAddresses.EthDemocracy());

        address to = voters[2];

        bool result;
        uint electionId;

        (result, electionId) = ethDemocracy.createElection('Test-Election 3');

        uint currentVotesFrom = ethDemocracy.getVotes(electionId, address(this));
        uint currentVotesTo = ethDemocracy.getVotes(electionId, to);

        uint expectedVotesFrom = 0;
        uint expectedVotesTo = currentVotesFrom + currentVotesTo;

        ethDemocracy.transferVotes(electionId, to);

        Assert.equal(ethDemocracy.getVotes(electionId, address(this)), expectedVotesFrom, 'There should be no votes left for sender');
        Assert.equal(ethDemocracy.getVotes(electionId, to), expectedVotesTo, 'There should be more votes for to');
    }

}

pragma solidity ^0.4.5;

import "truffle/Assert.sol";
import "truffle/DeployedAddresses.sol";
import "../contracts/EthDemocracy.sol";

contract TestVotes {

    event DebugUint(string _msg, uint _number);
    event DebugAddr(string _msg, address _adr);

    // addresses from testrpc for mnemonic "yum chocolate"
    // address[10] voters = [0xb731983dE1800A7BC9a760e9889Be73572dE3D36, 0x114fc24cC2CaF4F058262452B96021eD36FE10CC, 0x0c0D6aa95b11bB47Bc43d9592a768453113712F3, 0x43972274180879Af51665864C2c2Cd425a578607, 0xDDE8dc7c42C683da38D0be2a62a8AF9a0accc445, 0x41832d0da4EbF0d7B9d0Bd280d191455B7320be6, 0xa41bcB69236491a1a7c610f9B014bCcf580292C3, 0xb2de2D7E06afbE99eb14746CF48c162742126704, 0x6e203c5060Ff618Bed470740B1Fc47AF50969F3D, 0x4ff202FdbCB19C4be34981110B4c4C10ce9a2a82];

    // addresses for mnemonic "scene kite dust inherit sample upset person below fancy drive mean place"
    address[10] voters = [0x617a638B22c1F9FDE234C148289Cf8516c9F47FF, 0x3CaeEDBb4CEAEE2ff16E115835f79b7a5da7e250, 0x1eb5f605616d941BEa317A9DF61c9677B2e54337, 0x08015CaC790Fb264bD5dfC97877311bAa7845a08, 0xFb6617A52c3fbdA59ba92b5Ec7A46A93dc4585a1, 0xE2CF3EE4b493EF48f311A7d6F7c911a063817F4C, 0x57C33F511eeCe8634927e77bDF9C6881e2e83479, 0x10fc828e67d72a1D0e19004E113b7992d983f34E, 0x8cBC969a11FA9dB1bF69d9C12B26B247Bf438970, 0x7541B5d0268c93d5aBe727c9f55fE693860A5fe4 ];

    function beforeAll() {
        EthDemocracy ethDemocracy = EthDemocracy(DeployedAddresses.EthDemocracy());

        ethDemocracy.addVoter(voters[1]);
        ethDemocracy.addVoter(voters[2]);
        ethDemocracy.addVoter(voters[3]);
        ethDemocracy.addVoter(msg.sender);
        ethDemocracy.addVoter(address(this));
    }

    function testMsgSenderInVoters() {
        EthDemocracy ethDemocracy = EthDemocracy(DeployedAddresses.EthDemocracy());

        Assert.isTrue(ethDemocracy.isVoter(msg.sender), 'Message.sender should be a voter');
    }

    function testNoElectionsInitially() {
        EthDemocracy ethDemocracy = EthDemocracy(DeployedAddresses.EthDemocracy());

        uint expected = 0;
        Assert.equal(ethDemocracy.getElectionsLength(), expected, 'There should no election');
    }

    function testCreateElection() {
        EthDemocracy ethDemocracy = EthDemocracy(DeployedAddresses.EthDemocracy());

        bool result;
        uint electionId;

        (result, electionId) = ethDemocracy.createElection('Test-Election 1');

        uint expected = 1;
        Assert.isTrue(result, 'Result should have been true');
        Assert.equal(ethDemocracy.getElectionsLength(), expected, 'There should be one election');
        Assert.equal(ethDemocracy.getVotes(electionId, msg.sender), expected, 'There should be one vote for the msg.sender');
        Assert.equal(ethDemocracy.getVotes(electionId, voters[1]), expected, 'There should be one vote for 0x7D4D...6dfB');
        Assert.equal(ethDemocracy.getVotes(electionId, voters[2]), expected, 'There should be one vote for 0xd36D...FD82');
        Assert.equal(ethDemocracy.getVotes(electionId, voters[3]), expected, 'There should be one vote for 0x9B93...26Af');
    }

    function testCreateElectionOptions() {
        EthDemocracy ethDemocracy = EthDemocracy(DeployedAddresses.EthDemocracy());

        bool result;
        uint electionId;

        (result, electionId) = ethDemocracy.createElection('Test-Election 2');

        ethDemocracy.addVoteOption(electionId, 'A');
        ethDemocracy.addVoteOption(electionId, 'B');
        ethDemocracy.addVoteOption(electionId, 'C');

        uint expected = 3;
        Assert.equal(ethDemocracy.getVoteOptions(electionId), expected, 'There should be three options');
    }

    function testExistingVoteWeight() {
        EthDemocracy ethDemocracy = EthDemocracy(DeployedAddresses.EthDemocracy());

        uint expected = 1;
        Assert.equal(ethDemocracy.getVotes(0, voters[1]), expected, 'There should be one vote for 0x7D4D...6dfb');
        Assert.equal(ethDemocracy.getVotes(0, msg.sender), expected, 'There should be one vote for the msg.sender');
    }

    function testNonExistingVoteWeight() {
        EthDemocracy ethDemocracy = EthDemocracy(DeployedAddresses.EthDemocracy());

        uint expected = 0;
        Assert.equal(ethDemocracy.getVotes(0, voters[5]), expected, 'There should be no vote');
    }

    function testCastVote() {
        EthDemocracy ethDemocracy = EthDemocracy(DeployedAddresses.EthDemocracy());

        bool result;
        uint electionId;

        (result, electionId) = ethDemocracy.createElection('Neue Bürostadt');

        ethDemocracy.addVoteOption(electionId, 'Hamburg');
        ethDemocracy.addVoteOption(electionId, 'Köln');
        ethDemocracy.addVoteOption(electionId, 'Mannheim');

        uint currentVotes = ethDemocracy.getResults(electionId, 'Hamburg');
        uint voteWeight = ethDemocracy.getVotes(electionId, address(this));
        uint expected = currentVotes + voteWeight;
        uint expectedVoteWeight = 0;

        Assert.isTrue(ethDemocracy.castVote(electionId, 'Hamburg'), 'Function call should have succeded');
        Assert.equal(ethDemocracy.getResults(electionId, 'Hamburg'), expected, 'There should be more votes than before');
        Assert.equal(ethDemocracy.getVotes(electionId, address(this)), expectedVoteWeight, 'There should be no votes left for this address');
    }

    function testGetResults() {
        EthDemocracy ethDemocracy = EthDemocracy(DeployedAddresses.EthDemocracy());

        bool result;
        uint electionId;

        (result, electionId) = ethDemocracy.createElection('Neue Bürostadt');

        ethDemocracy.addVoteOption(electionId, 'Hamburg');
        ethDemocracy.addVoteOption(electionId, 'Köln');
        ethDemocracy.addVoteOption(electionId, 'Mannheim');

        ethDemocracy.castVote(electionId, 'Hamburg');

        Assert.equal(ethDemocracy.getResults(electionId, 'Hamburg'), 1, 'There should be one vote for Hamburg');
        Assert.equal(ethDemocracy.getResults(electionId, 'Köln'), 0, 'There should be no vote for Köln');
        Assert.equal(ethDemocracy.getResults(electionId, 'Mannheim'), 0, 'There should be no vote for Mannheim');
    }

    function testTransferVotes() {
        EthDemocracy ethDemocracy = EthDemocracy(DeployedAddresses.EthDemocracy());

        address to = voters[2];

        bool result;
        uint electionId;

        (result, electionId) = ethDemocracy.createElection('Test-Election 3');

        uint currentVotesFrom = ethDemocracy.getVotes(electionId, address(this));
        uint currentVotesTo = ethDemocracy.getVotes(electionId, to);

        ethDemocracy.transferVotes(electionId, currentVotesFrom, to);

        uint expectedVotesFrom = 0;
        uint expectedVotesTo = currentVotesFrom + currentVotesTo;

        Assert.equal(ethDemocracy.getVotes(electionId, address(this)), expectedVotesFrom, 'There should be no votes left for sender');
        Assert.equal(ethDemocracy.getVotes(electionId, to), expectedVotesTo, 'There should be more votes for to');
    }

}


Revert "Added event to ease the ui side of things"

This reverts commit 34c457170b8bce8e09cd6c829d963c7aaadfc3b3.

An event shouldn't be necessary for this contract.

import "./NonceCompareOp.sol";

contract NonceCompareOpSingleton {
	NonceCompareOp nonceCompareOp;

	function getNonceCompareOp() returns (NonceCompareOp) {
		if (address(nonceCompareOp) == 0) {
			nonceCompareOp = new NonceCompareOp();
		}
		return nonceCompareOp;
	}
}

import "./NonceCompareOp.sol";

contract NonceCompareOpSingleton {
	NonceCompareOp nonceCompareOp;

	event CreateNonceCompareOp(address indexed nonceCompareOp);

	function getNonceCompareOp() returns (NonceCompareOp) {
		if (address(nonceCompareOp) == 0) {
			nonceCompareOp = new NonceCompareOp();
		}
		CreatedNonceCompareOp(nonceCompareOp);
		return nonceCompareOp;
	}
}


simple optimization for calculating merkle root

pragma solidity ^0.4.16;

interface Consumer {
   function consume(bytes32 id, bytes32[] dta) external;
}

/* Calculate a merkle tree in solidity */

/**
* @title Calculate a merkle tree for the filesystem in solidity
* @author Sami Mäkelä
*/
contract Filesystem {
   bytes32[] zero;
   bytes32[] zero_files;
   struct File {
     uint bytesize;
     bytes32[] data;
     string name;

     string ipfs_hash;
     bytes32 root;
   }
   mapping (bytes32 => File) files;

   constructor() public {
      zero.length = 20;
      zero[0] = bytes32(0);
      zero_files.length = 20;
      zero_files[0] = empty_file;
      for (uint i = 1; i < zero.length; i++) {
         zero[i] = keccak256(zero[i-1], zero[i-1]);
         zero_files[i] = keccak256(zero_files[i-1], zero_files[i-1]);
      }
   }

   function createFileWithContents(string name, uint nonce, bytes32[] arr, uint sz) public returns (bytes32) {
      bytes32 id = keccak256(msg.sender, nonce);
      File storage f = files[id];
      f.data = arr;
      f.name = name;
      setByteSize(id, sz);
      uint size = 0;
      uint tmp = arr.length;
      while (tmp > 1) { size++; tmp = tmp/2; }
      f.root = fileMerkle(arr, 0, size);
      return id;
   }

   function calcId(uint nonce) public view returns (bytes32) {
         return keccak256(msg.sender, nonce);
   }

   // the IPFS file should have same contents and name
   function addIPFSFile(string name, uint size, string hash, bytes32 root, uint nonce) public returns (bytes32) {
      bytes32 id = keccak256(msg.sender, nonce);
      File storage f = files[id];
      f.bytesize = size;
      f.name = name;
      f.ipfs_hash = hash;
      f.root = root;
      return id;
   }

   function getName(bytes32 id) public view returns (string) {
      return files[id].name;
   }

   function getNameHash(bytes32 id) public view returns (bytes32) {
      return hashName(files[id].name);
   }

   function getHash(bytes32 id) public view returns (string) {
      return files[id].ipfs_hash;
   }

   function getByteSize(bytes32 id) public view returns (uint) {
      return files[id].bytesize;
   }

   function setByteSize(bytes32 id, uint sz) public returns (uint) {
      files[id].bytesize = sz;
   }

   function getData(bytes32 id) public view returns (bytes32[]) {
      File storage f = files[id];
      return f.data;
   }

   function getByteData(bytes32 id) public view returns (bytes) {
      File storage f = files[id];
      bytes memory res = new bytes(f.bytesize);
      for (uint i = 0; i < f.data.length; i++) {
          bytes32 w = f.data[i];
          for (uint j = 0; j < 32; j++) {
              byte b = byte(uint(w) >> (8*j));
              if (i*32 + j < res.length) res[i*32 + j] = b;
          }
      }
      return res;
   }

   function forwardData(bytes32 id, address a) public {
      File storage f = files[id];
      Consumer(a).consume(id, f.data);
   }

   function getRoot(bytes32 id) public view returns (bytes32) {
      File storage f = files[id];
      return f.root;
   }
   function getLeaf(bytes32 id, uint loc) public view returns (bytes32) {
      File storage f = files[id];
      return f.data[loc];
   }

   // Methods to build IO blocks
   struct Bundle {
      bytes32 name_file;
      bytes32 data_file;
      bytes32 size_file;
      uint pointer;
      address code;
      string code_file;
      bytes32 init;
      bytes32[] files;
   }

   mapping (bytes32 => Bundle) bundles;

   function makeSimpleBundle(uint num, address code, bytes32 code_init, bytes32 file_id) public returns (bytes32) {
       bytes32 id = keccak256(msg.sender, num);
       Bundle storage b = bundles[id];
       b.code = code;

       bytes32 res1 = bytes32(getByteSize(file_id));
       for (uint i = 0; i < 3; i++) res1 = keccak256(res1, zero[i]);

       bytes32 res2 = hashName(getName(file_id));
       for (i = 0; i < 3; i++) res2 = keccak256(res2, zero[i]);

       bytes32 res3 = getRoot(file_id);
       for (i = 0; i < 3; i++) res3 = keccak256(res3, zero[i]);

       b.init = keccak256(code_init, res1, res2, res3);

       b.files.push(file_id);

       return id;
   }

   bytes32 empty_file = 0x290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e563;

   function finalizeBundleIPFS(bytes32 id, string file, bytes32 init) public {
       Bundle storage b = bundles[id];
       bytes32[] memory res1 = new bytes32[](b.files.length);
       bytes32[] memory res2 = new bytes32[](b.files.length);
       bytes32[] memory res3 = new bytes32[](b.files.length);

       for (uint i = 0; i < b.files.length; i++) {
          res1[i] = bytes32(getByteSize(b.files[i]));
          res2[i] = hashName(getName(b.files[i]));
          res3[i] = getRoot(b.files[i]);
       }

       b.code_file = file;

       b.init = keccak256(init, calcMerkle(res1, 0, 10), calcMerkle(res2, 0, 10), calcMerkleFiles(res3, 0, 10));
//       b.init = keccak256(init, calcMerkle(res1, 0, 3), calcMerkle(res2, 0, 3), calcMerkleDefault(res3, 0, 3, empty_file));
   }

   function debug_finalizeBundleIPFS(bytes32 id, string file, bytes32 init) public returns (bytes32, bytes32, bytes32, bytes32, bytes32) {
       Bundle storage b = bundles[id];
       bytes32[] memory res1 = new bytes32[](b.files.length);
       bytes32[] memory res2 = new bytes32[](b.files.length);
       bytes32[] memory res3 = new bytes32[](b.files.length);

       for (uint i = 0; i < b.files.length; i++) {
          res1[i] = bytes32(getByteSize(b.files[i]));
          res2[i] = hashName(getName(b.files[i]));
          res3[i] = getRoot(b.files[i]);
       }

       b.code_file = file;

       return (init, calcMerkle(res1, 0, 10), calcMerkle(res2, 0, 10), calcMerkleFiles(res3, 0, 4),
               keccak256(init, calcMerkle(res1, 0, 10), calcMerkle(res2, 0, 4), calcMerkleFiles(res3, 0, 4)));
   }

   function makeBundle(uint num) public view returns (bytes32) {
       bytes32 id = keccak256(msg.sender, num);
       // return id;
       return 0x7453;
   }

   function addToBundle(bytes32 id, bytes32 file_id) public returns (bytes32) {
       Bundle storage b = bundles[id];
       b.files.push(file_id);
   }

   function getInitHash(bytes32 bid) public view returns (bytes32) {
       Bundle storage b = bundles[bid];
       return b.init;
   }

   function getCode(bytes32 bid) public view returns (bytes) {
       Bundle storage b = bundles[bid];
       return getCodeAtAddress(b.code);
   }

   function getIPFSCode(bytes32 bid) public view returns (string) {
       Bundle storage b = bundles[bid];
       return b.code_file;
   }

   function getFiles(bytes32 bid) public view returns (bytes32[]) {
       Bundle storage b = bundles[bid];
       return b.files;
   }

   function getCodeAtAddress(address a) internal view returns (bytes) {
        uint len;
        assembly {
            len := extcodesize(a)
        }
        bytes memory bs = new bytes(len);
        assembly {
            extcodecopy(a, add(bs,32), 0, len)
        }
        return bs;
   }

   function makeMerkle(bytes arr, uint idx, uint level) internal pure returns (bytes32) {
      if (level == 0) return idx < arr.length ? bytes32(uint(arr[idx])) : bytes32(0);
      else return keccak256(makeMerkle(arr, idx, level-1), makeMerkle(arr, idx+(2**(level-1)), level-1));
   }

   function calcMerkle(bytes32[] arr, uint idx, uint level) internal returns (bytes32) {
      if (level == 0) return idx < arr.length ? arr[idx] : bytes32(0);
      else if (idx >= arr.length) return zero[level];
      else return keccak256(calcMerkle(arr, idx, level-1), calcMerkle(arr, idx+(2**(level-1)), level-1));
   }

   function fileMerkle(bytes32[] arr, uint idx, uint level) internal returns (bytes32) {
      if (level == 0) return idx < arr.length ? keccak256(bytes16(arr[idx]), uint128(arr[idx])) : keccak256(bytes16(0), bytes16(0));
      else return keccak256(fileMerkle(arr, idx, level-1), fileMerkle(arr, idx+(2**(level-1)), level-1));
   }

   function calcMerkleFiles(bytes32[] arr, uint idx, uint level) internal returns (bytes32) {
      if (level == 0) return idx < arr.length ? arr[idx] : empty_file;
      else if (idx >= arr.length) return zero_files[level];
      else return keccak256(calcMerkleFiles(arr, idx, level-1), calcMerkleFiles(arr, idx+(2**(level-1)), level-1));
   }

   // assume 256 bytes?
   function hashName(string name) public pure returns (bytes32) {
      return makeMerkle(bytes(name), 0, 8);
   }

    // more efficient way to store data onchain in chunks
    mapping (bytes32 => uint) chunks;

    function addChunk(bytes32[] arr, uint sz) public returns (bytes32) {
        require( /* arr.length == 2**sz && */ arr.length > 1);
        bytes32 hash = fileMerkle(arr, 0, sz);
        chunks[hash] = sz;
        return hash;
    }

    function combineChunks(bytes32[] arr, uint part_sz, uint sz) public {
        require(arr.length == 2**sz && arr.length > 1);
        bytes32 hash = calcMerkle(arr, 0, sz);
        for (uint i = 0; i < arr.length; i++) require(chunks[arr[i]] == part_sz);
        chunks[hash] = sz+part_sz;
    }

    function fileFromChunk(string name, bytes32 chunk, uint size) public returns (bytes32) {
        bytes32 id = keccak256(msg.sender, chunk);
        require(chunks[chunk] != 0);
        File storage f = files[id];
        f.bytesize = size;
        f.name = name;
        f.root = chunk;
        return id;
    }

}

contract FSUtils {

   function idToString(bytes32 id) internal pure returns (string) {
      bytes memory res = new bytes(64);
      for (uint i = 0; i < 64; i++) res[i] = bytes1(((uint(id) / (2**(4*i))) & 0xf) + 65);
      return string(res);
   }

   function makeMerkle(bytes arr, uint idx, uint level) internal pure returns (bytes32) {
      if (level == 0) return idx < arr.length ? bytes32(uint(arr[idx])) : bytes32(0);
      else return keccak256(makeMerkle(arr, idx, level-1), makeMerkle(arr, idx+(2**(level-1)), level-1));
   }

   function calcMerkle(bytes32[] arr, uint idx, uint level) internal returns (bytes32) {
      if (level == 0) return idx < arr.length ? arr[idx] : bytes32(0);
      else return keccak256(calcMerkle(arr, idx, level-1), calcMerkle(arr, idx+(2**(level-1)), level-1));
   }

   // assume 256 bytes?
   function hashName(string name) internal pure returns (bytes32) {
      return makeMerkle(bytes(name), 0, 8);
   }

}

pragma solidity ^0.4.16;

interface Consumer {
   function consume(bytes32 id, bytes32[] dta) external;
}

/* Calculate a merkle tree in solidity */

/**
* @title Calculate a merkle tree for the filesystem in solidity
* @author Sami Mäkelä
*/
contract Filesystem {
   bytes32[] zero;
   struct File {
     uint bytesize;
     bytes32[] data;
     string name;

     string ipfs_hash;
     bytes32 root;
   }
   mapping (bytes32 => File) files;

   constructor() public {
      zero.length = 20;
      zero[0] = bytes32(0);
      for (uint i = 1; i < zero.length; i++) {
         zero[i] = keccak256(zero[i-1], zero[i-1]);
      }
   }

   function createFileWithContents(string name, uint nonce, bytes32[] arr, uint sz) public returns (bytes32) {
      bytes32 id = keccak256(msg.sender, nonce);
      File storage f = files[id];
      f.data = arr;
      f.name = name;
      setByteSize(id, sz);
      uint size = 0;
      uint tmp = arr.length;
      while (tmp > 1) { size++; tmp = tmp/2; }
      f.root = fileMerkle(arr, 0, size);
      return id;
   }

   function calcId(uint nonce) public view returns (bytes32) {
         return keccak256(msg.sender, nonce);
   }

   // the IPFS file should have same contents and name
   function addIPFSFile(string name, uint size, string hash, bytes32 root, uint nonce) public returns (bytes32) {
      bytes32 id = keccak256(msg.sender, nonce);
      File storage f = files[id];
      f.bytesize = size;
      f.name = name;
      f.ipfs_hash = hash;
      f.root = root;
      return id;
   }

   function getName(bytes32 id) public view returns (string) {
      return files[id].name;
   }

   function getNameHash(bytes32 id) public view returns (bytes32) {
      return hashName(files[id].name);
   }

   function getHash(bytes32 id) public view returns (string) {
      return files[id].ipfs_hash;
   }

   function getByteSize(bytes32 id) public view returns (uint) {
      return files[id].bytesize;
   }

   function setByteSize(bytes32 id, uint sz) public returns (uint) {
      files[id].bytesize = sz;
   }

   function getData(bytes32 id) public view returns (bytes32[]) {
      File storage f = files[id];
      return f.data;
   }

   function forwardData(bytes32 id, address a) public {
      File storage f = files[id];
      Consumer(a).consume(id, f.data);
   }

   function getRoot(bytes32 id) public view returns (bytes32) {
      File storage f = files[id];
      return f.root;
   }
   function getLeaf(bytes32 id, uint loc) public view returns (bytes32) {
      File storage f = files[id];
      return f.data[loc];
   }

   // Methods to build IO blocks
   struct Bundle {
      bytes32 name_file;
      bytes32 data_file;
      bytes32 size_file;
      uint pointer;
      address code;
      string code_file;
      bytes32 init;
      bytes32[] files;
   }

   mapping (bytes32 => Bundle) bundles;

   function makeSimpleBundle(uint num, address code, bytes32 code_init, bytes32 file_id) public returns (bytes32) {
       bytes32 id = keccak256(msg.sender, num);
       Bundle storage b = bundles[id];
       b.code = code;

       bytes32 res1 = bytes32(getByteSize(file_id));
       for (uint i = 0; i < 3; i++) res1 = keccak256(res1, zero[i]);

       bytes32 res2 = hashName(getName(file_id));
       for (i = 0; i < 3; i++) res2 = keccak256(res2, zero[i]);

       bytes32 res3 = getRoot(file_id);
       for (i = 0; i < 3; i++) res3 = keccak256(res3, zero[i]);

       b.init = keccak256(code_init, res1, res2, res3);

       b.files.push(file_id);

       return id;
   }

   bytes32 empty_file = 0x290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e563;

   function finalizeBundleIPFS(bytes32 id, string file, bytes32 init) public {
       Bundle storage b = bundles[id];
       bytes32[] memory res1 = new bytes32[](b.files.length);
       bytes32[] memory res2 = new bytes32[](b.files.length);
       bytes32[] memory res3 = new bytes32[](b.files.length);

       for (uint i = 0; i < b.files.length; i++) {
          res1[i] = bytes32(getByteSize(b.files[i]));
          res2[i] = hashName(getName(b.files[i]));
          res3[i] = getRoot(b.files[i]);
       }

       b.code_file = file;

       b.init = keccak256(init, calcMerkle(res1, 0, 10), calcMerkle(res2, 0, 10), calcMerkleDefault(res3, 0, 10, empty_file));
   }

   function debug_finalizeBundleIPFS(bytes32 id, string file, bytes32 init) public returns (bytes32, bytes32, bytes32, bytes32, bytes32) {
       Bundle storage b = bundles[id];
       bytes32[] memory res1 = new bytes32[](b.files.length);
       bytes32[] memory res2 = new bytes32[](b.files.length);
       bytes32[] memory res3 = new bytes32[](b.files.length);

       for (uint i = 0; i < b.files.length; i++) {
          res1[i] = bytes32(getByteSize(b.files[i]));
          res2[i] = hashName(getName(b.files[i]));
          res3[i] = getRoot(b.files[i]);
       }

       b.code_file = file;

       return (init, calcMerkle(res1, 0, 10), calcMerkle(res2, 0, 10), calcMerkleDefault(res3, 0, 4, empty_file),
               keccak256(init, calcMerkle(res1, 0, 10), calcMerkle(res2, 0, 4), calcMerkleDefault(res3, 0, 4, empty_file)));
   }

   function makeBundle(uint num) public view returns (bytes32) {
       bytes32 id = keccak256(msg.sender, num);
       return id;
   }

   function addToBundle(bytes32 id, bytes32 file_id) public returns (bytes32) {
       Bundle storage b = bundles[id];
       b.files.push(file_id);
   }

   function getInitHash(bytes32 bid) public view returns (bytes32) {
       Bundle storage b = bundles[bid];
       return b.init;
   }

   function getCode(bytes32 bid) public view returns (bytes) {
       Bundle storage b = bundles[bid];
       return getCodeAtAddress(b.code);
   }

   function getIPFSCode(bytes32 bid) public view returns (string) {
       Bundle storage b = bundles[bid];
       return b.code_file;
   }

   function getFiles(bytes32 bid) public view returns (bytes32[]) {
       Bundle storage b = bundles[bid];
       return b.files;
   }

   function getCodeAtAddress(address a) internal view returns (bytes) {
        uint len;
        assembly {
            len := extcodesize(a)
        }
        bytes memory bs = new bytes(len);
        assembly {
            extcodecopy(a, add(bs,32), 0, len)
        }
        return bs;
   }

   function makeMerkle(bytes arr, uint idx, uint level) internal pure returns (bytes32) {
      if (level == 0) return idx < arr.length ? bytes32(uint(arr[idx])) : bytes32(0);
      else return keccak256(makeMerkle(arr, idx, level-1), makeMerkle(arr, idx+(2**(level-1)), level-1));
   }

   function calcMerkle(bytes32[] arr, uint idx, uint level) internal returns (bytes32) {
      if (level == 0) return idx < arr.length ? arr[idx] : bytes32(0);
      else return keccak256(calcMerkle(arr, idx, level-1), calcMerkle(arr, idx+(2**(level-1)), level-1));
   }

   function fileMerkle(bytes32[] arr, uint idx, uint level) internal returns (bytes32) {
      if (level == 0) return idx < arr.length ? keccak256(bytes16(arr[idx]), uint128(arr[idx])) : keccak256(bytes16(0), bytes16(0));
      else return keccak256(fileMerkle(arr, idx, level-1), fileMerkle(arr, idx+(2**(level-1)), level-1));
   }

   function calcMerkleDefault(bytes32[] arr, uint idx, uint level, bytes32 def) internal returns (bytes32) {
      if (level == 0) return idx < arr.length ? arr[idx] : def;
      else return keccak256(calcMerkleDefault(arr, idx, level-1, def), calcMerkleDefault(arr, idx+(2**(level-1)), level-1, def));
   }

   // assume 256 bytes?
   function hashName(string name) public pure returns (bytes32) {
      return makeMerkle(bytes(name), 0, 8);
   }

}


set firstUserMade in addFirstUser

set firstUserMade in addFirstUser

pragma solidity ^0.4.0;

import "./Concept.sol";
import "./ConceptRegistry.sol";

/*
@type: contract
@name: UserRegistry
@purpose: To store data about users for easy, secure access and manage token balances
*/
contract UserRegistry {
  address public conceptRegistry; //Tnce
  mapping (address => uint) public balances; //Maps the addresses of users to their token balances
  mapping (address => bool) public availability;
  mapping (address => mapping (address => uint)) public allowed;
  bool firstUserMade = false; //Keeps track of whether or not the first user has been made yet
  event Notification(address user, address sender, uint topic);
    /*
      0 = You've started an assessment
      1 = Called As A Potential Assessor
      2 = Confirmed for assessing, stake has been taken
      3 = Assessment Cancled and you have been refunded
      4 = Assessment Has Started
      5 = Send in Score
      6 = Payout
    */

  modifier onlyConcept() {
    if(ConceptRegistry(conceptRegistry).conceptExists(msg.sender) == false)
    {
      throw;
    }
    _;
  }

  modifier onlyThis() {
    if(msg.sender != address(this))
    {
      throw;
    }
    _;
  }

  function UserRegistry(address _conceptRegistry) {
    conceptRegistry = _conceptRegistry;
  }

  function toggleAvailability() {
    availability[msg.sender] = !availability[msg.sender];
  }

  function notification(address user, uint topic) {
    Notification(user, msg.sender, topic);
  }

  function firstUser(address userAddress) {
    if(firstUserMade == false) {
      Concept(ConceptRegistry(conceptRegistry).mewAddress()).addFirstUser(userAddress);
      balances[userAddress] = 1000;
      firstUserMade = true;
    }
  }

  //@purpose: To preform payouts in Asessments
  function addBalance(address _to, uint _amount) returns(bool) {
    if(balances[_to] + _amount > balances[_to]){
      balances[_to] += _amount;
      return true;
    }
    else {
      return false;
    }
  }

  //@purpose: To preform payments and staking for assessments
  function subtractBalance(address _from, uint _amount) returns(bool) {
    if(balances[_from] > _amount){
      balances[_from] -= _amount;
      return true;
    }
    return false;
  }

  function transfer(address _to, uint _amount) returns(bool) {
    if(balances[msg.sender] > _amount &&
       balances[_to] + _amount > balances[_to]) {
      balances[msg.sender] -= _amount;
      balances[_to] += _amount;
      return true;
    }
    else {
      return false;
    }
  }

  function approve(address _spender, uint _amount) returns(bool) {
      allowed[msg.sender][_spender] = _amount;
      return true;
  }

  function transferFrom(address _from, address _to, uint _amount) returns(bool) {
    if(allowed[_from][msg.sender] > _amount &&
       balances[_from] > _amount &&
       balances[_to] > balances[_to] + _amount) {
        balances[_from] -= _amount;
        balances[_to] += _amount;
        allowed[_from][msg.sender] -= _amount;
        return true;
    }
    else {
        return false;
    }
  }

  function remove(address reciever) onlyThis() {
    suicide(reciever);
  }
}

pragma solidity ^0.4.0;

import "./Concept.sol";
import "./ConceptRegistry.sol";

/*
@type: contract
@name: UserRegistry
@purpose: To store data about users for easy, secure access and manage token balances
*/
contract UserRegistry {
  address public conceptRegistry; //Tnce
  mapping (address => uint) public balances; //Maps the addresses of users to their token balances
  mapping (address => bool) public availability;
  mapping (address => mapping (address => uint)) public allowed;
  bool firstUserMade = false; //Keeps track of whether or not the first user has been made yet
  event Notification(address user, address sender, uint topic);
    /*
      0 = You've started an assessment
      1 = Called As A Potential Assessor
      2 = Confirmed for assessing, stake has been taken
      3 = Assessment Cancled and you have been refunded
      4 = Assessment Has Started
      5 = Send in Score
      6 = Payout
    */

  modifier onlyConcept() {
    if(ConceptRegistry(conceptRegistry).conceptExists(msg.sender) == false)
    {
      throw;
    }
    _;
  }

  modifier onlyThis() {
    if(msg.sender != address(this))
    {
      throw;
    }
    _;
  }

  function UserRegistry(address _conceptRegistry) {
    conceptRegistry = _conceptRegistry;
  }

  function toggleAvailability() {
    availability[msg.sender] = !availability[msg.sender];
  }

  function notification(address user, uint topic) {
    Notification(user, msg.sender, topic);
  }

  function firstUser(address userAddress) {
    if(firstUserMade == false) {
      Concept(ConceptRegistry(conceptRegistry).mewAddress()).addFirstUser(userAddress);
      balances[userAddress] = 1000;
    }
  }

  //@purpose: To preform payouts in Asessments
  function addBalance(address _to, uint _amount) returns(bool) {
    if(balances[_to] + _amount > balances[_to]){
      balances[_to] += _amount;
      return true;
    }
    else {
      return false;
    }
  }

  //@purpose: To preform payments and staking for assessments
  function subtractBalance(address _from, uint _amount) returns(bool) {
    if(balances[_from] > _amount){
      balances[_from] -= _amount;
      return true;
    }
    return false;
  }

  function transfer(address _to, uint _amount) returns(bool) {
    if(balances[msg.sender] > _amount &&
       balances[_to] + _amount > balances[_to]) {
      balances[msg.sender] -= _amount;
      balances[_to] += _amount;
      return true;
    }
    else {
      return false;
    }
  }

  function approve(address _spender, uint _amount) returns(bool) {
      allowed[msg.sender][_spender] = _amount;
      return true;
  }

  function transferFrom(address _from, address _to, uint _amount) returns(bool) {
    if(allowed[_from][msg.sender] > _amount &&
       balances[_from] > _amount &&
       balances[_to] > balances[_to] + _amount) {
        balances[_from] -= _amount;
        balances[_to] += _amount;
        allowed[_from][msg.sender] -= _amount;
        return true;
    }
    else {
        return false;
    }
  }

  function remove(address reciever) onlyThis() {
    suicide(reciever);
  }
}