Further micro-optimization.

Further micro-optimization.

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

    struct BlobInfo {               // Single slot.
        bool updatable;             // Can the blob be updated? Cannot be enabled after creation.
        bool forceNewRevisions;     // When updating always make a new revision. Cannot be disabled after creation.
        bool retractable;           // Can the blob be retracted? Cannot be enabled after creation.
        bool disownable;            // Can the blob be disowned? Cannot be enabled after creation.
        uint32 blockNumber;         // Which block has revision 0 of this blob.
        uint32 numRevisions;        // Number of additional revisions.
        address owner;              // Who created this blob.
    }

    mapping (bytes32 => BlobInfo) idBlobInfo;
    mapping (bytes32 => mapping (uint => bytes32)) idPackedRevisionBlockNumbers;

    event logBlob(bytes32 indexed id, uint indexed revisionId, bytes blob);
    event logRetract(bytes32 indexed id);
    event logDisown(bytes32 indexed id);
    event logSetNotUpdatable(bytes32 indexed id);
    event logSetForceNewRevisions(bytes32 indexed id);
    event logSetNotRetractable(bytes32 indexed id);
    event logSetNotDisownable(bytes32 indexed id);

    // Create a 96-bit id for this contract. This is unique across all blockchains.
    // Wait a few minutes after deploying for this id to settle.
    bytes12 constant public contractId = bytes12(sha3(this, block.blockhash(block.number - 1)));

    modifier noValue() {
        if (msg.value > 0) {
            throw;      // Do not maintain a balance.
        }
        _
    }

    modifier isOwner(bytes32 id) {
        if (idBlobInfo[id].owner != msg.sender) {
            throw;
        }
        _
    }

    modifier isUpdatable(bytes32 id) {
        if (!idBlobInfo[id].updatable) {
            throw;
        }
        _
    }

    modifier isRetractable(bytes32 id) {
        if (!idBlobInfo[id].retractable) {
            throw;
        }
        _
    }

    modifier isDisownable(bytes32 id) {
        if (!idBlobInfo[id].disownable) {
            throw;
        }
        _
    }

    /**
     * @dev Stores a blob in the transaction log. It is guaranteed that each user will get a different id from the same nonce.
     * @param blob Blob that should be stored.
     * @return hash Hash of sender and blob.
     */
    function store(bytes blob, bytes32 nonce, bool updatable, bool forceNewRevisions, bool retractable, bool disownable, bool anon) noValue external returns (bytes32 id) {
        // Determine the id.
        id = contractId | (sha3(msg.sender, nonce) & (2 ** 160 - 1));
        // Make sure this id has not been used before.
        if (idBlobInfo[id].blockNumber != 0) {
            throw;
        }
        // Store blob info in state.
        idBlobInfo[id] = BlobInfo({
            updatable: updatable,
            forceNewRevisions: forceNewRevisions,
            retractable: retractable,
            disownable: disownable,
            numRevisions: 0,
            blockNumber: uint32(block.number),
            owner: anon ? 0 : msg.sender,
        });
        // Store the blob in a log in the current block.
        logBlob(id, 0, blob);
    }

    function setPackedRevisionBlockNumber(bytes32 id, uint offset, bool update) internal {
        if (offset % 8 > 0) {
            bytes32 slot = idPackedRevisionBlockNumbers[id][offset / 8];
            if (update) {
                slot &= ~bytes32(uint32(-1) * (2 ** ((offset % 8) * 32)));
            }
            slot |= bytes32(uint32(block.number) * (2 ** ((offset % 8) * 32)));
            idPackedRevisionBlockNumbers[id][offset / 8] = slot;
        }
        else {
            idPackedRevisionBlockNumbers[id][offset / 8] = bytes32(uint32(block.number));
        }
    }

    function update(bytes32 id, bytes blob, bool newRevision) noValue isOwner(id) isUpdatable(id) external returns (uint revisionId) {
        BlobInfo blobInfo = idBlobInfo[id];
        if (newRevision || blobInfo.forceNewRevisions) {
            setPackedRevisionBlockNumber(id, blobInfo.numRevisions++, false);
        }
        else {
            if (blobInfo.numRevisions == 0) {
                blobInfo.blockNumber = uint32(block.number);
            }
            else {
                setPackedRevisionBlockNumber(id, blobInfo.numRevisions - 1, true);
            }
        }
        revisionId = blobInfo.numRevisions;
        // Store the new blob in a log in the current block.
        logBlob(id, revisionId, blob);
    }

    function retract(bytes32 id) noValue isOwner(id) isRetractable(id) external {
        // Delete the packed revision block numbers.
        uint numSlots = (idBlobInfo[id].numRevisions + 7) / 8;
        for (uint i = 0; i < numSlots; i++) {
            delete idPackedRevisionBlockNumbers[id][i];
        }
        // Mark this blob as retracted.
        idBlobInfo[id] = BlobInfo({
            updatable: false,
            forceNewRevisions: false,
            retractable: false,
            disownable: false,
            numRevisions: 0,
            blockNumber: uint32(-1),
            owner: 0,
        });
        // Log that the blob has been retracted.
        logRetract(id);
    }

    function disown(bytes32 id) noValue isOwner(id) isDisownable(id) external {
        // Remove the owner from the blob's state.
        delete idBlobInfo[id].owner;
        // Log as blob as disowned.
        logDisown(id);
    }

    function setNotUpdatable(bytes32 id) noValue isOwner(id) {
        // Record in state that the blob is not updatable.
        idBlobInfo[id].updatable = false;
        // Log that the blob is not updatable.
        logSetNotUpdatable(id);
    }

    function setForceNewTransactions(bytes32 id) noValue isOwner(id) {
        // Record in state that all changes to this blob must be new revisions.
        idBlobInfo[id].forceNewRevisions = true;
        // Log that the blob now forces new revisions.
        logSetForceNewRevisions(id);
    }

    function setNotRetractable(bytes32 id) noValue isOwner(id) {
        // Record in state that the blob is not retractable.
        idBlobInfo[id].retractable = false;
        // Log that the blob is not retractable.
        logSetNotRetractable(id);
    }

    function setNotDisownable(bytes32 id) noValue isOwner(id) {
        // Record in state that the blob is not disownable.
        idBlobInfo[id].disownable = false;
        // Log that the blob is not disownable.
        logSetNotDisownable(id);
    }

    function getInfo(bytes32 id) noValue constant external returns (address owner, bool updatable, bool forceNewRevisions, bool retractable, bool disownable, uint numRevisions, uint latestBlockNumber) {
        owner = idBlobInfo[id].owner;
        updatable = idBlobInfo[id].updatable;
        forceNewRevisions = idBlobInfo[id].forceNewRevisions;
        retractable = idBlobInfo[id].retractable;
        disownable = idBlobInfo[id].disownable;
        numRevisions = idBlobInfo[id].numRevisions;
        latestBlockNumber = getRevisionBlockNumber(id, numRevisions);
    }

    function getOwner(bytes32 id) noValue constant external returns (address owner) {
        owner = idBlobInfo[id].owner;
    }

    function getUpdatable(bytes32 id) noValue constant external returns (bool updatable) {
        updatable = idBlobInfo[id].updatable;
    }

    function getForceNewRevisions(bytes32 id) noValue constant external returns (bool forceNewRevisions) {
        forceNewRevisions = idBlobInfo[id].forceNewRevisions;
    }

    function getRetractable(bytes32 id) noValue constant external returns (bool retractable) {
        retractable = idBlobInfo[id].retractable;
    }

    function getDisownable(bytes32 id) noValue constant external returns (bool disownable) {
        disownable = idBlobInfo[id].disownable;
    }

    function numRevisions(bytes32 id) noValue constant external returns (uint32 numRevisions) {
        numRevisions = idBlobInfo[id].numRevisions;
    }

    function getRevisionBlockNumber(bytes32 id, uint revisionId) noValue constant returns (uint blockNumber) {
        if (revisionId == 0) {
            blockNumber = idBlobInfo[id].blockNumber;
        }
        else {
            bytes32 slot = idPackedRevisionBlockNumbers[id][(revisionId - 1) / 8];
            blockNumber = uint32(uint256(slot) / 2 ** (((revisionId - 1) % 8) * 32));
        }
    }

    function() {
        throw;      // Do not maintain a balance.
    }

}

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

    struct BlobInfo {               // Single slot.
        bool updatable;             // Can the blob be updated? Cannot be enabled after creation.
        bool forceNewRevisions;     // When updating always make a new revision. Cannot be disabled after creation.
        bool retractable;           // Can the blob be retracted? Cannot be enabled after creation.
        bool disownable;            // Can the blob be disowned? Cannot be enabled after creation.
        uint32 blockNumber;         // Which block has revision 0 of this blob.
        uint32 numRevisions;        // Number of additional revisions.
        address owner;              // Who created this blob.
    }

    mapping (bytes32 => BlobInfo) idBlobInfo;
    mapping (bytes32 => mapping (uint => bytes32)) idPackedRevisionBlockNumbers;

    event logBlob(bytes32 indexed id, uint indexed revisionId, bytes blob);
    event logRetract(bytes32 indexed id);
    event logDisown(bytes32 indexed id);
    event logSetNotUpdatable(bytes32 indexed id);
    event logSetForceNewRevisions(bytes32 indexed id);
    event logSetNotRetractable(bytes32 indexed id);
    event logSetNotDisownable(bytes32 indexed id);

    // Create a 96-bit id for this contract. This is unique across all blockchains.
    // Wait a few minutes after deploying for this id to settle.
    bytes12 constant public contractId = bytes12(sha3(this, block.blockhash(block.number - 1)));

    modifier noValue() {
        if (msg.value > 0) {
            throw;      // Do not maintain a balance.
        }
        _
    }

    modifier isOwner(bytes32 id) {
        if (idBlobInfo[id].owner != msg.sender) {
            throw;
        }
        _
    }

    modifier isUpdatable(bytes32 id) {
        if (!idBlobInfo[id].updatable) {
            throw;
        }
        _
    }

    modifier isRetractable(bytes32 id) {
        if (!idBlobInfo[id].retractable) {
            throw;
        }
        _
    }

    modifier isDisownable(bytes32 id) {
        if (!idBlobInfo[id].disownable) {
            throw;
        }
        _
    }

    /**
     * @dev Stores a blob in the transaction log. It is guaranteed that each user will get a different id from the same nonce.
     * @param blob Blob that should be stored.
     * @return hash Hash of sender and blob.
     */
    function store(bytes blob, bytes32 nonce, bool updatable, bool forceNewRevisions, bool retractable, bool disownable, bool anon) noValue external returns (bytes32 id) {
        // Determine the id.
        id = contractId | (sha3(msg.sender, nonce) & (2 ** 160 - 1));
        // Make sure this id has not been used before.
        if (idBlobInfo[id].blockNumber != 0) {
            throw;
        }
        // Store blob info in state.
        idBlobInfo[id] = BlobInfo({
            updatable: updatable,
            forceNewRevisions: forceNewRevisions,
            retractable: retractable,
            disownable: disownable,
            numRevisions: 0,
            blockNumber: uint32(block.number),
            owner: anon ? 0 : msg.sender,
        });
        // Store the blob in a log in the current block.
        logBlob(id, 0, blob);
    }

    function setPackedRevisionBlockNumber(bytes32 id, uint offset, bool update)  internal {
        bytes32 slot;
        if (offset % 8 > 0) {
            uint multiplier = 2 ** ((offset % 8) * 32);
            slot = idPackedRevisionBlockNumbers[id][offset / 8];
            if (update) {
                slot &= ~bytes32(uint32(-1) * multiplier);
            }
            slot |= bytes32(uint32(block.number) * multiplier);
        }
        else {
            slot = bytes32(uint32(block.number));
        }
        idPackedRevisionBlockNumbers[id][offset / 8] = slot;
    }

    function update(bytes32 id, bytes blob, bool newRevision) noValue isOwner(id) isUpdatable(id) external returns (uint revisionId) {
        BlobInfo blobInfo = idBlobInfo[id];
        if (newRevision || blobInfo.forceNewRevisions) {
            setPackedRevisionBlockNumber(id, blobInfo.numRevisions++, false);
        }
        else {
            if (blobInfo.numRevisions == 0) {
                blobInfo.blockNumber = uint32(block.number);
            }
            else {
                setPackedRevisionBlockNumber(id, blobInfo.numRevisions - 1, true);
            }
        }
        revisionId = blobInfo.numRevisions;
        // Store the new blob in a log in the current block.
        logBlob(id, revisionId, blob);
    }

    function retract(bytes32 id) noValue isOwner(id) isRetractable(id) external {
        // Delete the packed revision block numbers.
        uint numSlots = (idBlobInfo[id].numRevisions + 7) / 8;
        for (uint i = 0; i < numSlots; i++) {
            delete idPackedRevisionBlockNumbers[id][i];
        }
        // Mark this blob as retracted.
        idBlobInfo[id] = BlobInfo({
            updatable: false,
            forceNewRevisions: false,
            retractable: false,
            disownable: false,
            numRevisions: 0,
            blockNumber: uint32(-1),
            owner: 0,
        });
        // Log that the blob has been retracted.
        logRetract(id);
    }

    function disown(bytes32 id) noValue isOwner(id) isDisownable(id) external {
        // Remove the owner from the blob's state.
        delete idBlobInfo[id].owner;
        // Log as blob as disowned.
        logDisown(id);
    }

    function setNotUpdatable(bytes32 id) noValue isOwner(id) {
        // Record in state that the blob is not updatable.
        idBlobInfo[id].updatable = false;
        // Log that the blob is not updatable.
        logSetNotUpdatable(id);
    }

    function setForceNewTransactions(bytes32 id) noValue isOwner(id) {
        // Record in state that all changes to this blob must be new revisions.
        idBlobInfo[id].forceNewRevisions = true;
        // Log that the blob now forces new revisions.
        logSetForceNewRevisions(id);
    }

    function setNotRetractable(bytes32 id) noValue isOwner(id) {
        // Record in state that the blob is not retractable.
        idBlobInfo[id].retractable = false;
        // Log that the blob is not retractable.
        logSetNotRetractable(id);
    }

    function setNotDisownable(bytes32 id) noValue isOwner(id) {
        // Record in state that the blob is not disownable.
        idBlobInfo[id].disownable = false;
        // Log that the blob is not disownable.
        logSetNotDisownable(id);
    }

    function getInfo(bytes32 id) noValue constant external returns (address owner, bool updatable, bool forceNewRevisions, bool retractable, bool disownable, uint numRevisions, uint latestBlockNumber) {
        owner = idBlobInfo[id].owner;
        updatable = idBlobInfo[id].updatable;
        forceNewRevisions = idBlobInfo[id].forceNewRevisions;
        retractable = idBlobInfo[id].retractable;
        disownable = idBlobInfo[id].disownable;
        numRevisions = idBlobInfo[id].numRevisions;
        latestBlockNumber = getRevisionBlockNumber(id, numRevisions);
    }

    function getOwner(bytes32 id) noValue constant external returns (address owner) {
        owner = idBlobInfo[id].owner;
    }

    function getUpdatable(bytes32 id) noValue constant external returns (bool updatable) {
        updatable = idBlobInfo[id].updatable;
    }

    function getForceNewRevisions(bytes32 id) noValue constant external returns (bool forceNewRevisions) {
        forceNewRevisions = idBlobInfo[id].forceNewRevisions;
    }

    function getRetractable(bytes32 id) noValue constant external returns (bool retractable) {
        retractable = idBlobInfo[id].retractable;
    }

    function getDisownable(bytes32 id) noValue constant external returns (bool disownable) {
        disownable = idBlobInfo[id].disownable;
    }

    function numRevisions(bytes32 id) noValue constant external returns (uint32 numRevisions) {
        numRevisions = idBlobInfo[id].numRevisions;
    }

    function getRevisionBlockNumber(bytes32 id, uint revisionId) noValue constant returns (uint blockNumber) {
        if (revisionId == 0) {
            blockNumber = idBlobInfo[id].blockNumber;
        }
        else {
            bytes32 slot = idPackedRevisionBlockNumbers[id][(revisionId - 1) / 8];
            blockNumber = uint32(uint256(slot) / 2 ** (((revisionId - 1) % 8) * 32));
        }
    }

    function() {
        throw;      // Do not maintain a balance.
    }

}


Refactor contract

Refactor contract

contract Conference {
	string public name;
	uint256 public balance;
	uint256 public deposit;
	int public capacity;
	int public registered;
	int public attended;
	mapping (address => Participant) public participants;

	struct Participant {
		address addr;
		bool attended;
	}

	event Register(uint256 value, uint256 deposit);

	function Conference() {
		name = 'CodeUp';
		deposit = 1000000000000000000;		// 1 ETH = 10**18 wai
		balance = 0;
		registered = 0;
		attended = 0;
	}

	function register(){
		Register(msg.value, deposit);
		if (msg.value != deposit) throw;

		participants[msg.sender] = Participant(msg.sender, false);
		balance = balance + (deposit * 1);
		registered++;
	}

	function attend(){
		if (isRegistered() != true) throw;

		participants[msg.sender].attended = true;
		attended++;
	}

	function isRegistered() returns (bool){
		return participants[msg.sender].addr != 0x0;
	}

	function isAttended() returns (bool){
		return isRegistered() && participants[msg.sender].attended;
	}
}

contract Conference {
	string public name;
	uint256 public balance;
	uint256 public deposit;
	int public capacity;
	int public registered;
	int public attended;
	mapping (address => Participant) public participants;

	struct Participant {
		address addr;
		bool attended;
	}

	event Register(uint256 value, uint256 deposit, uint256 balance);

	function Conference() {
		name = 'CodeUp';
		deposit = 1000000000000000000;		// 1 ETH = 10**18 wai
		balance = 0;
		registered = 0;
		attended = 0;
	}

	function register(){
		if (msg.value != deposit) throw;

		participants[msg.sender] = Participant(msg.sender, false);
		balance = balance + (deposit * 1);
		registered++;
		Register(msg.value, deposit, balance);
	}

	function attend(){
		if (isRegistered() != true) throw;

		participants[msg.sender].attended = true;
		attended++;
	}

	function isRegistered() returns (bool){
		if (participants[msg.sender].addr != 0x0){
			return true;
		} else {
			return false;
		}
	}

	function isAttended() returns (bool){
		if (isRegistered() && (participants[msg.sender].attended == true)){
			return true;
		} else {
			return false;
		}
	}
}


renaming contract

renaming contract

pragma solidity ^0.4.11;

contract Crowdfund {

  // cryptofund account
  struct Account {
    address uuid;
  }

  // campaign funder
  struct Funder {
    uint uuid;
    uint amount;
    address wallet;
  }

  // campaign
  struct Campaign {
	  address beneficiary; // benefactor of the campaign
    uint fundingGoal; // end goal
	  uint numFunders; // number of funders to the campaign
	  uint amount; // current amount backing campaign
    uint endDate; // ending date time in seconds from epoch
    bool isActive; // is the campaign active
    mapping (address => Funder) funders;
  }

  // utils
  address cryptofund;
  uint numCampaigns = 0;
  mapping (uint => Campaign) campaigns;

  // functionality
  // newCampaign starts a new cryptofund
  function newCampaign(address beneficiary, uint fundingGoal, uint endDate) returns (uint campaignID) {
	  campaignID = numCampaigns++; // campaignID is return variable
	  // Creates new struct and saves in storage. We leave out the mapping type.
	  campaigns[campaignID] = Campaign(beneficiary, fundingGoal, 0, 0, endDate, true);
  }

  // contribute to the campaign
  function contribute(uint campaignID) {
      Campaign c = campaigns[campaignID];
      if (c.isActive) {
      // if this is a new funder, create funder and assign to mapping
        if (c.funders[msg.sender]) {
          c.numFunders++;
          c.funders[msg.sender].push(Funder({uuid: msg.sender, amount: msg.value}));
          c.amount += msg.value;
      } else {
        // otherwise update the funders total contribution
        Funder updatedFunder = c.funders[msg.sender];
        updatedFunder.amount = updatedFunder.amount + msg.value;
        c.funders[msg.sender] = updatedFunder;
      }
    }
  }

  // remove the campaign (mark it unactive)
//  function deleteCampaign(uint campaignID) {
//    Campaign c = campaigns[campaignID];
//    c.isActive = false;
//    this.applyRefund(c);
//    //cryptofund.send(msg.gas);
//  }

  // todo
  // would like to provide a percentage based return policy
//  function applyRefund(Campaign campaign) {
//  }

  // has the campaign reached it's goal?
//	function checkGoalReached(uint campaignID) returns (bool reached) {
//    Campaign c = campaigns[campaignID];
//    return c.amount >= c.fundingGoal;
//	}

  // payout the beneficiary
//  function payout(Campaign compaignID) payable {
//    Campaign c = campaigns[campaignID];
//    if (this.checkGoalReached(campaignID)) {
//      c.beneficiary.transfer(c.amount);
//    } else {
//      this.applyRefund(c);
//    }
//    this.deleteCampaign(campaignID);
//    //cryptofund.send(msg.gas);
//  }

//  function fee(Campaign campaignID) payable {
//    Campaign c = campaigns[campaignID];
//    c.beneficiary.send(campaignID.fundingGoal / 100); //1% fee
//    //cryptofund.send(msg.gas);
//  }

}


Remove SignatureBouncer contract

Remove SignatureBouncer contract

(cherry picked from commit c876254457fcfff717cd79b6122d5dfa228d348f)

pragma solidity ^0.5.0;

import "../GSN/Context.sol";
import "../access/roles/SignerRole.sol";
import "../cryptography/ECDSA.sol";

/**
 * @title SignatureBouncer
 * @author PhABC, Shrugs and aflesher
 * @dev SignatureBouncer allows users to submit a signature as a permission to
 * do an action.
 * If the signature is from one of the authorized signer addresses, the
 * signature is valid.
 * Note that SignatureBouncer offers no protection against replay attacks, users
 * must add this themselves!
 *
 * Signer addresses can be individual servers signing grants or different
 * users within a decentralized club that have permission to invite other
 * members. This technique is useful for whitelists and airdrops; instead of
 * putting all valid addresses on-chain, simply sign a grant of the form
 * keccak256(abi.encodePacked(`:contractAddress` + `:granteeAddress`)) using a
 * valid signer address.
 * Then restrict access to your crowdsale/whitelist/airdrop using the
 * `onlyValidSignature` modifier (or implement your own using _isValidSignature).
 * In addition to `onlyValidSignature`, `onlyValidSignatureAndMethod` and
 * `onlyValidSignatureAndData` can be used to restrict access to only a given
 * method or a given method with given parameters respectively.
 * See the tests in SignatureBouncer.test.js for specific usage examples.
 *
 * @notice A method that uses the `onlyValidSignatureAndData` modifier must make
 * the _signature parameter the "last" parameter. You cannot sign a message that
 * has its own signature in it so the last 128 bytes of msg.data (which
 * represents the length of the _signature data and the _signature data itself)
 * is ignored when validating. Also non fixed sized parameters make constructing
 * the data in the signature much more complex.
 * See https://ethereum.stackexchange.com/a/50616 for more details.
 */
contract SignatureBouncer is Context, SignerRole {
    using ECDSA for bytes32;

    // Function selectors are 4 bytes long, as documented in
    // https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector
    uint256 private constant _METHOD_ID_SIZE = 4;
    // Signature size is 65 bytes (tightly packed v + r + s), but gets padded to 96 bytes
    uint256 private constant _SIGNATURE_SIZE = 96;

    constructor () internal {
        // solhint-disable-previous-line no-empty-blocks
    }

    /**
     * @dev Requires that a valid signature of a signer was provided.
     */
    modifier onlyValidSignature(bytes memory signature) {
        require(_isValidSignature(_msgSender(), signature), "SignatureBouncer: invalid signature for caller");
        _;
    }

    /**
     * @dev Requires that a valid signature with a specified method of a signer was provided.
     */
    modifier onlyValidSignatureAndMethod(bytes memory signature) {
        // solhint-disable-next-line max-line-length
        require(_isValidSignatureAndMethod(_msgSender(), signature), "SignatureBouncer: invalid signature for caller and method");
        _;
    }

    /**
     * @dev Requires that a valid signature with a specified method and params of a signer was provided.
     */
    modifier onlyValidSignatureAndData(bytes memory signature) {
        // solhint-disable-next-line max-line-length
        require(_isValidSignatureAndData(_msgSender(), signature), "SignatureBouncer: invalid signature for caller and data");
        _;
    }

    /**
     * @dev is the signature of `this + account` from a signer?
     * @return bool
     */
    function _isValidSignature(address account, bytes memory signature) internal view returns (bool) {
        return _isValidDataHash(keccak256(abi.encodePacked(address(this), account)), signature);
    }

    /**
     * @dev is the signature of `this + account + methodId` from a signer?
     * @return bool
     */
    function _isValidSignatureAndMethod(address account, bytes memory signature) internal view returns (bool) {
        bytes memory msgData = _msgData();
        bytes memory data = new bytes(_METHOD_ID_SIZE);
        for (uint256 i = 0; i < data.length; i++) {
            data[i] = msgData[i];
        }
        return _isValidDataHash(keccak256(abi.encodePacked(address(this), account, data)), signature);
    }

    /**
     * @dev is the signature of `this + account + methodId + params(s)` from a signer?
     * @notice the signature parameter of the method being validated must be the "last" parameter
     * @return bool
     */
    function _isValidSignatureAndData(address account, bytes memory signature) internal view returns (bool) {
        bytes memory msgData = _msgData();
        require(msgData.length > _SIGNATURE_SIZE, "SignatureBouncer: data is too short");

        bytes memory data = new bytes(msgData.length - _SIGNATURE_SIZE);
        for (uint256 i = 0; i < data.length; i++) {
            data[i] = msgData[i];
        }

        return _isValidDataHash(keccak256(abi.encodePacked(address(this), account, data)), signature);
    }

    /**
     * @dev Internal function to convert a hash to an eth signed message
     * and then recover the signature and check it against the signer role.
     * @return bool
     */
    function _isValidDataHash(bytes32 hash, bytes memory signature) internal view returns (bool) {
        address signer = hash.toEthSignedMessageHash().recover(signature);

        return signer != address(0) && isSigner(signer);
    }
}


Return the top bid to the bidder in a cancelled auction

// This is the main contract that governs execution of auctions
// of non-fungible on-chain assets. Any user can initiate an auction
// for an item that conforms to the Asset interface described in
// Asset.sol

import "Asset.sol";

contract AuctionHouse {

    struct Bid {
	address bidder;
	uint256 amount;
	uint timestamp;
    }

    enum AuctionStatus {Pending, Active, Inactive}

    struct Auction {
	// Location and ownership information of the item for sale
	address seller;
	address contractAddress; // Contract where the item exists
	string recordId;         // RecordID within the contract as per the Asset interface

	// Auction metadata
	string title;
	string description;      // Optionally markdown formatted?
	uint blockNumberOfDeadline;
	AuctionStatus status;

	// Distribution bonus
	uint distributionCut;    // In percent, ie 10 is a 10% cut to the distribution address
	address distributionAddress;

	// Pricing
	uint256 startingPrice;   // In wei
	uint256 reservePrice;
	uint256 currentBid;

	Bid[] bids;
    }

    Auction[] public auctions;          // All auctions
    mapping(address => uint[]) public auctionsRunByUser; // Pointer to auctions index for auctions run by this user

    mapping(address => uint[]) public auctionsBidOnByUser; // Pointer to auctions index for auctions this user has bid on

    address owner;

    // Events
    event AuctionCreated(uint id, string title, uint256 startingPrice, uint256 reservePrice);
    event AuctionActivated(uint id);
    event AuctionCancelled(uint id);
    event BidPlaced(uint auctionId, address bidder, uint256 amount);
    event AuctionEndedWithWinner(uint auctionId, address winningBidder, uint256 amount);
    event AuctionEndedWithoutWinner(uint auctionId, uint256 topBid, uint256 reservePrice);

    event LogFailure(string message);

    modifier onlyOwner {
	if (owner != msg.sender) throw;
	_
    }

    modifier onlySeller(uint auctionId) {
	if (auctions[auctionId].seller != msg.sender) throw;
	_
    }

    modifier onlyLive(uint auctionId) {
	Auction a = auctions[auctionId];
	if (a.status != AuctionStatus.Active) {
	    throw;
	}

	// Auction should not be over
	if (block.number >= a.blockNumberOfDeadline) {
	    throw;
	}
	_
    }

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

    // This is a convenience function for development, testing debugging
    // and catching throws in the tests. Can remove after getting the
    // pattern down.
    function throwTest() {
	throw;
    }

    // Create an auction, transfer the item to this contract, activate the auction
    function createAuction(
	string _title,
	string _description,
	address _contractAddressOfAsset,
	string _recordIdOfAsset,
	uint _deadline,   // in blocknumber
	uint256 _startingPrice,
	uint256 _reservePrice,
	uint _distributionCut,
	address _distributionCutAddress) returns (uint auctionId) {

	    // Check to see if the seller owns the asset at the contract
	    if (!partyOwnsAsset(msg.sender, _contractAddressOfAsset, _recordIdOfAsset)) {
		throw;
	    }

	    // Check to see if the auction deadline is in the future
	    if (block.number >= _deadline) {
		throw;
	    }

	    // Price validations
	    if (_startingPrice < 0 || _reservePrice < 0) {
		throw;
	    }

	    // Distribution validations
	    if (_distributionCut < 0 || _distributionCut > 100) {
		throw;
	    }

	    auctionId = auctions.length++;
	    Auction a = auctions[auctionId];
	    a.seller = msg.sender;
	    a.contractAddress = _contractAddressOfAsset;
	    a.recordId = _recordIdOfAsset;
	    a.title = _title;
	    a.description = _description;
	    a.blockNumberOfDeadline = _deadline;
	    a.status = AuctionStatus.Pending;
	    a.distributionCut = _distributionCut;
	    a.distributionAddress = _distributionCutAddress;
	    a.startingPrice = _startingPrice;
	    a.reservePrice = _reservePrice;
	    a.currentBid = 0;

            auctionsRunByUser[a.seller].push(auctionId);
	    AuctionCreated(auctionId, a.title, a.startingPrice, a.reservePrice);

	    return auctionId;
	}

    function partyOwnsAsset(address _party, address _contract, string _recordId) returns (bool success) {
	Asset assetContract = Asset(_contract);
	return assetContract.owner(_recordId) == _party;
    }

    /**
     * The auction fields are indexed in the return val as follows
     * [0]  -> Auction.seller
     * [1]  -> Auction.contractAddress
     * [2]  -> Auction.recordId
     * [3]  -> Auction.title
     * [4]  -> Auction.description
     * [5]  -> Auction.blockNumberOfDeadline
     * [6]  -> Auction.distributionCut
     * [7]  -> Auction.distributionAddress
     * [8]  -> Auction.startingPrice
     * [9] -> Auction.reservePrice
     * [10] -> Auction.currentBid
     * [11] -> Auction.bids.length
     * []  -> Auction.status (Not included right now)
     */
    function getAuction(uint idx) returns (address, address, string, string, string, uint, uint, address, uint256, uint256, uint256, uint) {
	Auction a = auctions[idx];
	return (a.seller,
		a.contractAddress,
		a.recordId,
		a.title,
		a.description,
		a.blockNumberOfDeadline,
		a.distributionCut,
		a.distributionAddress,
		a.startingPrice,
		a.reservePrice,
		a.currentBid,
		a.bids.length
        );
    }

    function getStatus(uint idx) returns (uint) {
	Auction a = auctions[idx];
	return uint(a.status);
    }

    function getAuctionsCountForUser(address addr) returns (uint) {
        return auctionsRunByUser[addr].length;
    }

    function getAuctionIdForUserAndIdx(address addr, uint idx) returns (uint) {
        return auctionsRunByUser[addr][idx];
    }

    // Checks if this contract address is the owner of the item for the auction
    function activateAuction(uint auctionId) onlySeller(auctionId) returns (bool){
        Auction a = auctions[auctionId];

        if (!partyOwnsAsset(this, a.contractAddress, a.recordId)) throw;

        a.status = AuctionStatus.Active;
	AuctionActivated(auctionId);
        return true;
    }

    function cancelAuction(uint auctionId) onlySeller(auctionId) returns (bool) {
        Auction a = auctions[auctionId];

        if (!partyOwnsAsset(this, a.contractAddress, a.recordId)) throw;

        Asset asset = Asset(a.contractAddress);
        asset.setOwner(a.recordId, a.seller);

	// Return funds to the bidder
	uint bidsLength = a.bids.length;
	if (bidsLength > 0) {
	    Bid topBid = a.bids[bidsLength - 1];
	    if (!topBid.bidder.send(topBid.amount)) {
		LogFailure("Couldn't return funds to the bidder");
		return false;
	    }
	}

	AuctionCancelled(auctionId);
        a.status = AuctionStatus.Inactive;
	return true;
    }

    /* BIDS */
    function getBidCountForAuction(uint auctionId) returns (uint) {
	Auction a = auctions[auctionId];
	return a.bids.length;
    }

    function getBidForAuctionByIdx(uint auctionId, uint idx) returns (address bidder, uint256 amount, uint timestamp) {
	Auction a = auctions[auctionId];
	if(idx > a.bids.length - 1) {
	    throw;
	}

	Bid b = a.bids[idx];
	return (b.bidder, b.amount, b.timestamp);
    }

    function placeBid(uint auctionId) onlyLive(auctionId) returns (bool success) {
	uint256 amount = msg.value;
	Auction a = auctions[auctionId];

	if (a.currentBid >= amount) {
	    // Want to return the bid amount and return false
	    if(!msg.sender.send(amount)) {
		LogFailure("Could not return the invalid bid amount to the bidder");
	    }
	    return false;
	}

	uint bidIdx = a.bids.length++;
	Bid b = a.bids[bidIdx];
	b.bidder = msg.sender;
	b.amount = amount;
	b.timestamp = now;
	a.currentBid = amount;

	auctionsBidOnByUser[b.bidder].push(auctionId);

	// Return ETH to previous bidder
	if (bidIdx > 0) {
	    Bid previousBid = a.bids[bidIdx - 1];
	    if (!previousBid.bidder.send(previousBid.amount)) {
		LogFailure("Could not return the outbid amount to the previous bidder");
	    }
	}

	BidPlaced(auctionId, b.bidder, b.amount);
	return true;
    }

    function endAuction(uint auctionId) returns (bool success) {
	// Check if the auction is passed the end date
	Auction a = auctions[auctionId];
	if (block.number < a.blockNumberOfDeadline) {
	    LogFailure("Can not end an auction that hasn't hit the deadline yet");
	    return false;
	}

	// No bids, make the auction inactive
	if (a.bids.length == 0) {
	    a.status = AuctionStatus.Inactive;
	    return true;
	}

	Bid topBid = a.bids[a.bids.length - 1];
	Asset asset = Asset(a.contractAddress);

	// If the auction hit its reserve price
	if (a.currentBid >= a.reservePrice) {
	    uint distributionShare = a.currentBid * a.distributionCut / 100;  // Calculate the distribution cut
	    uint sellerShare = a.currentBid - distributionShare;

	    asset.setOwner(a.recordId, topBid.bidder);  // Set the items new owner

	    if (!a.distributionAddress.send(distributionShare)) { LogFailure("Couldn't send the marketing distribution"); }
	    if (!a.seller.send(sellerShare)) { LogFailure("Couldn't send the seller his cut"); }

	    AuctionEndedWithWinner(auctionId, topBid.bidder, a.currentBid);
	} else {
	    // Return the item to the owner and the money to the top bidder
	    asset.setOwner(a.recordId, a.seller);
	    if (!topBid.bidder.send(a.currentBid)) { LogFailure("Couldn't send the top bidder his money back on a failed to meet reserve scenario."); }

	    AuctionEndedWithoutWinner(auctionId, a.currentBid, a.reservePrice);
	}

	a.status = AuctionStatus.Inactive;
	return true;
    }

    function() {
	// Don't allow ether to be sent blindly to this contract
	throw;
    }
}

// This is the main contract that governs execution of auctions
// of non-fungible on-chain assets. Any user can initiate an auction
// for an item that conforms to the Asset interface described in
// Asset.sol

import "Asset.sol";

contract AuctionHouse {

    struct Bid {
	address bidder;
	uint256 amount;
	uint timestamp;
    }

    enum AuctionStatus {Pending, Active, Inactive}

    struct Auction {
	// Location and ownership information of the item for sale
	address seller;
	address contractAddress; // Contract where the item exists
	string recordId;         // RecordID within the contract as per the Asset interface

	// Auction metadata
	string title;
	string description;      // Optionally markdown formatted?
	uint blockNumberOfDeadline;
	AuctionStatus status;

	// Distribution bonus
	uint distributionCut;    // In percent, ie 10 is a 10% cut to the distribution address
	address distributionAddress;

	// Pricing
	uint256 startingPrice;   // In wei
	uint256 reservePrice;
	uint256 currentBid;

	Bid[] bids;
    }

    Auction[] public auctions;          // All auctions
    mapping(address => uint[]) public auctionsRunByUser; // Pointer to auctions index for auctions run by this user

    mapping(address => uint[]) public auctionsBidOnByUser; // Pointer to auctions index for auctions this user has bid on

    address owner;

    // Events
    event AuctionCreated(uint id, string title, uint256 startingPrice, uint256 reservePrice);
    event AuctionActivated(uint id);
    event AuctionCancelled(uint id);
    event BidPlaced(uint auctionId, address bidder, uint256 amount);
    event AuctionEndedWithWinner(uint auctionId, address winningBidder, uint256 amount);
    event AuctionEndedWithoutWinner(uint auctionId, uint256 topBid, uint256 reservePrice);

    event LogFailure(string message);

    modifier onlyOwner {
	if (owner != msg.sender) throw;
	_
    }

    modifier onlySeller(uint auctionId) {
	if (auctions[auctionId].seller != msg.sender) throw;
	_
    }

    modifier onlyLive(uint auctionId) {
	Auction a = auctions[auctionId];
	if (a.status != AuctionStatus.Active) {
	    throw;
	}

	// Auction should not be over
	if (block.number >= a.blockNumberOfDeadline) {
	    throw;
	}
	_
    }

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

    // This is a convenience function for development, testing debugging
    // and catching throws in the tests. Can remove after getting the
    // pattern down.
    function throwTest() {
	throw;
    }

    // Create an auction, transfer the item to this contract, activate the auction
    function createAuction(
	string _title,
	string _description,
	address _contractAddressOfAsset,
	string _recordIdOfAsset,
	uint _deadline,   // in blocknumber
	uint256 _startingPrice,
	uint256 _reservePrice,
	uint _distributionCut,
	address _distributionCutAddress) returns (uint auctionId) {

	    // Check to see if the seller owns the asset at the contract
	    if (!partyOwnsAsset(msg.sender, _contractAddressOfAsset, _recordIdOfAsset)) {
		throw;
	    }

	    // Check to see if the auction deadline is in the future
	    if (block.number >= _deadline) {
		throw;
	    }

	    // Price validations
	    if (_startingPrice < 0 || _reservePrice < 0) {
		throw;
	    }

	    // Distribution validations
	    if (_distributionCut < 0 || _distributionCut > 100) {
		throw;
	    }

	    auctionId = auctions.length++;
	    Auction a = auctions[auctionId];
	    a.seller = msg.sender;
	    a.contractAddress = _contractAddressOfAsset;
	    a.recordId = _recordIdOfAsset;
	    a.title = _title;
	    a.description = _description;
	    a.blockNumberOfDeadline = _deadline;
	    a.status = AuctionStatus.Pending;
	    a.distributionCut = _distributionCut;
	    a.distributionAddress = _distributionCutAddress;
	    a.startingPrice = _startingPrice;
	    a.reservePrice = _reservePrice;
	    a.currentBid = 0;

            auctionsRunByUser[a.seller].push(auctionId);
	    AuctionCreated(auctionId, a.title, a.startingPrice, a.reservePrice);

	    return auctionId;
	}

    function partyOwnsAsset(address _party, address _contract, string _recordId) returns (bool success) {
	Asset assetContract = Asset(_contract);
	return assetContract.owner(_recordId) == _party;
    }

    /**
     * The auction fields are indexed in the return val as follows
     * [0]  -> Auction.seller
     * [1]  -> Auction.contractAddress
     * [2]  -> Auction.recordId
     * [3]  -> Auction.title
     * [4]  -> Auction.description
     * [5]  -> Auction.blockNumberOfDeadline
     * [6]  -> Auction.distributionCut
     * [7]  -> Auction.distributionAddress
     * [8]  -> Auction.startingPrice
     * [9] -> Auction.reservePrice
     * [10] -> Auction.currentBid
     * [11] -> Auction.bids.length
     * []  -> Auction.status (Not included right now)
     */
    function getAuction(uint idx) returns (address, address, string, string, string, uint, uint, address, uint256, uint256, uint256, uint) {
	Auction a = auctions[idx];
	return (a.seller,
		a.contractAddress,
		a.recordId,
		a.title,
		a.description,
		a.blockNumberOfDeadline,
		a.distributionCut,
		a.distributionAddress,
		a.startingPrice,
		a.reservePrice,
		a.currentBid,
		a.bids.length
        );
    }

    function getStatus(uint idx) returns (uint) {
	Auction a = auctions[idx];
	return uint(a.status);
    }

    function getAuctionsCountForUser(address addr) returns (uint) {
        return auctionsRunByUser[addr].length;
    }

    function getAuctionIdForUserAndIdx(address addr, uint idx) returns (uint) {
        return auctionsRunByUser[addr][idx];
    }

    // Checks if this contract address is the owner of the item for the auction
    function activateAuction(uint auctionId) onlySeller(auctionId) returns (bool){
        Auction a = auctions[auctionId];

        if (!partyOwnsAsset(this, a.contractAddress, a.recordId)) throw;

        a.status = AuctionStatus.Active;
	AuctionActivated(auctionId);
        return true;
    }

    function cancelAuction(uint auctionId) onlySeller(auctionId) returns (bool) {
        Auction a = auctions[auctionId];

        if (!partyOwnsAsset(this, a.contractAddress, a.recordId)) throw;

        Asset asset = Asset(a.contractAddress);
        asset.setOwner(a.recordId, a.seller);

	AuctionCancelled(auctionId);
        a.status = AuctionStatus.Inactive;
	return true;
    }

    /* BIDS */
    function getBidCountForAuction(uint auctionId) returns (uint) {
	Auction a = auctions[auctionId];
	return a.bids.length;
    }

    function getBidForAuctionByIdx(uint auctionId, uint idx) returns (address bidder, uint256 amount, uint timestamp) {
	Auction a = auctions[auctionId];
	if(idx > a.bids.length - 1) {
	    throw;
	}

	Bid b = a.bids[idx];
	return (b.bidder, b.amount, b.timestamp);
    }

    function placeBid(uint auctionId) onlyLive(auctionId) returns (bool success) {
	uint256 amount = msg.value;
	Auction a = auctions[auctionId];

	if (a.currentBid >= amount) {
	    // Want to return the bid amount and return false
	    if(!msg.sender.send(amount)) {
		LogFailure("Could not return the invalid bid amount to the bidder");
	    }
	    return false;
	}

	uint bidIdx = a.bids.length++;
	Bid b = a.bids[bidIdx];
	b.bidder = msg.sender;
	b.amount = amount;
	b.timestamp = now;
	a.currentBid = amount;

	auctionsBidOnByUser[b.bidder].push(auctionId);

	// Return ETH to previous bidder
	if (bidIdx > 0) {
	    Bid previousBid = a.bids[bidIdx - 1];
	    if (!previousBid.bidder.send(previousBid.amount)) {
		LogFailure("Could not return the outbid amount to the previous bidder");
	    }
	}

	BidPlaced(auctionId, b.bidder, b.amount);
	return true;
    }

    function endAuction(uint auctionId) returns (bool success) {
	// Check if the auction is passed the end date
	Auction a = auctions[auctionId];
	if (block.number < a.blockNumberOfDeadline) {
	    LogFailure("Can not end an auction that hasn't hit the deadline yet");
	    return false;
	}

	// No bids, make the auction inactive
	if (a.bids.length == 0) {
	    a.status = AuctionStatus.Inactive;
	    return true;
	}

	Bid topBid = a.bids[a.bids.length - 1];
	Asset asset = Asset(a.contractAddress);

	// If the auction hit its reserve price
	if (a.currentBid >= a.reservePrice) {
	    uint distributionShare = a.currentBid * a.distributionCut / 100;  // Calculate the distribution cut
	    uint sellerShare = a.currentBid - distributionShare;

	    asset.setOwner(a.recordId, topBid.bidder);  // Set the items new owner

	    if (!a.distributionAddress.send(distributionShare)) { LogFailure("Couldn't send the marketing distribution"); }
	    if (!a.seller.send(sellerShare)) { LogFailure("Couldn't send the seller his cut"); }

	    AuctionEndedWithWinner(auctionId, topBid.bidder, a.currentBid);
	} else {
	    // Return the item to the owner and the money to the top bidder
	    asset.setOwner(a.recordId, a.seller);
	    if (!topBid.bidder.send(a.currentBid)) { LogFailure("Couldn't send the top bidder his money back on a failed to meet reserve scenario."); }

	    AuctionEndedWithoutWinner(auctionId, a.currentBid, a.reservePrice);
	}

	a.status = AuctionStatus.Inactive;
	return true;
    }

    function() {
	// Don't allow ether to be sent blindly to this contract
	throw;
    }
}


uid always first

uid always first

contract MicropaymentsNetwork
{

    enum ChannelStage
    {
        Empty,
        PartiallyConfirmed,
        Confirmed,
        Closing,
        Closed
    }

    struct MicropaymentsChannel
    {
        ChannelStage stage;

        address from;
        uint fromBalance;

        address to;
        uint toBalance;

        uint balanceTimestamp;
        uint closingBlockNumber;
    }

    uint public constant closingDelay = 10;

    mapping(uint => MicropaymentsChannel) channels;
    mapping(uint => bool) reserved;

    function MicropaymentsNetwork()
    {
    }

    function isAvailable(uint _cid)
        constant
        returns (bool)
    {
        return !reserved[_cid];
    }

    function assertAvailable(uint _cid)
        internal
    {
        if (!isAvailable(_cid))
        {
            throw;
        }
    }

    function assertOnlyFrom(uint _cid)
        internal
    {
        if (msg.sender != channels[_cid].from)
        {
            throw;
        }
    }

    function assertOnlyTo(uint _cid)
        internal
    {
        if (msg.sender != channels[_cid].to)
        {
            throw;
        }
    }

    function assertOnlyParticipants(uint _cid)
        internal
    {
        if ((msg.sender != channels[_cid].from) && (msg.sender != channels[_cid].to))
        {
            throw;
        }
    }

    function assertAtStage(uint _cid, ChannelStage _stage)
        internal
    {
        if (channels[_cid].stage != _stage)
        {
            throw;
        }
    }

    function assertAtOneOfStages(uint _cid, ChannelStage _stage1, ChannelStage _stage2)
    {
        if ((channels[_cid].stage != _stage1) && (channels[_cid].stage != _stage2))
        {
            throw;
        }
    }

    function assertReadyToClose(uint _cid)
    {
        if (block.number < channels[_cid].closingBlockNumber)
        {
            throw;
        }
    }

    function assertYoungerBalance(uint _cid, uint _balanceTimestamp)
        internal
    {
        if (_balanceTimestamp <= channels[_cid].balanceTimestamp)
        {
            throw;
        }
    }

    function assertMatchingBalance(uint _cid, uint _balanceTimestamp)
        internal
    {
        if (_balanceTimestamp != channels[_cid].balanceTimestamp)
        {
            throw;
        }
    }

    function assertSaneBalance(uint _cid, uint _fromBalance, uint _toBalance)
        internal
    {
        if (channels[_cid].fromBalance + channels[_cid].toBalance < _fromBalance + _toBalance)
        {
            throw;
        }
    }

    function assertStillValid(uint _timeout)
        internal
    {
        if (_timeout < now)
        {
            throw;
        }
    }

    function assertSaneHTLC(uint _cid, int _fromToDelta)
        internal
    {
        if ((int(channels[_cid].fromBalance) - _fromToDelta < 0) ||
            (int(channels[_cid].toBalance) + _fromToDelta < 0))
        {
            throw;
        }
    }

    function assertHash(bytes32 _data, bytes32 _hash)
        internal
    {
        if (getHash(_data) != _hash)
        {
            throw;
        }
    }

    function assertSignedByBoth(
        uint _cid,
        bytes32 _sigHash,
        uint8 _sigV,
        bytes32 _sigR,
        bytes32 _sigS)
        internal
    {
        address signer = getSigner(_sigHash, _sigV, _sigR, _sigS);
        if (!(((channels[_cid].from == msg.sender) && (channels[_cid].to == signer)) ||
              ((channels[_cid].from == signer) && (channels[_cid].to == msg.sender))))
        {
            throw;
        }
    }

    function getHash(bytes32 _data)
        constant
        returns (bytes32)
    {
        return sha3(_data);
    }

    function getUpdateHash(
        uint _cid,
        uint _balanceTimestamp,
        uint _fromBalance,
        uint _toBalance)
        constant
        returns(bytes32)
    {
        return sha3(_cid, _balanceTimestamp, _fromBalance, _toBalance);
    }

    function getHTLCHash(
        uint _cid,
        uint _balanceTimestamp,
        uint _timeout,
        bytes32 _hash,
        int _fromToDelta)
        constant
        returns(bytes32)
    {
        return sha3(_cid, _timeout, _hash, _fromToDelta);
    }

    function getSigner(
        bytes32 _sigHash,
        uint8 _sigV,
        bytes32 _sigR,
        bytes32 _sigS)
        constant
        returns(address)
    {
        return ecrecover(_sigHash, _sigV, _sigR, _sigS);
    }

    function createChannel(uint _cid, address _from, address _to)
    {
        assertAvailable(_cid);

        reserved[_cid] = true;
        channels[_cid] = MicropaymentsChannel(ChannelStage.Empty, _from, 0, _to, 0, 0, 0);
    }

    function getFrom(uint _cid)
        constant
        returns (address)
    {
        return channels[_cid].from;
    }

    function getFromBalance(uint _cid)
        constant
        returns (uint)
    {
        return channels[_cid].fromBalance;
    }

    function getTo(uint _cid)
        constant
        returns (address)
    {
        return channels[_cid].to;
    }

    function getToBalance(uint _cid)
        constant
        returns (uint)
    {
        return channels[_cid].toBalance;
    }

    function getBalanceTimestamp(uint _cid)
        constant
        returns (uint)
    {
        return channels[_cid].balanceTimestamp;
    }

    function getClosingBlockNumber(uint _cid)
        constant
        returns (uint)
    {
        return channels[_cid].closingBlockNumber;
    }

    function openChannel(uint _cid)
    {
        assertOnlyFrom(_cid);
        assertAtStage(_cid, ChannelStage.Empty);

        channels[_cid].stage = ChannelStage.PartiallyConfirmed;
        channels[_cid].fromBalance = msg.value;
    }

    function confirmChannel(uint _cid)
    {
        assertOnlyTo(_cid);
        assertAtStage(_cid, ChannelStage.PartiallyConfirmed);

        channels[_cid].stage = ChannelStage.Confirmed;
        channels[_cid].toBalance = msg.value;
    }

    function requestClosingChannel(uint _cid)
    {
        assertOnlyParticipants(_cid);
        assertAtOneOfStages(_cid, ChannelStage.PartiallyConfirmed, ChannelStage.Confirmed);

        if (channels[_cid].stage == ChannelStage.PartiallyConfirmed)
        {
            channels[_cid].stage = ChannelStage.Closed;
        }
        else
        {
            channels[_cid].stage = ChannelStage.Closing;
            channels[_cid].closingBlockNumber = block.number + closingDelay;
        }
    }

    function closeChannel(uint _cid)
    {
        assertOnlyParticipants(_cid);
        assertAtStage(_cid, ChannelStage.Closing);
        assertReadyToClose(_cid);

        channels[_cid].stage = ChannelStage.Closed;
    }

    function withdrawFrom(uint _cid)
    {
        assertOnlyFrom(_cid);
        assertAtStage(_cid, ChannelStage.Closed);

        uint balance = channels[_cid].fromBalance;
        channels[_cid].fromBalance = 0;
        channels[_cid].from.send(balance);
    }

    function withdrawTo(uint _cid)
    {
        assertOnlyTo(_cid);
        assertAtStage(_cid, ChannelStage.Closed);

        uint balance = channels[_cid].toBalance;
        channels[_cid].toBalance = 0;
        channels[_cid].to.send(balance);
    }

    function updateChannelState(
        uint _cid,
        uint _balanceTimestamp,
        uint _fromBalance,
        uint _toBalance,
        uint8 _sigV,
        bytes32 _sigR,
        bytes32 _sigS)
    {
        assertOnlyParticipants(_cid);
        assertAtOneOfStages(_cid, ChannelStage.Confirmed, ChannelStage.Closing);
        assertYoungerBalance(_cid, _balanceTimestamp);
        assertSaneBalance(_cid, _fromBalance, _toBalance);
        assertSignedByBoth(_cid, getUpdateHash(_cid, _balanceTimestamp, _fromBalance, _toBalance), _sigV, _sigR, _sigS);

        channels[_cid].balanceTimestamp = _balanceTimestamp;
        channels[_cid].fromBalance = _fromBalance;
        channels[_cid].toBalance = _toBalance;
    }

    function resolveHTLC(
        uint _cid,
        uint _balanceTimestamp,
        uint _timeout,
        bytes32 _hash,
        int _fromToDelta,
        bytes32 _data,
        uint8 _sigV,
        bytes32 _sigR,
        bytes32 _sigS)
    {
        assertOnlyParticipants(_cid);
        assertAtOneOfStages(_cid, ChannelStage.Confirmed, ChannelStage.Closing);
        assertMatchingBalance(_cid, _balanceTimestamp);
        assertStillValid(_timeout);
        assertSaneHTLC(_cid, _fromToDelta);
        assertHash(_data, _hash);
        assertSignedByBoth(_cid, getHTLCHash(_cid, _balanceTimestamp, _timeout, _hash, _fromToDelta), _sigV, _sigR, _sigS);

        channels[_cid].fromBalance = uint(int(channels[_cid].fromBalance) - _fromToDelta);
        channels[_cid].toBalance = uint(int(channels[_cid].toBalance) + _fromToDelta);
    }
}

contract MicropaymentsNetwork
{

    enum ChannelStage
    {
        Empty,
        PartiallyConfirmed,
        Confirmed,
        Closing,
        Closed
    }

    struct MicropaymentsChannel
    {
        ChannelStage stage;

        address from;
        uint fromBalance;

        address to;
        uint toBalance;

        uint balanceTimestamp;
        uint closingBlockNumber;
    }

    uint public constant closingDelay = 10;

    mapping(uint => MicropaymentsChannel) channels;
    mapping(uint => bool) reserved;

    function MicropaymentsNetwork()
    {
    }

    function isAvailable(uint _cid)
        constant
        returns (bool)
    {
        return !reserved[_cid];
    }

    function assertAvailable(uint _cid)
        internal
    {
        if (!isAvailable(_cid))
        {
            throw;
        }
    }

    function assertOnlyFrom(uint _cid)
        internal
    {
        if (msg.sender != channels[_cid].from)
        {
            throw;
        }
    }

    function assertOnlyTo(uint _cid)
        internal
    {
        if (msg.sender != channels[_cid].to)
        {
            throw;
        }
    }

    function assertOnlyParticipants(uint _cid)
        internal
    {
        if ((msg.sender != channels[_cid].from) && (msg.sender != channels[_cid].to))
        {
            throw;
        }
    }

    function assertAtStage(uint _cid, ChannelStage _stage)
        internal
    {
        if (channels[_cid].stage != _stage)
        {
            throw;
        }
    }

    function assertAtOneOfStages(uint _cid, ChannelStage _stage1, ChannelStage _stage2)
    {
        if ((channels[_cid].stage != _stage1) && (channels[_cid].stage != _stage2))
        {
            throw;
        }
    }

    function assertReadyToClose(uint _cid)
    {
        if (block.number < channels[_cid].closingBlockNumber)
        {
            throw;
        }
    }

    function assertYoungerBalance(uint _cid, uint _balanceTimestamp)
        internal
    {
        if (_balanceTimestamp <= channels[_cid].balanceTimestamp)
        {
            throw;
        }
    }

    function assertMatchingBalance(uint _cid, uint _balanceTimestamp)
        internal
    {
        if (_balanceTimestamp != channels[_cid].balanceTimestamp)
        {
            throw;
        }
    }

    function assertSaneBalance(uint _cid, uint _fromBalance, uint _toBalance)
        internal
    {
        if (channels[_cid].fromBalance + channels[_cid].toBalance < _fromBalance + _toBalance)
        {
            throw;
        }
    }

    function assertStillValid(uint _timeout)
        internal
    {
        if (_timeout < now)
        {
            throw;
        }
    }

    function assertSaneHTLC(uint _cid, int _fromToDelta)
        internal
    {
        if ((int(channels[_cid].fromBalance) - _fromToDelta < 0) ||
            (int(channels[_cid].toBalance) + _fromToDelta < 0))
        {
            throw;
        }
    }

    function assertHash(bytes32 _data, bytes32 _hash)
        internal
    {
        if (getHash(_data) != _hash)
        {
            throw;
        }
    }

    function assertSignedByBoth(
        uint _cid,
        bytes32 _sigHash,
        uint8 _sigV,
        bytes32 _sigR,
        bytes32 _sigS)
        internal
    {
        address signer = getSigner(_sigHash, _sigV, _sigR, _sigS);
        if (!(((channels[_cid].from == msg.sender) && (channels[_cid].to == signer)) ||
              ((channels[_cid].from == signer) && (channels[_cid].to == msg.sender))))
        {
            throw;
        }
    }

    function getHash(bytes32 _data)
        constant
        returns (bytes32)
    {
        return sha3(_data);
    }

    function getUpdateHash(
        uint _cid,
        uint _balanceTimestamp,
        uint _fromBalance,
        uint _toBalance)
        constant
        returns(bytes32)
    {
        return sha3(_cid, _balanceTimestamp, _fromBalance, _toBalance);
    }

    function getHTLCHash(
        uint _cid,
        uint _balanceTimestamp,
        uint _timeout,
        bytes32 _hash,
        int _fromToDelta)
        constant
        returns(bytes32)
    {
        return sha3(_cid, _timeout, _hash, _fromToDelta);
    }

    function getSigner(
        bytes32 _sigHash,
        uint8 _sigV,
        bytes32 _sigR,
        bytes32 _sigS)
        constant
        returns(address)
    {
        return ecrecover(_sigHash, _sigV, _sigR, _sigS);
    }

    function createChannel(address _from, address _to, uint _cid)
    {
        assertAvailable(_cid);

        reserved[_cid] = true;
        channels[_cid] = MicropaymentsChannel(ChannelStage.Empty, _from, 0, _to, 0, 0, 0);
    }

    function getFrom(uint _cid)
        constant
        returns (address)
    {
        return channels[_cid].from;
    }

    function getFromBalance(uint _cid)
        constant
        returns (uint)
    {
        return channels[_cid].fromBalance;
    }

    function getTo(uint _cid)
        constant
        returns (address)
    {
        return channels[_cid].to;
    }

    function getToBalance(uint _cid)
        constant
        returns (uint)
    {
        return channels[_cid].toBalance;
    }

    function getBalanceTimestamp(uint _cid)
        constant
        returns (uint)
    {
        return channels[_cid].balanceTimestamp;
    }

    function getClosingBlockNumber(uint _cid)
        constant
        returns (uint)
    {
        return channels[_cid].closingBlockNumber;
    }

    function openChannel(uint _cid)
    {
        assertOnlyFrom(_cid);
        assertAtStage(_cid, ChannelStage.Empty);

        channels[_cid].stage = ChannelStage.PartiallyConfirmed;
        channels[_cid].fromBalance = msg.value;
    }

    function confirmChannel(uint _cid)
    {
        assertOnlyTo(_cid);
        assertAtStage(_cid, ChannelStage.PartiallyConfirmed);

        channels[_cid].stage = ChannelStage.Confirmed;
        channels[_cid].toBalance = msg.value;
    }

    function requestClosingChannel(uint _cid)
    {
        assertOnlyParticipants(_cid);
        assertAtOneOfStages(_cid, ChannelStage.PartiallyConfirmed, ChannelStage.Confirmed);

        if (channels[_cid].stage == ChannelStage.PartiallyConfirmed)
        {
            channels[_cid].stage = ChannelStage.Closed;
        }
        else
        {
            channels[_cid].stage = ChannelStage.Closing;
            channels[_cid].closingBlockNumber = block.number + closingDelay;
        }
    }

    function closeChannel(uint _cid)
    {
        assertOnlyParticipants(_cid);
        assertAtStage(_cid, ChannelStage.Closing);
        assertReadyToClose(_cid);

        channels[_cid].stage = ChannelStage.Closed;
    }

    function withdrawFrom(uint _cid)
    {
        assertOnlyFrom(_cid);
        assertAtStage(_cid, ChannelStage.Closed);

        uint balance = channels[_cid].fromBalance;
        channels[_cid].fromBalance = 0;
        channels[_cid].from.send(balance);
    }

    function withdrawTo(uint _cid)
    {
        assertOnlyTo(_cid);
        assertAtStage(_cid, ChannelStage.Closed);

        uint balance = channels[_cid].toBalance;
        channels[_cid].toBalance = 0;
        channels[_cid].to.send(balance);
    }

    function updateChannelState(
        uint _cid,
        uint _balanceTimestamp,
        uint _fromBalance,
        uint _toBalance,
        uint8 _sigV,
        bytes32 _sigR,
        bytes32 _sigS)
    {
        assertOnlyParticipants(_cid);
        assertAtOneOfStages(_cid, ChannelStage.Confirmed, ChannelStage.Closing);
        assertYoungerBalance(_cid, _balanceTimestamp);
        assertSaneBalance(_cid, _fromBalance, _toBalance);
        assertSignedByBoth(_cid, getUpdateHash(_cid, _balanceTimestamp, _fromBalance, _toBalance), _sigV, _sigR, _sigS);

        channels[_cid].balanceTimestamp = _balanceTimestamp;
        channels[_cid].fromBalance = _fromBalance;
        channels[_cid].toBalance = _toBalance;
    }

    function resolveHTLC(
        uint _cid,
        uint _balanceTimestamp,
        uint _timeout,
        bytes32 _hash,
        int _fromToDelta,
        bytes32 _data,
        uint8 _sigV,
        bytes32 _sigR,
        bytes32 _sigS)
    {
        assertOnlyParticipants(_cid);
        assertAtOneOfStages(_cid, ChannelStage.Confirmed, ChannelStage.Closing);
        assertMatchingBalance(_cid, _balanceTimestamp);
        assertStillValid(_timeout);
        assertSaneHTLC(_cid, _fromToDelta);
        assertHash(_data, _hash);
        assertSignedByBoth(_cid, getHTLCHash(_cid, _balanceTimestamp, _timeout, _hash, _fromToDelta), _sigV, _sigR, _sigS);

        channels[_cid].fromBalance = uint(int(channels[_cid].fromBalance) - _fromToDelta);
        channels[_cid].toBalance = uint(int(channels[_cid].toBalance) + _fromToDelta);
    }
}


added blackswan.sol

added blackswan.sol

pragma solidity ^0.4.0;
contract BlackSwan {

	struct EntityStruct {

	    string enode;
	    bool isEntity;
	}

	mapping(address => EntityStruct) public entityStructs;
	address[] public entityList;

	function isEntity(address entityAddress) public constant returns(bool isIndeed) {
		return entityStructs[entityAddress].isEntity;
	   }

	function getEntityCount() public constant returns(uint entityCount) {
		return entityList.length;
	}

	function newEntity(address entityAddress, string enode) public returns(uint rowNumber) {

		if(isEntity(entityAddress)) revert();
		entityStructs[entityAddress].enode = enode;
		entityStructs[entityAddress].isEntity = true;
		return entityList.push(entityAddress) -1;
	}

	function updateEntity(address entityAddress, string enode) public returns(bool success) {
		if(!isEntity(entityAddress)) revert();
		entityStructs[entityAddress].enode = enode;
		return true;
	}

	address public owner;
	string[6] greetings;

	function BlackSwan()  {
		owner = msg.sender;

		greetings[0] = "Hi, my name is Omar Metwally.";
		greetings[1] = "I am the creator of this contract.";
		greetings[2] = "Black Swan Lives!";
		greetings[3] = "Watching Parnassus on a beautiful, sunny day in SF...";
		greetings[4] = "Healthcare is a human right.";
	}

    /* Generates a random number from 0 to 10 based on the last block hash */
    function randomGen(uint seed) constant returns (uint randomNumber) {
        return(uint(sha3(block.blockhash(block.number-1), seed ))%10);
    }

	event NewEntity (
		address addr,
		string enode
	);

    function add_entity(string enode) public returns(uint rowNumber) {
	if (isEntity(msg.sender)) {
		updateEntity(msg.sender, enode);
	} else {
		newEntity(msg.sender, enode);
	}
    }

	// retrieve record using IPFS hash (input)
	// returns Record elements, namely id, ipfs hash, description,
	// shared_by_fingerprint and shared_with_fingerprint
	function get_enode() public returns (string _enode) {

	    if (isEntity(msg.sender)) {
		return entityStructs[msg.sender].enode;
	    }

	    return "null";
	}

	function greet_omar(uint _i) public returns (string greeting) {
		require(_i>=0);
		require(_i<greetings.length);
		return greetings[_i];
	}

}

error: pathspec 'ddash/source/blackswan.sol' did not match any file(s) known to git


Added stampIn/stamp out (needs to be tested!!!),

pragma solidity ^0.4.11;
import "./mortal.sol";
import "./Storage.sol";

/// @title Immigration
/// version 0.2
/// The immigration acts as a the border patrol. Citizens passing Immigration
/// have to provide a valid visa. The visa will be stamped when entering and
/// leaving the country
contract Immigration is owned, mortal {
    address usedStorage;
    address nationCtrl;

    struct Visa {
        address owner;
        uint country; // as ISO 3166-1 numeric code
        bytes32 identifier;
        uint amountPaid;
        uint price;
        uint entered; // highest block # when entering country
        uint left;    // highest block # when leaving country
    }

    /*mapping(address => uint) countries;*/
    mapping (address => uint) immigrationOfCountry;

    modifier onlyImmigration() {
        require(immigrationOfCountry[msg.sender] != 0);
        _;
    }

    /*modifier onlyCountry() {
        require(countries[msg.sender] != 0);
        _;
    }*/

    modifier onlyNation() {
        require(msg.sender == nationCtrl);
        _;
    }

    /*modifier sameCountry(uint _country) {
        require(_country == immigrationOfCountry[msg.sender]);
        _;
    }*/

    function Immigration() {
        usedStorage = '0x008aB18490E729bBea993817E0c2B3c19c877115';
    }

    function setStorage(address _store) onlyOwner() returns (bool) {
        usedStorage = _store;
        return true;
    }

    function setNation(address _nation) onlyOwner() returns (bool) {
        nationCtrl = _nation;
        return true;
    }

    /*function addCountry(address _addr, uint _country) onlyOwner() {
        countries[_addr] = _country;
    }*/

    function addImmigrationOfCountry(address _immigration, uint _country) onlyNation() {
        immigrationOfCountry[_immigration] = _country;
    }

    function getPassData(address _user) onlyImmigration() constant returns (address, bytes32, bool) {
        return Storage(usedStorage).passByOwner(_user);
    }

    function getVisa(address _user, uint _country, uint _arrayPosition) onlyImmigration() constant returns(
        address _userAdd,
        uint _countryId,
        bytes32 _identifier,
        uint _amountPaid,
        uint _price,
        uint _entered,
        uint _left)
    {
        _userAdd = _user;
        _countryId = _country;
        _identifier = getVisaIdentifier(_user, _country, _arrayPosition);
        _amountPaid = getVisaAmountPaid(_user, _country, _arrayPosition);
        _price = getVisaPrice(_user, _country, _arrayPosition);
        _entered = getVisaEntered(_user, _country, _arrayPosition);
        _left = getVisaLeft(_user, _country, _arrayPosition);

    }
    function getVisaIdentifier(address _user, uint _country, uint _arrayPosition) onlyImmigration() constant returns(
        bytes32 _identifier
        )
    {
        var(a,b,c,d,e,f,g) = Storage(usedStorage).visaStore(_user, _country, _arrayPosition);
        _identifier = bytes32(c);
    }
    function getVisaAmountPaid(address _user, uint _country, uint _arrayPosition) onlyImmigration() constant returns(
        uint _amountPaid
        )     {
        var(a,b,c,d,e,f,g) = Storage(usedStorage).visaStore(_user, _country, _arrayPosition);
        _amountPaid = uint(d);
    }
    function getVisaPrice(address _user, uint _country, uint _arrayPosition) onlyImmigration() constant returns(
        uint _price
        )     {
        var(a,b,c,d,e,f,g) = Storage(usedStorage).visaStore(_user, _country, _arrayPosition);
        _price = uint(e);
    }
    function getVisaEntered(address _user, uint _country, uint _arrayPosition) onlyImmigration() constant returns(
        uint _entered
        )     {
        var(a,b,c,d,e,f,g) = Storage(usedStorage).visaStore(_user, _country, _arrayPosition);
        _entered = uint(f);
    }
    function getVisaLeft(address _user, uint _country, uint _arrayPosition) onlyImmigration() constant returns(
        uint _left
        )     {
        var(a,b,c,d,e,f,g) = Storage(usedStorage).visaStore(_user, _country, _arrayPosition);
        _left = uint(g);
    }

    function immigrate() returns (bool) {
        return false;
    }

    function emigrate() returns (bool) {
        return false;
    }
    function stampIn(address _owner, uint _country, uint _visaId) {
        require(getVisaEntered(_owner,_country,_visaId) == 0);
        Storage(usedStorage).updateVisa(_owner, _country, _visaId, getVisaAmountPaid(_owner,_country,_visaId), now, 0);
    }
    function stampOut(address _owner, uint _country, uint _visaId) {
        require(getVisaLeft(_owner,_country,_visaId) == 0);
        require(getVisaEntered(_owner,_country,_visaId) <= now);
        Storage(usedStorage).updateVisa(_owner, _country, _visaId, getVisaAmountPaid(_owner,_country,_visaId),getVisaEntered(_owner,_country,_visaId) , now);
    }
}

pragma solidity ^0.4.11;
import "./mortal.sol";
import "./Storage.sol";

/// @title Immigration
/// version 0.2
/// The immigration acts as a the border patrol. Citizens passing Immigration
/// have to provide a valid visa. The visa will be stamped when entering and
/// leaving the country
contract Immigration is owned, mortal {
    address usedStorage;
    address nationCtrl;

    struct Visa {
        address owner;
        uint country; // as ISO 3166-1 numeric code
        bytes32 identifier;
        uint amountPaid;
        uint price;
        uint entered; // highest block # when entering country
        uint left;    // highest block # when leaving country
    }

    /*mapping(address => uint) countries;*/
    mapping (address => uint) immigrationOfCountry;

    modifier onlyImmigration() {
        require(immigrationOfCountry[msg.sender] != 0);
        _;
    }

    /*modifier onlyCountry() {
        require(countries[msg.sender] != 0);
        _;
    }*/

    modifier onlyNation() {
        require(msg.sender == nationCtrl);
        _;
    }

    /*modifier sameCountry(uint _country) {
        require(_country == immigrationOfCountry[msg.sender]);
        _;
    }*/

    function Immigration() {
        usedStorage = '0x008aB18490E729bBea993817E0c2B3c19c877115';
    }

    function setStorage(address _store) onlyOwner() returns (bool) {
        usedStorage = _store;
        return true;
    }

    function setNation(address _nation) onlyOwner() returns (bool) {
        nationCtrl = _nation;
        return true;
    }

    /*function addCountry(address _addr, uint _country) onlyOwner() {
        countries[_addr] = _country;
    }*/

    function addImmigrationOfCountry(address _immigration, uint _country) onlyNation() {
        immigrationOfCountry[_immigration] = _country;
    }

    function getPassData(address _user) onlyImmigration() constant returns (address, bytes32, bool) {
        return Storage(usedStorage).passByOwner(_user);
    }

    function getVisa(address _user, uint _country, uint _arrayPosition) onlyImmigration() constant returns(
        address _userAdd,
        uint _countryId,
        bytes32 _identifier,
        uint _amountPaid,
        uint _price,
        uint _entered,
        uint _left)
    {
        _userAdd = _user;
        _countryId = _country;
        _identifier = getVisaIdentifier(_user, _country, _arrayPosition);
        _amountPaid = getVisaAmountPaid(_user, _country, _arrayPosition);
        _price = getVisaPrice(_user, _country, _arrayPosition);
        _entered = getVisaEntered(_user, _country, _arrayPosition);
        _left = getVisaLeft(_user, _country, _arrayPosition);

    }
    function getVisaIdentifier(address _user, uint _country, uint _arrayPosition) onlyImmigration() constant returns(
        bytes32 _identifier
        )
    {
        var(a,b,c,d,e,f,g) = Storage(usedStorage).visaStore(_user, _country, _arrayPosition);
        _identifier = bytes32(c);
    }
    function getVisaAmountPaid(address _user, uint _country, uint _arrayPosition) onlyImmigration() constant returns(
        uint _amountPaid
        )     {
        var(a,b,c,d,e,f,g) = Storage(usedStorage).visaStore(_user, _country, _arrayPosition);
        _amountPaid = uint(d);
    }
    function getVisaPrice(address _user, uint _country, uint _arrayPosition) onlyImmigration() constant returns(
        uint _price
        )     {
        var(a,b,c,d,e,f,g) = Storage(usedStorage).visaStore(_user, _country, _arrayPosition);
        _price = uint(e);
    }
    function getVisaEntered(address _user, uint _country, uint _arrayPosition) onlyImmigration() constant returns(
        uint _entered
        )     {
        var(a,b,c,d,e,f,g) = Storage(usedStorage).visaStore(_user, _country, _arrayPosition);
        _entered = uint(f);
    }
    function getVisaLeft(address _user, uint _country, uint _arrayPosition) onlyImmigration() constant returns(
        uint _left
        )     {
        var(a,b,c,d,e,f,g) = Storage(usedStorage).visaStore(_user, _country, _arrayPosition);
        _left = uint(g);
    }

    function immigrate() returns (bool) {
        return false;
    }

    function emigrate() returns (bool) {
        return false;
    }
}


added comment for tests

added comment for tests

pragma solidity ^0.4.15;
import './SmartTokenController.sol';
import './Utils.sol';
import './Managed.sol';
import './Pausable.sol';
import './SmartToken.sol';
import './interfaces/ISmartToken.sol';

/*

    The CrowdsaleController allows contributing ether in exchange for Rootcoin tokens
    The price remains fixed for the entire duration of the crowdsale
    Presale contributes are allocated (manually) with additional 20% tokens from the beneficiary tokens.
    Presale contribute mst use pre-verified addresses. (KYC)
*/
contract CrowdsaleController is SmartTokenController, Managed, Pausable {

    uint256 public constant MIN_CONTRIBUTION = 0.01 ether;      // general sale min contribution
    uint256 public constant DURATION = 14 days;                 // crowdsale duration
    uint256 public constant TOKEN_PRICE_N = 1;                  // initial price in wei (numerator)
    uint256 public constant TOKEN_PRICE_D = 1000;               // initial price in wei (denominator) (1000 wei equals 1 token)
    uint256 public constant MAX_GAS_PRICE = 50000000000 wei;    // maximum gas price for contribution transactions
    uint256 public constant MAX_CONTRIBUTION = 40 ether;        // maximum ether allowed to contribute by an unauthorized single account
    uint256 public constant SOFTCAP_GRACE_DURATION = 86400;     // crowdsale softcap reached grace duration in seconds (24 hours) (use 8 seconds for tests)
    uint256 public TOTAL_ETHER_CAP = 1000000 ether;             // overall ether contribution cap
    uint256 public TOTAL_ETHER_SOFT_CAP = 500000 ether;         // overall ether contribution soft cap

    //Presale constants
    uint256 public constant PRESALE_DURATION = 14 days;               // pressale duration
    uint256 public constant PRESALE_MIN_CONTRIBUTION = 200 ether;     // pressale min contribution

    //Token constants
    string public constant TOKEN_NAME = "Rootcoin"; //Token name
    string public constant TOKEN_SYM = "RCT";       //Token symbol
    uint8 public constant TOKEN_DEC = 18;           //Token decimals

    //State variables
    uint256 public startTime = 0;                   // crowdsale start time (in seconds)
    uint256 public endTime = 0;                     // crowdsale end time (in seconds)
    uint256 public totalEtherContributed = 0;       // ether contributed so far
    address public beneficiary = 0x0;               // address to receive all ether contributions
    mapping(address => bool) public whiteList;  //whitelist of accounts that can participate in presale and also contribute more than MAX_CONTRIBUTION

    // triggered on each contribution
    event Contribution(address indexed _contributor, uint256 _amount, uint256 _return);

    /**
        @dev constructor
        @param _startTime      crowdsale start time
        @param _beneficiary    address to receive all ether contributions
    */
    function CrowdsaleController(uint256 _startTime, address _beneficiary)
        SmartTokenController(new SmartToken(TOKEN_NAME, TOKEN_SYM, TOKEN_DEC))
        validAddress(_beneficiary)
        earlierThan(_startTime)
    {
        startTime = _startTime;
        endTime = startTime + DURATION;
        beneficiary = _beneficiary;
        token.disableTransfers(true);
    }

    // verifies that the gas price is lower than 50 gwei
    modifier validGasPrice() {
        assert(tx.gasprice <= MAX_GAS_PRICE);
        _;
    }

    // ensures that it's earlier than the given time
    modifier earlierThan(uint256 _time) {
        assert(now < _time);
        _;
    }

    // ensures that the current time is between _startTime (inclusive) and _endTime (exclusive)
    modifier between(uint256 _startTime, uint256 _endTime) {
        assert(now >= _startTime && now < _endTime);
        _;
    }

    // ensures that we didn't reach the soft ether cap, and sets the end time time when we do. Must be placed before the etherCapNotReached.
    modifier etherSoftCapNotReached(uint256 _contribution) {
        if (safeAdd(totalEtherContributed, _contribution) >= TOTAL_ETHER_SOFT_CAP) {
            endTime = now + SOFTCAP_GRACE_DURATION;
        }
        _;
    }

    // ensures that we didn't reach the ether cap
    modifier etherCapNotReached(uint256 _contribution) {
        assert(safeAdd(totalEtherContributed, _contribution) <= TOTAL_ETHER_CAP);
        _;
    }

    // verifies that the contribution is more than general minimum
    modifier validateMinPrice() {
        require(msg.value >= MIN_CONTRIBUTION);
        _;
    }

    // verifies that the presale contribution is more than presale minimum
    modifier validatePresaleMinPrice() {
        require(msg.value >= PRESALE_MIN_CONTRIBUTION);
        _;
    }

    // verifies that the presale contribution is from predefined address - TBD (not in use unless we decide to make a whitelist.)
    modifier validatePresaleAddress() {
         require(whiteList[msg.sender] == true);
        _;
    }

    // verifies that the total contributions from contributing account do not reach max alloewed unless it is on the whitelist.
    modifier maxAccountContributionNotReached() {
        assert(safeAdd(msg.value, safeMul(token.balanceOf(msg.sender), TOKEN_PRICE_N) / TOKEN_PRICE_D) <= MAX_CONTRIBUTION || whiteList[msg.sender]==true);
        _;
    }

    /**
        @dev computes the number of tokens that should be issued for a given contribution

        @param _contribution    contribution amount

        @return computed number of tokens
    */
    function computeReturn(uint256 _contribution) public constant returns (uint256) {
        // return safeMul(_contribution, TOKEN_PRICE_D) / TOKEN_PRICE_N;
        return safeMul(_contribution, TOKEN_PRICE_D);
    }

    /**
        @dev adds a whitelist address for which there is no max contribution and is alloewed to participate in the presale.

        @param _address    verified contributor address

        @return true
    */
    function addToWhitelist(address _address)
    public
    managerOnly
    returns (bool added)
    {
        whiteList[_address] = true;
        return true;
    }

    /**
        @dev removes a whitelist address for which there is no max contribution and is alloewed to participate in the presale.

        @param _address    verified contributor address to be removed

        @return true
    */
    function removeFromWhitelist(address _address)
    public
    managerOnly
    returns (bool added)
    {
        whiteList[_address] = false;
        return true;
    }

    /**
        @dev ETH contribution
        can only be called during the crowdsale

        @return tokens issued in return
    */
    function contributeETH()
        public
        payable
        between(startTime, endTime)
        whenNotPaused
        validateMinPrice
        maxAccountContributionNotReached
        returns (uint256 amount)
    {
        return processContribution();
    }

     /**
        @dev handles contribution during presale (min 200 ether)
        can only be called 14 days before the crowdsale start date

        @return tokens issued in return
    */
    function contributePreSale()
        public
        payable
        between(safeSub(startTime,PRESALE_DURATION), startTime)
        whenNotPaused
        validatePresaleMinPrice
        validatePresaleAddress
        returns (uint256 amount)
    {
        return processContribution();
    }

     /**
        @dev handles contribution with Fiat - for
        can only be called by manager

        @return tokens issued in return
    */
    function contributeFiat(address _contributor, uint256 _amount)
        public
        payable
        managerOnly
        between(safeSub(startTime,PRESALE_DURATION), safeAdd(startTime, DURATION))
        whenNotPaused
        returns (uint256 amount)
    {
        uint256 tokenAmount = computeReturn(_amount);

        totalEtherContributed = safeAdd(totalEtherContributed, _amount); // update the total contribution amount
        token.issue(_contributor, tokenAmount); // issue new funds to the contributor's address, provided by the manager, in the smart token
        token.issue(beneficiary, tokenAmount); // issue tokens to the beneficiary

        Contribution(_contributor, msg.value, tokenAmount);
        return tokenAmount;
    }

    /**
        @dev handles contribution logic
        note that the Contribution event is triggered using the sender as the contributor, regardless of the actual contributor

        @return tokens issued in return
    */
    function processContribution() private
        active
        etherSoftCapNotReached(msg.value)
        etherCapNotReached(msg.value)
        validGasPrice
        returns (uint256 amount)
    {
        uint256 tokenAmount = computeReturn(msg.value);
        assert(beneficiary.send(msg.value)); // transfer the ether to the beneficiary account
        totalEtherContributed = safeAdd(totalEtherContributed, msg.value); // update the total contribution amount
        token.issue(msg.sender, tokenAmount); // issue new funds to the contributor in the smart token
        token.issue(beneficiary, tokenAmount); // issue tokens to the beneficiary

        Contribution(msg.sender, msg.value, tokenAmount);
        return tokenAmount;
    }

    // fallback
    function() payable {
        contributeETH();
    }
}

pragma solidity ^0.4.15;
import './SmartTokenController.sol';
import './Utils.sol';
import './Managed.sol';
import './Pausable.sol';
import './SmartToken.sol';
import './interfaces/ISmartToken.sol';

/*

    The CrowdsaleController allows contributing ether in exchange for Rootcoin tokens
    The price remains fixed for the entire duration of the crowdsale
    Presale contributes are allocated (manually) with additional 20% tokens from the beneficiary tokens.
    Presale contribute mst use pre-verified addresses. (KYC)
*/
contract CrowdsaleController is SmartTokenController, Managed, Pausable {

    uint256 public constant MIN_CONTRIBUTION = 0.01 ether;      // general sale min contribution
    uint256 public constant DURATION = 14 days;                 // crowdsale duration
    uint256 public constant TOKEN_PRICE_N = 1;                  // initial price in wei (numerator)
    uint256 public constant TOKEN_PRICE_D = 1000;               // initial price in wei (denominator) (1000 wei equals 1 token)
    uint256 public constant MAX_GAS_PRICE = 50000000000 wei;    // maximum gas price for contribution transactions
    uint256 public constant MAX_CONTRIBUTION = 40 ether;        // maximum ether allowed to contribute by an unauthorized single account
    uint256 public constant SOFTCAP_GRACE_DURATION = 86400;     // crowdsale softcap reached grace duration in seconds (10 seconds for tests)
    uint256 public TOTAL_ETHER_CAP = 1000000 ether;             // overall ether contribution cap
    uint256 public TOTAL_ETHER_SOFT_CAP = 500000 ether;         // overall ether contribution soft cap

    //Presale constants
    uint256 public constant PRESALE_DURATION = 14 days;               // pressale duration
    uint256 public constant PRESALE_MIN_CONTRIBUTION = 200 ether;     // pressale min contribution

    //Token constants
    string public constant TOKEN_NAME = "Rootcoin"; //Token name
    string public constant TOKEN_SYM = "RCT";       //Token symbol
    uint8 public constant TOKEN_DEC = 18;           //Token decimals

    //State variables
    uint256 public startTime = 0;                   // crowdsale start time (in seconds)
    uint256 public endTime = 0;                     // crowdsale end time (in seconds)
    uint256 public totalEtherContributed = 0;       // ether contributed so far
    address public beneficiary = 0x0;               // address to receive all ether contributions
    mapping(address => bool) public whiteList;  //whitelist of accounts that can participate in presale and also contribute more than MAX_CONTRIBUTION

    // triggered on each contribution
    event Contribution(address indexed _contributor, uint256 _amount, uint256 _return);

    /**
        @dev constructor
        @param _startTime      crowdsale start time
        @param _beneficiary    address to receive all ether contributions
    */
    function CrowdsaleController(uint256 _startTime, address _beneficiary)
        SmartTokenController(new SmartToken(TOKEN_NAME, TOKEN_SYM, TOKEN_DEC))
        validAddress(_beneficiary)
        earlierThan(_startTime)
    {
        startTime = _startTime;
        endTime = startTime + DURATION;
        beneficiary = _beneficiary;
        token.disableTransfers(true);
    }

    // verifies that the gas price is lower than 50 gwei
    modifier validGasPrice() {
        assert(tx.gasprice <= MAX_GAS_PRICE);
        _;
    }

    // ensures that it's earlier than the given time
    modifier earlierThan(uint256 _time) {
        assert(now < _time);
        _;
    }

    // ensures that the current time is between _startTime (inclusive) and _endTime (exclusive)
    modifier between(uint256 _startTime, uint256 _endTime) {
        assert(now >= _startTime && now < _endTime);
        _;
    }

    // ensures that we didn't reach the soft ether cap, and sets the end time time when we do. Must be placed before the etherCapNotReached.
    modifier etherSoftCapNotReached(uint256 _contribution) {
        if (safeAdd(totalEtherContributed, _contribution) >= TOTAL_ETHER_SOFT_CAP) {
            endTime = now + SOFTCAP_GRACE_DURATION;
        }
        _;
    }

    // ensures that we didn't reach the ether cap
    modifier etherCapNotReached(uint256 _contribution) {
        assert(safeAdd(totalEtherContributed, _contribution) <= TOTAL_ETHER_CAP);
        _;
    }

    // verifies that the contribution is more than general minimum
    modifier validateMinPrice() {
        require(msg.value >= MIN_CONTRIBUTION);
        _;
    }

    // verifies that the presale contribution is more than presale minimum
    modifier validatePresaleMinPrice() {
        require(msg.value >= PRESALE_MIN_CONTRIBUTION);
        _;
    }

    // verifies that the presale contribution is from predefined address - TBD (not in use unless we decide to make a whitelist.)
    modifier validatePresaleAddress() {
         require(whiteList[msg.sender] == true);
        _;
    }

    // verifies that the total contributions from contributing account do not reach max alloewed unless it is on the whitelist.
    modifier maxAccountContributionNotReached() {
        assert(safeAdd(msg.value, safeMul(token.balanceOf(msg.sender), TOKEN_PRICE_N) / TOKEN_PRICE_D) <= MAX_CONTRIBUTION || whiteList[msg.sender]==true);
        _;
    }

    /**
        @dev computes the number of tokens that should be issued for a given contribution

        @param _contribution    contribution amount

        @return computed number of tokens
    */
    function computeReturn(uint256 _contribution) public constant returns (uint256) {
        // return safeMul(_contribution, TOKEN_PRICE_D) / TOKEN_PRICE_N;
        return safeMul(_contribution, TOKEN_PRICE_D);
    }

    /**
        @dev adds a whitelist address for which there is no max contribution and is alloewed to participate in the presale.

        @param _address    verified contributor address

        @return true
    */
    function addToWhitelist(address _address)
    public
    managerOnly
    returns (bool added)
    {
        whiteList[_address] = true;
        return true;
    }

    /**
        @dev removes a whitelist address for which there is no max contribution and is alloewed to participate in the presale.

        @param _address    verified contributor address to be removed

        @return true
    */
    function removeFromWhitelist(address _address)
    public
    managerOnly
    returns (bool added)
    {
        whiteList[_address] = false;
        return true;
    }

    /**
        @dev ETH contribution
        can only be called during the crowdsale

        @return tokens issued in return
    */
    function contributeETH()
        public
        payable
        between(startTime, endTime)
        whenNotPaused
        validateMinPrice
        maxAccountContributionNotReached
        returns (uint256 amount)
    {
        return processContribution();
    }

     /**
        @dev handles contribution during presale (min 200 ether)
        can only be called 14 days before the crowdsale start date

        @return tokens issued in return
    */
    function contributePreSale()
        public
        payable
        between(safeSub(startTime,PRESALE_DURATION), startTime)
        whenNotPaused
        validatePresaleMinPrice
        validatePresaleAddress
        returns (uint256 amount)
    {
        return processContribution();
    }

     /**
        @dev handles contribution with Fiat - for
        can only be called by manager

        @return tokens issued in return
    */
    function contributeFiat(address _contributor, uint256 _amount)
        public
        payable
        managerOnly
        between(safeSub(startTime,PRESALE_DURATION), safeAdd(startTime, DURATION))
        whenNotPaused
        returns (uint256 amount)
    {
        uint256 tokenAmount = computeReturn(_amount);

        totalEtherContributed = safeAdd(totalEtherContributed, _amount); // update the total contribution amount
        token.issue(_contributor, tokenAmount); // issue new funds to the contributor's address, provided by the manager, in the smart token
        token.issue(beneficiary, tokenAmount); // issue tokens to the beneficiary

        Contribution(_contributor, msg.value, tokenAmount);
        return tokenAmount;
    }

    /**
        @dev handles contribution logic
        note that the Contribution event is triggered using the sender as the contributor, regardless of the actual contributor

        @return tokens issued in return
    */
    function processContribution() private
        active
        etherSoftCapNotReached(msg.value)
        etherCapNotReached(msg.value)
        validGasPrice
        returns (uint256 amount)
    {
        uint256 tokenAmount = computeReturn(msg.value);
        assert(beneficiary.send(msg.value)); // transfer the ether to the beneficiary account
        totalEtherContributed = safeAdd(totalEtherContributed, msg.value); // update the total contribution amount
        token.issue(msg.sender, tokenAmount); // issue new funds to the contributor in the smart token
        token.issue(beneficiary, tokenAmount); // issue tokens to the beneficiary

        Contribution(msg.sender, msg.value, tokenAmount);
        return tokenAmount;
    }

    // fallback
    function() payable {
        contributeETH();
    }
}