Add CryptoPunks contract as starting point

pragma solidity ^0.4.8;
contract CryptoPunksMarket {

// You can use this hash to verify the image file containing all the punks
    string public imageHash = "ac39af4793119ee46bbff351d8cb6b5f23da60222126add4268e261199a2921b";

    address owner;

    string public standard = 'CryptoPunks';
    string public name;
    string public symbol;
    uint8 public decimals;
    uint256 public totalSupply;

    uint public nextPunkIndexToAssign = 0;

    bool public allPunksAssigned = false;
    uint public punksRemainingToAssign = 0;

//mapping (address => uint) public addressToPunkIndex;
    mapping (uint => address) public punkIndexToAddress;

/* This creates an array with all balances */
    mapping (address => uint256) public balanceOf;

    struct Offer {
    bool isForSale;
    uint punkIndex;
    address seller;
    uint minValue;          // in ether
    address onlySellTo;     // specify to sell only to a specific person
    }

    struct Bid {
    bool hasBid;
    uint punkIndex;
    address bidder;
    uint value;
    }

// A record of punks that are offered for sale at a specific minimum value, and perhaps to a specific person
    mapping (uint => Offer) public punksOfferedForSale;

// A record of the highest punk bid
    mapping (uint => Bid) public punkBids;

    mapping (address => uint) public pendingWithdrawals;

    event Assign(address indexed to, uint256 punkIndex);
    event Transfer(address indexed from, address indexed to, uint256 value);
    event PunkTransfer(address indexed from, address indexed to, uint256 punkIndex);
    event PunkOffered(uint indexed punkIndex, uint minValue, address indexed toAddress);
    event PunkBidEntered(uint indexed punkIndex, uint value, address indexed fromAddress);
    event PunkBidWithdrawn(uint indexed punkIndex, uint value, address indexed fromAddress);
    event PunkBought(uint indexed punkIndex, uint value, address indexed fromAddress, address indexed toAddress);
    event PunkNoLongerForSale(uint indexed punkIndex);

/* Initializes contract with initial supply tokens to the creator of the contract */
    function CryptoPunksMarket() payable {
    //        balanceOf[msg.sender] = initialSupply;              // Give the creator all initial tokens
        owner = msg.sender;
        totalSupply = 10000;                        // Update total supply
        punksRemainingToAssign = totalSupply;
        name = "CRYPTOPUNKS";                                   // Set the name for display purposes
        symbol = "Ͼ";                               // Set the symbol for display purposes
        decimals = 0;                                       // Amount of decimals for display purposes
    }

    function setInitialOwner(address to, uint punkIndex) {
        if (msg.sender != owner) throw;
        if (allPunksAssigned) throw;
        if (punkIndex >= 10000) throw;
        if (punkIndexToAddress[punkIndex] != to) {
            if (punkIndexToAddress[punkIndex] != 0x0) {
                balanceOf[punkIndexToAddress[punkIndex]]--;
            } else {
                punksRemainingToAssign--;
            }
            punkIndexToAddress[punkIndex] = to;
            balanceOf[to]++;
            Assign(to, punkIndex);
        }
    }

    function setInitialOwners(address[] addresses, uint[] indices) {
        if (msg.sender != owner) throw;
        uint n = addresses.length;
        for (uint i = 0; i < n; i++) {
            setInitialOwner(addresses[i], indices[i]);
        }
    }

    function allInitialOwnersAssigned() {
        if (msg.sender != owner) throw;
        allPunksAssigned = true;
    }

    function getPunk(uint punkIndex) {
        if (!allPunksAssigned) throw;
        if (punksRemainingToAssign == 0) throw;
        if (punkIndexToAddress[punkIndex] != 0x0) throw;
        if (punkIndex >= 10000) throw;
        punkIndexToAddress[punkIndex] = msg.sender;
        balanceOf[msg.sender]++;
        punksRemainingToAssign--;
        Assign(msg.sender, punkIndex);
    }

// Transfer ownership of a punk to another user without requiring payment
    function transferPunk(address to, uint punkIndex) {
        if (!allPunksAssigned) throw;
        if (punkIndexToAddress[punkIndex] != msg.sender) throw;
        if (punkIndex >= 10000) throw;
        if (punksOfferedForSale[punkIndex].isForSale) {
            punkNoLongerForSale(punkIndex);
        }
        punkIndexToAddress[punkIndex] = to;
        balanceOf[msg.sender]--;
        balanceOf[to]++;
        Transfer(msg.sender, to, 1);
        PunkTransfer(msg.sender, to, punkIndex);
    // Check for the case where there is a bid from the new owner and refund it.
    // Any other bid can stay in place.
        Bid bid = punkBids[punkIndex];
        if (bid.bidder == to) {
        // Kill bid and refund value
            pendingWithdrawals[to] += bid.value;
            punkBids[punkIndex] = Bid(false, punkIndex, 0x0, 0);
        }
    }

    function punkNoLongerForSale(uint punkIndex) {
        if (!allPunksAssigned) throw;
        if (punkIndexToAddress[punkIndex] != msg.sender) throw;
        if (punkIndex >= 10000) throw;
        punksOfferedForSale[punkIndex] = Offer(false, punkIndex, msg.sender, 0, 0x0);
        PunkNoLongerForSale(punkIndex);
    }

    function offerPunkForSale(uint punkIndex, uint minSalePriceInWei) {
        if (!allPunksAssigned) throw;
        if (punkIndexToAddress[punkIndex] != msg.sender) throw;
        if (punkIndex >= 10000) throw;
        punksOfferedForSale[punkIndex] = Offer(true, punkIndex, msg.sender, minSalePriceInWei, 0x0);
        PunkOffered(punkIndex, minSalePriceInWei, 0x0);
    }

    function offerPunkForSaleToAddress(uint punkIndex, uint minSalePriceInWei, address toAddress) {
        if (!allPunksAssigned) throw;
        if (punkIndexToAddress[punkIndex] != msg.sender) throw;
        if (punkIndex >= 10000) throw;
        punksOfferedForSale[punkIndex] = Offer(true, punkIndex, msg.sender, minSalePriceInWei, toAddress);
        PunkOffered(punkIndex, minSalePriceInWei, toAddress);
    }

    function buyPunk(uint punkIndex) payable {
        if (!allPunksAssigned) throw;
        Offer offer = punksOfferedForSale[punkIndex];
        if (punkIndex >= 10000) throw;
        if (!offer.isForSale) throw;                // punk not actually for sale
        if (offer.onlySellTo != 0x0 && offer.onlySellTo != msg.sender) throw;  // punk not supposed to be sold to this user
        if (msg.value < offer.minValue) throw;      // Didn't send enough ETH
        if (offer.seller != punkIndexToAddress[punkIndex]) throw; // Seller no longer owner of punk

        address seller = offer.seller;

        punkIndexToAddress[punkIndex] = msg.sender;
        balanceOf[seller]--;
        balanceOf[msg.sender]++;
        Transfer(seller, msg.sender, 1);

        punkNoLongerForSale(punkIndex);
        pendingWithdrawals[seller] += msg.value;
        PunkBought(punkIndex, msg.value, seller, msg.sender);

    // Check for the case where there is a bid from the new owner and refund it.
    // Any other bid can stay in place.
        Bid bid = punkBids[punkIndex];
        if (bid.bidder == msg.sender) {
        // Kill bid and refund value
            pendingWithdrawals[msg.sender] += bid.value;
            punkBids[punkIndex] = Bid(false, punkIndex, 0x0, 0);
        }
    }

    function withdraw() {
        if (!allPunksAssigned) throw;
        uint amount = pendingWithdrawals[msg.sender];
    // Remember to zero the pending refund before
    // sending to prevent re-entrancy attacks
        pendingWithdrawals[msg.sender] = 0;
        msg.sender.transfer(amount);
    }

    function enterBidForPunk(uint punkIndex) payable {
        if (punkIndex >= 10000) throw;
        if (!allPunksAssigned) throw;
        if (punkIndexToAddress[punkIndex] == 0x0) throw;
        if (punkIndexToAddress[punkIndex] == msg.sender) throw;
        if (msg.value == 0) throw;
        Bid existing = punkBids[punkIndex];
        if (msg.value <= existing.value) throw;
        if (existing.value > 0) {
        // Refund the failing bid
            pendingWithdrawals[existing.bidder] += existing.value;
        }
        punkBids[punkIndex] = Bid(true, punkIndex, msg.sender, msg.value);
        PunkBidEntered(punkIndex, msg.value, msg.sender);
    }

    function acceptBidForPunk(uint punkIndex, uint minPrice) {
        if (punkIndex >= 10000) throw;
        if (!allPunksAssigned) throw;
        if (punkIndexToAddress[punkIndex] != msg.sender) throw;
        address seller = msg.sender;
        Bid bid = punkBids[punkIndex];
        if (bid.value == 0) throw;
        if (bid.value < minPrice) throw;

        punkIndexToAddress[punkIndex] = bid.bidder;
        balanceOf[seller]--;
        balanceOf[bid.bidder]++;
        Transfer(seller, bid.bidder, 1);

        punksOfferedForSale[punkIndex] = Offer(false, punkIndex, bid.bidder, 0, 0x0);
        uint amount = bid.value;
        punkBids[punkIndex] = Bid(false, punkIndex, 0x0, 0);
        pendingWithdrawals[seller] += amount;
        PunkBought(punkIndex, bid.value, seller, bid.bidder);
    }

    function withdrawBidForPunk(uint punkIndex) {
        if (punkIndex >= 10000) throw;
        if (!allPunksAssigned) throw;
        if (punkIndexToAddress[punkIndex] == 0x0) throw;
        if (punkIndexToAddress[punkIndex] == msg.sender) throw;
        Bid bid = punkBids[punkIndex];
        if (bid.bidder != msg.sender) throw;
        PunkBidWithdrawn(punkIndex, bid.value, msg.sender);
        uint amount = bid.value;
        punkBids[punkIndex] = Bid(false, punkIndex, 0x0, 0);
    // Refund the bid money
        msg.sender.transfer(amount);
    }

}

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


add Player1 + his alias to event GameJoined

/**
 * Chess contract
 * Stores any amount of games with two players and current state.
 * State encoding:
 *    positive numbers for white, negative numbers for black
 *    <TODO>
 */

contract Chess {
    int8[64] defaultState; // this should be constant if possible

    struct Game {
        address player1;
        address player2;
        string player1Alias;
        string player2Alias;
        address nextPlayer;
        address winner;
        int[64] state;
    }

    mapping (bytes32 => Game) games;

    function Chess() {
        // Just a test to see some output, this should be more storage/cost efficient
        defaultState[0] = 1;
        defaultState[1] = 1;
        defaultState[0x38] = -1;
        defaultState[0x39] = -1;
    }

    event GameInitialized(bytes32 indexed gameId, address indexed player1, string player1Alias);
    event GameJoined(bytes32 indexed gameId, address indexed player1, string player1Alias, address indexed player2, string player2Alias);
    event GameStateChanged(bytes32 indexed gameId, int[64] state);
    event Move(bytes32 indexed gameId, bool indexed moveSuccesful);

    /* Initialize a game */
    function initGame(string player1Alias) public {
        // Generate game id based on player's addresses and current timestamp
        bytes32 gameId = sha3(msg.sender, now);

        // Initialize participants
        games[gameId].player1 = msg.sender;
        games[gameId].player1Alias = player1Alias;

        // Initialize state
        games[gameId].state = defaultState;

        // Game starts with P2
        games[gameId].nextPlayer = games[gameId].player1;

        // Sent notification events
        GameInitialized(gameId, games[gameId].player1, player1Alias);
        GameStateChanged(gameId, games[gameId].state);
    }

    /* Join a game */
    function joinGame(bytes32 gameId, string player2Alias) public {
      if (games[gameId].player2 != 0) {
        throw;
      }

      games[gameId].player2 = msg.sender;
      games[gameId].player2Alias = player2Alias;
      GameJoined(gameId, games[gameId].player1, games[gameId].player1Alias, games[gameId].player2, player2Alias);
    }

    /* Move a figure */
    function move(bytes32 gameId) public {
        // Check that it is this player's turn
        if (games[gameId].nextPlayer != msg.sender) {
            throw;
        }

        // TODO: Validate move

        // TODO: Update state

        // TODO: Set nextPlayer

        // GameStateChanged(gameId, games[gameId].state);
        Move(gameId, true);
    }

    /* This unnamed function is called whenever someone tries to send ether to it */
    function () {
        throw;     // Prevents accidental sending of ether
    }
}

/**
 * Chess contract
 * Stores any amount of games with two players and current state.
 * State encoding:
 *    positive numbers for white, negative numbers for black
 *    <TODO>
 */

contract Chess {
    int8[64] defaultState; // this should be constant if possible

    struct Game {
        address player1;
        address player2;
        string player1Alias;
        string player2Alias;
        address nextPlayer;
        address winner;
        int[64] state;
    }

    mapping (bytes32 => Game) games;

    function Chess() {
        // Just a test to see some output, this should be more storage/cost efficient
        defaultState[0] = 1;
        defaultState[1] = 1;
        defaultState[0x38] = -1;
        defaultState[0x39] = -1;
    }

    event GameInitialized(bytes32 indexed gameId, address indexed player1, string player1Alias);
    event GameJoined(bytes32 indexed gameId, address indexed player2, string player2Alias);
    event GameStateChanged(bytes32 indexed gameId, int[64] state);
    event Move(bytes32 indexed gameId, bool indexed moveSuccesful);

    /* Initialize a game */
    function initGame(string player1Alias) public {
        // Generate game id based on player's addresses and current timestamp
        bytes32 gameId = sha3(msg.sender, now);

        // Initialize participants
        games[gameId].player1 = msg.sender;
        games[gameId].player1Alias = player1Alias;

        // Initialize state
        games[gameId].state = defaultState;

        // Game starts with P2
        games[gameId].nextPlayer = games[gameId].player1;

        // Sent notification events
        GameInitialized(gameId, games[gameId].player1, player1Alias);
        GameStateChanged(gameId, games[gameId].state);
    }

    /* Join a game */
    function joinGame(bytes32 gameId, string player2Alias) public {
      if (games[gameId].player2 != 0) {
        throw;
      }

      games[gameId].player2 = msg.sender;
      games[gameId].player2Alias = player2Alias;
      GameJoined(gameId, games[gameId].player2, player2Alias);
    }

    /* Move a figure */
    function move(bytes32 gameId) public {
        // Check that it is this player's turn
        if (games[gameId].nextPlayer != msg.sender) {
            throw;
        }

        // TODO: Validate move

        // TODO: Update state

        // TODO: Set nextPlayer

        // GameStateChanged(gameId, games[gameId].state);
        Move(gameId, true);
    }

    /* This unnamed function is called whenever someone tries to send ether to it */
    function () {
        throw;     // Prevents accidental sending of ether
    }
}


ENJAllocation - Show circulating supply of Enjin Coins

pragma solidity ^0.4.15;

import './IERC20Token.sol';

contract IENJToken is IERC20Token {
    function crowdfundAddress() public constant returns (address);
    function incentivisationFundAddress() public constant returns (address);
    function totalAllocated() public constant returns (uint256);
}

contract ENJAllocation {
    address public tokenAddress;
    IENJToken token;

    function ENJAllocation(address _tokenAddress){
        tokenAddress = _tokenAddress;
        token = IENJToken(tokenAddress);
    }

    function circulation() constant returns (uint256) {
        return token.totalAllocated() - token.balanceOf(token.incentivisationFundAddress());
    }
}

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


use onlyAgreed to compare agreement terms

pragma solidity ^0.4.15;

// Defines a fund raising asset contract

contract InvestmentAsset {

    // Reference to the investment offer
    address public offerAddress;
    // Asset owner
    address public owner;
    // Asset currency
    string public currency;
    // Asset fixed value
    uint256 public fixedValue;
    // period to return the investment
    uint256 public paybackDays;
    // Gross return of investment
    uint256 public grossReturn;
    // Asset buyer
    address public investor;
    // Protocol version
    string public protocolVersion;
    // Contractual terms hash of investment
    bytes public assetTermsHash;
    // Document hash agreeing the contractual terms
    bytes public agreementHash;
    // investment timestamp
    uint public investedAt;

    // possible stages of an asset
    enum Status {
        AVAILABLE,
        PENDING_OWNER_AGREEMENT,
        INVESTED,
        RETURNED,
        DELAYED_RETURN
    }
    Status public status;

    event Transferred(
        string _id,
        address _from,
        address _to,
        uint256 _value
    );

    event Canceled(
        string _id,
        address _owner,
        address _investor,
        uint256 _value
    );

    event Withdrawal(
        string _id,
        address _owner,
        address _investor,
        uint256 _value,
        bytes _terms
    );

    event Refused(
        string _id,
        address _owner,
        address _investor,
        uint256 _value
    );

    event Returned(
        string _id,
        address _owner,
        address _investor,
        uint256 _value,
        Status _status
    );

    // Checks the current asset's status
    modifier hasStatus(Status _status) {
        assert(status == _status);
        _;
    }

    // Checks if the owner is the caller
    modifier onlyOwner() {
        require(msg.sender == owner);
        _;
    }

    // Checks if the investor is the caller
    modifier onlyInvestor() {
        require(msg.sender == investor);
        _;
    }

    // Compares the agreement terms hash of investor and owner
    modifier onlyAgreed(bytes _agreementHash) {
        require(keccak256(agreementHash) == keccak256(_agreementHash));
        _;
    }

    function InvestmentAsset(
        address _owner,
        string _protocolVersion,
        string _currency,
        uint256 _fixedValue,
        bytes _assetTermsHash,
        uint _paybackDays,
        uint _grossReturn)
        public
    {
        owner = _owner;
        protocolVersion = _protocolVersion;
        currency = _currency;
        fixedValue = _fixedValue;
        assetTermsHash = _assetTermsHash;
        paybackDays = _paybackDays;
        grossReturn = _grossReturn;
        status = Status.AVAILABLE;
    }

    // Refund and remove the current investor and make the asset available for investments
    function makeAvailable()
        hasStatus(Status.PENDING_OWNER_AGREEMENT)
        private
        returns(address, uint256)
    {
        uint256 investedValue = this.balance;
        investor.transfer(investedValue);
        address currentInvestor = investor;
        investor = address(0);
        agreementHash = "";
        status = Status.AVAILABLE;
        investedAt = uint(0);
        return (currentInvestor, investedValue);
    }

    // Add investment interest in this asset and retain the funds within the smart contract
    function invest(string _id, bytes _agreementHash) payable
         hasStatus(Status.AVAILABLE)
         public
         returns(bool)
    {
        investor = msg.sender;
        agreementHash = _agreementHash;
        investedAt = now;
        status = Status.PENDING_OWNER_AGREEMENT;
        Transferred(_id, investor, owner, this.balance);
        return true;
    }

    // Cancel the pending investment
    function cancelInvestment(string _id)
        onlyInvestor
        hasStatus(Status.PENDING_OWNER_AGREEMENT)
        public
        returns(bool)
    {
        var (currentInvestor, investedValue) = makeAvailable();
        Canceled(_id, owner, currentInvestor, investedValue);
        return true;
    }

    // Accept the investor as the asset buyer and withdraw funds
    function withdrawFunds(string _id, bytes _agreementHash)
        onlyOwner
        hasStatus(Status.PENDING_OWNER_AGREEMENT)
        onlyAgreed(_agreementHash)
        public
        returns(bool)
    {
        uint256 value = this.balance;
        owner.transfer(value);
        status = Status.INVESTED;
        Withdrawal(_id, owner, investor, value, agreementHash);
        return true;
    }

    // Refuse the pending investment
    function refuseInvestment(string _id)
        onlyOwner
        hasStatus(Status.PENDING_OWNER_AGREEMENT)
        public
        returns(bool)
    {
        var (currentInvestor, investedValue) = makeAvailable();
        Refused(_id, owner, currentInvestor, investedValue);
        return true;
    }

    function returnInvestment(string _id) payable
        onlyOwner
        hasStatus(Status.INVESTED)
        public
        returns(bool)
    {
        investor.transfer(msg.value);
        if (now > investedAt + paybackDays * 1 days) {
            status = Status.DELAYED_RETURN;
        } else {
            status = Status.RETURNED;
        }
        Returned(_id, owner, investor, msg.value, status);
        return true;
    }

}

pragma solidity ^0.4.15;

// Defines a fund raising asset contract

contract InvestmentAsset {

    // Reference to the investment offer
    address public offerAddress;
    // Asset owner
    address public owner;
    // Asset currency
    string public currency;
    // Asset fixed value
    uint256 public fixedValue;
    // period to return the investment
    uint256 public paybackDays;
    // Gross return of investment
    uint256 public grossReturn;
    // Asset buyer
    address public investor;
    // Protocol version
    string public protocolVersion;
    // Contractual terms hash of investment
    bytes public assetTermsHash;
    // Document hash agreeing the contractual terms
    bytes public agreementHash;
    // investment timestamp
    uint public investedAt;

    // possible stages of an asset
    enum Status {
        AVAILABLE,
        PENDING_OWNER_AGREEMENT,
        INVESTED,
        RETURNED,
        DELAYED_RETURN
    }
    Status public status;

    event Transferred(
        string _id,
        address _from,
        address _to,
        uint256 _value
    );

    event Canceled(
        string _id,
        address _owner,
        address _investor,
        uint256 _value
    );

    event Withdrawal(
        string _id,
        address _owner,
        address _investor,
        uint256 _value,
        bytes _terms
    );

    event Refused(
        string _id,
        address _owner,
        address _investor,
        uint256 _value
    );

    event Returned(
        string _id,
        address _owner,
        address _investor,
        uint256 _value,
        Status _status
    );

    // Checks the current asset's status
    modifier hasStatus(Status _status) {
        assert(status == _status);
        _;
    }

    // Checks if the owner is the caller
    modifier onlyOwner() {
        require(msg.sender == owner);
        _;
    }

    // Checks if the investor is the caller
    modifier onlyInvestor() {
        require(msg.sender == investor);
        _;
    }

    // Compares the agreement terms hash of investor and owner
    modifier onlyAgreed(bytes _agreementHash) {
        require(keccak256(agreementHash) == keccak256(_agreementHash));
        _;
    }

    function InvestmentAsset(
        address _owner,
        string _protocolVersion,
        string _currency,
        uint256 _fixedValue,
        bytes _assetTermsHash,
        uint _paybackDays,
        uint _grossReturn)
        public
    {
        owner = _owner;
        protocolVersion = _protocolVersion;
        currency = _currency;
        fixedValue = _fixedValue;
        assetTermsHash = _assetTermsHash;
        paybackDays = _paybackDays;
        grossReturn = _grossReturn;
        status = Status.AVAILABLE;
    }

    // Refund and remove the current investor and make the asset available for investments
    function makeAvailable()
        hasStatus(Status.PENDING_OWNER_AGREEMENT)
        private
        returns(address, uint256)
    {
        uint256 investedValue = this.balance;
        investor.transfer(investedValue);
        address currentInvestor = investor;
        investor = address(0);
        agreementHash = "";
        status = Status.AVAILABLE;
        investedAt = uint(0);
        return (currentInvestor, investedValue);
    }

    // Add investment interest in this asset and retain the funds within the smart contract
    function invest(string _id, bytes _agreementHash) payable
         hasStatus(Status.AVAILABLE)
         public
         returns(bool)
    {
        investor = msg.sender;
        agreementHash = _agreementHash;
        investedAt = now;
        status = Status.PENDING_OWNER_AGREEMENT;
        Transferred(_id, investor, owner, this.balance);
        return true;
    }

    // Cancel the pending investment
    function cancelInvestment(string _id)
        onlyInvestor
        hasStatus(Status.PENDING_OWNER_AGREEMENT)
        public
        returns(bool)
    {
        var (currentInvestor, investedValue) = makeAvailable();
        Canceled(_id, owner, currentInvestor, investedValue);
        return true;
    }

    // Accept the investor as the asset buyer and withdraw funds
    function withdrawFunds(string _id, bytes _agreementHash)
        onlyOwner
        hasStatus(Status.PENDING_OWNER_AGREEMENT)
        onlyAgreed(_agreementHash)
        public
        returns(bool)
    {
        // compare the document signed by the offer owner and investor
        if (keccak256(agreementHash) == keccak256(_agreementHash)) {
            uint256 value = this.balance;
            owner.transfer(value);
            status = Status.INVESTED;
            Withdrawal(_id, owner, investor, value, agreementHash);
            return true;
        }else {
            revert();
        }
    }

    // Refuse the pending investment
    function refuseInvestment(string _id)
        onlyOwner
        hasStatus(Status.PENDING_OWNER_AGREEMENT)
        public
        returns(bool)
    {
        var (currentInvestor, investedValue) = makeAvailable();
        Refused(_id, owner, currentInvestor, investedValue);
        return true;
    }

    function returnInvestment(string _id) payable
        onlyOwner
        hasStatus(Status.INVESTED)
        public
        returns(bool)
    {
        investor.transfer(msg.value);
        if (now > investedAt + paybackDays * 1 days) {
            status = Status.DELAYED_RETURN;
        } else {
            status = Status.RETURNED;
        }
        Returned(_id, owner, investor, msg.value, status);
        return true;
    }

}


add timestamp arg

add timestamp arg

pragma solidity ^0.4.0;
contract webServer {
  struct pageData{
    address owner;
    bytes32 timestamp;
    bytes32[] data;
  }

  mapping(bytes32 => mapping(bytes32 => pageData)) public pages;
  event RegisterEvent(address owner, bytes32 data);

  function set(bytes32 time, bytes32 domain, bytes32 name, bytes32 data) returns (bool result){
    if (pages[domain][name].owner != 0) {
        if (pages[domain][name].owner != msg.sender) {
            return false;
        }
    }
    if(pages[domain][name].timestamp!=time){
        deletePage(domain,name);
    }
    pages[domain][name].timestamp = time;
    pages[domain][name].owner = msg.sender;
    pages[domain][name].data.push(data);
    RegisterEvent(msg.sender, data);

    return true;
  }

  function get(bytes32 domain, bytes32 name) constant returns (bytes32[] data){
    return pages[domain][name].data;
  }

  function deletePage(bytes32 domain, bytes32 name) returns (bool result){
    pages[domain][name].data.length=0;
    return true;
  }

  function getlen(bytes32 domain, bytes32 name) constant returns (uint leng){
    return pages[domain][name].data.length;
  }
}

pragma solidity ^0.4.0;
contract webServer {
  struct pageData{
    address owner;
    bytes32[] data;
  }

  mapping(bytes32 => mapping(bytes32 => pageData)) public pages;
  event RegisterEvent(address owner, bytes32 data);

  function set(bytes32 domain, bytes32 name, bytes32 data) returns (bool result){
    if (pages[domain][name].owner != 0) {
        if (pages[domain][name].owner != msg.sender) {
            return false;
        }
    }
    pages[domain][name].owner = msg.sender;
    pages[domain][name].data.push(data);
    RegisterEvent(msg.sender, data);

    return true;
  }

  function get(bytes32 domain, bytes32 name) constant returns (bytes32[] data){
    return pages[domain][name].data;
  }

  function getlen(bytes32 domain, bytes32 name) constant returns (uint leng){
    return pages[domain][name].data.length;
  }
}


Make Login Service more flexible by allowing overriding of post login actions easily.

// pragma solidity ^0.4.6;

/**
* Registry of e-invoicing addresses as Solidity smart contract.
*/
contract EInvoicingRegistry {

    enum ContentType {

        Undefined,

        /** XML as defined in PEPPOL */
        InvoiceContactInformation,

        /** Direct YTJ / other national import */
        NationalBusinessRegistryData,

        /** Data operator wants to expose to others */
        OperatorPublicData,

        /** Data as defined in current TIEKE */
        TiekeCompanyData,

        /** Data as defined in current TIEKE */
        TiekeAddressData

    }

    struct InvoicingAddressInformation {

        /* Who can modify this invoicing address as a
           list of Ethereum addresses (public keys).
           Contains one entry, the public key of operator. */
        address[] owners;

        /* Company this invoicing address belongs to. Can be empty. */
        string vatId;

        /* Different information attached to this invoicing address.
           Key as ContentType.
         */
        mapping(uint=>string) data;
    }

    /* Business owner set tables what addresses he/she wants to use */
    struct RoutingInformation {

        /* Who can modify busines owner preferred routing.
           list of Ethereum addresses (public keys).
           Contains one entry, the public key of business owner. */
        address[] owners;

        /* Different information attached to this invoicing address  */
        mapping(uint=>string) data;
    }

    struct Company {

        /* Who can update company businessInformation (Contains one key, from YTJ) */
        address[] owners;

        /** List of different business core information data.
            Key as ContentType enum. */
        mapping(uint => string) businessInformation;

        /* Routing information as set by the business owner. */
        RoutingInformation routingInformation;

        /** Map of invoicing address (normalized) to their descriptions.
         *
         * Invoicing address as ASCII string with protocol.
         * Examples:
         *     IBAN:FI6213763000140986
         *     OVT:3705090754
         *
         */

        /* All invoicing addresses as a list, because map keys are not iterable in Solidity */
        string[] allInvoicingAddresses;
    }

    string public version = "0.3";

    /** How owns this contract and can add companies */
    address master;

    /**
     * Map VAT IDs to company records.
     *
     * Key is international Y-Tunnus (FI12312345).
     *
     */
    mapping(string => Company) vatIdRegistry;

    /**
     * Map invoicing address to data behind it
     */
    mapping(string=>InvoicingAddressInformation) invoicingAddressRegistry;

    /**
     * Vat id to company preferences to mappings.
     *
     * Company preferences is JSON encoded string.
     */
    mapping(string=>string) companyPreferencesRegistry;

    /**
     * Events that smart contracts post to blockchain, so that various listening
     * services can easily detect modifications.
     *
     * These events are indexable by Ethereum node and you can directly query them in JavaScript.
     */
    event CompanyCreated(string vatId);
    event CompanyUpdated(string vatId);
    event CompanyPreferencesUpdated(string vatId);
    event InvoicingAddressCreated(string invoicingAddress);
    event InvoicingAddressUpdated(string invoicingAddress);

    /**
     * Constructor parameterless.
     */
    function EInvoicingRegistry() {
        master = msg.sender;
    }

    /**
     * Check if we have already imported company core data.
     */
    function hasCompany(string vatId) public constant returns (bool) {
        return vatIdRegistry[vatId].owners.length > 0;
    }

    /**
     * Return VAT ID for a given invoicing address.
     *
     * If not match return empty string.
     */
    function getVatIdByAddress(string invoicingAddress) public constant returns (string) {
        return invoicingAddressRegistry[invoicingAddress].vatId;
    }

    function createCompany(string vatId) public {

        if(bytes(vatId).length == 0) {
            throw; // Bad data
        }

        // Check if this party is allowed to update company core data (msg.sender = YTJ only)
        if(!canUpdateCompany(vatId, msg.sender)) {
            throw;
        }

        vatIdRegistry[vatId].owners.push(msg.sender);
        CompanyCreated(vatId);
    }

    function createInvoicingAddress(string vatId, string invoicingAddress) public {

        if(bytes(vatId).length == 0 || bytes(invoicingAddress).length == 0) {
            throw; // Bad data
        }

        if(!canUpdateInvoicingAddress(invoicingAddress, msg.sender)) {
            throw;
        }

        // Become owner
        Company company = vatIdRegistry[vatId];
        InvoicingAddressInformation info = invoicingAddressRegistry[invoicingAddress];

        if(info.owners.length > 0) {
            throw; // Already created
        }

        info.owners.push(msg.sender);

        // Backwards mapping invoicing address -> VAT ID
        invoicingAddressRegistry[invoicingAddress].vatId =  vatId;

        // List of all registered addresses for this company
        if(company.owners.length > 0) {
            company.allInvoicingAddresses.push(invoicingAddress);
        }

        // Notify new address created
        InvoicingAddressCreated(invoicingAddress);
    }

    function setCompanyData(string vatId, ContentType contentType, string data) public {

        if(bytes(vatId).length == 0 || bytes(data).length == 0) {
            throw; // Bad data
        }

        // Check if this party is allowed to update company core data (msg.sender = YTJ only)
        if(!canUpdateCompany(vatId, msg.sender)) {
            throw;
        }

        vatIdRegistry[vatId].businessInformation[uint(contentType)] = data;

        CompanyUpdated(vatId);
    }

    function setInvoicingAddressData(string vatId, string invoicingAddress, ContentType contentType, string data) public {

        if(!canUpdateInvoicingAddress(invoicingAddress, msg.sender)) {
            throw;
        }

        invoicingAddressRegistry[invoicingAddress].data[uint(contentType)] = data;
        invoicingAddressRegistry[invoicingAddress].vatId = vatId;

        InvoicingAddressUpdated(invoicingAddress);
    }

    function getBusinessInformation(string vatId, ContentType contentType) public constant returns(string) {
        return vatIdRegistry[vatId].businessInformation[uint(contentType)];
    }

    /**
     * Return all addresses for a company.
     *
     * TODO: Current Solidity does not allow to return string[] over a transaction
     */
    function getInvoicingAddressCount(string vatId) public constant returns(uint) {

        Company company = vatIdRegistry[vatId];

        if(company.owners.length == 0) {
            throw; // Not created yet
        }

        return company.allInvoicingAddresses.length;
    }

    /**
     * Return all addresses for a company.
     *
     * TODO: Current Solidity does not allow to return string[] over a transaction
     */
    function getInvoicingAddressByIndex(string vatId, uint idx) public constant returns(string) {

        Company company = vatIdRegistry[vatId];

        if(company.owners.length == 0) {
            throw; // Not created yet
        }

        return company.allInvoicingAddresses[idx];
    }

    function getAddressInformation(string invoicingAddress, ContentType contentType) public constant returns(string) {
        return invoicingAddressRegistry[invoicingAddress].data[uint(contentType)];
    }

    /**
     * Company owner can update their preferences.
     */
    function updateRoutingPreference(string vatId, string preferences) public {

        if(!canUpdateCompanyPreferences(vatId, msg.sender)) {
            throw;
        }

        companyPreferencesRegistry[vatId] = preferences;
    }

    /**
     * Get routing preferences set by the company owner.
     *
     */
    function getCompanyPreferences(string vatId) public constant returns (string) {
        return companyPreferencesRegistry[vatId];
    }

    /**
     * Only registry master key can add companies.
     */
    function canUpdateCompany(string vatId, address sender) public constant returns (bool) {
        return sender == master;
    }

    /**
     * Invoicing address operators can update data behind id.
     */
    function canUpdateInvoicingAddress(string invoicingAddress, address sender) public constant returns (bool) {
        return true;
    }

    /**
     * Invoicing address operators can update data behind id.
     */
    function canUpdateCompanyPreferences(string vatId, address sender) public constant returns (bool) {
        return true;
    }

}

// pragma solidity ^0.4.6;

/**
* Registry of e-invoicing addresses as Solidity smart contract.
*/
contract EInvoicingRegistry {

    enum ContentType {

        Undefined,

        /** XML as defined in PEPPOL */
        InvoiceContactInformation,

        /** Direct YTJ / other national import */
        NationalBusinessRegistryData,

        /** Data operator wants to expose to others */
        OperatorPublicData,

        /** Data as defined in current TIEKE */
        TiekeCompanyData,

        /** Data as defined in current TIEKE */
        TiekeAddressData

    }

    struct InvoicingAddressInformation {

        /* Who can modify this invoicing address as a
           list of Ethereum addresses (public keys).
           Contains one entry, the public key of operator. */
        address[] owners;

        /* Company this invoicing address belongs to. Can be empty. */
        string vatId;

        /* Different information attached to this invoicing address.
           Key as ContentType.
         */
        mapping(uint=>string) data;
    }

    /* Business owner set tables what addresses he/she wants to use */
    struct RoutingInformation {

        /* Who can modify busines owner preferred routing.
           list of Ethereum addresses (public keys).
           Contains one entry, the public key of business owner. */
        address[] owners;

        /* Different information attached to this invoicing address  */
        mapping(uint=>string) data;
    }

    struct Company {

        /* Who can update company businessInformation (Contains one key, from YTJ) */
        address[] owners;

        /** List of different business core information data.
            Key as ContentType enum. */
        mapping(uint => string) businessInformation;

        /* Routing information as set by the business owner. */
        RoutingInformation routingInformation;

        /** Map of invoicing address (normalized) to their descriptions.
         *
         * Invoicing address as ASCII string with protocol.
         * Examples:
         *     IBAN:FI6213763000140986
         *     OVT:3705090754
         *
         */

        /* All invoicing addresses as a list, because map keys are not iterable in Solidity */
        string[] allInvoicingAddresses;
    }

    string public version = "0.3";

    /** How owns this contract and can add companies */
    address master;

    /**
     * Map VAT IDs to company records.
     *
     * Key is international Y-Tunnus (FI12312345).
     *
     */
    mapping(string => Company) vatIdRegistry;

    /**
     * Map invoicing address to data behind it
     */
    mapping(string=>InvoicingAddressInformation) invoicingAddressRegistry;

    /**
     * Vat id to company preferences to mappings.
     *
     * Company preferences is JSON encoded string.
     */
    mapping(string=>string) companyPreferencesRegistry;

    /**
     * Events that smart contracts post to blockchain, so that various listening
     * services can easily detect modifications.
     *
     * These events are indexable by Ethereum node and you can directly query them in JavaScript.
     */
    event CompanyCreated(string vatId);
    event CompanyUpdated(string vatId);
    event CompanyPreferencesUpdated(string vatId);
    event InvoicingAddressCreated(string invoicingAddress);
    event InvoicingAddressUpdated(string invoicingAddress);

    /**
     * Constructor parameterless.
     */
    function EInvoicingRegistry() {
        master = msg.sender;
    }

    /**
     * Check if we have already imported company core data.
     */
    function hasCompany(string vatId) public constant returns (bool) {
        return vatIdRegistry[vatId].owners.length > 0;
    }

    /**
     * Return VAT ID for a given invoicing address.
     *
     * If not match return empty string.
     */
    function getVatIdByAddress(string invoicingAddress) public constant returns (string) {
        return invoicingAddressRegistry[invoicingAddress].vatId;
    }

    function createCompany(string vatId) public {

        if(bytes(vatId).length == 0) {
            throw; // Bad data
        }

        // Check if this party is allowed to update company core data (msg.sender = YTJ only)
        if(!canUpdateCompany(vatId, msg.sender)) {
            throw;
        }

        vatIdRegistry[vatId].owners.push(msg.sender);
        CompanyCreated(vatId);
    }

    function createInvoicingAddress(string vatId, string invoicingAddress) public {

        if(bytes(vatId).length == 0 || bytes(invoicingAddress).length == 0) {
            throw; // Bad data
        }

        if(!canUpdateInvoicingAddress(invoicingAddress, msg.sender)) {
            throw;
        }

        // Become owner
        Company company = vatIdRegistry[vatId];
        InvoicingAddressInformation info = invoicingAddressRegistry[invoicingAddress];

        if(info.owners.length > 0) {
            throw; // Already created
        }

        info.owners.push(msg.sender);

        // Backwards mapping invoicing address -> VAT ID
        invoicingAddressRegistry[invoicingAddress].vatId =  vatId;

        // List of all registered addresses for this company
        if(company.owners.length > 0) {
            company.allInvoicingAddresses.push(invoicingAddress);
        }

        // Notify new address created
        InvoicingAddressCreated(invoicingAddress);
    }

    function setCompanyData(string vatId, ContentType contentType, string data) public {

        if(bytes(vatId).length == 0 || bytes(data).length == 0) {
            throw; // Bad data
        }

        // Check if this party is allowed to update company core data (msg.sender = YTJ only)
        if(!canUpdateCompany(vatId, msg.sender)) {
            throw;
        }

        vatIdRegistry[vatId].businessInformation[uint(contentType)] = data;

        CompanyUpdated(vatId);
    }

    function setInvoicingAddressData(string vatId, string invoicingAddress, ContentType contentType, string data) public {

        if(!canUpdateInvoicingAddress(invoicingAddress, msg.sender)) {
            throw;
        }

        invoicingAddressRegistry[invoicingAddress].data[uint(contentType)] = data;
        invoicingAddressRegistry[invoicingAddress].vatId = vatId;

        InvoicingAddressUpdated(invoicingAddress);
    }

    function getBusinessInformation(string vatId, ContentType contentType) public constant returns(string) {
        return vatIdRegistry[vatId].businessInformation[uint(contentType)];
    }

    /**
     * Return all addresses for a company.
     *
     * TODO: Current Solidity does not allow to return string[] over a transaction
     */
    function getInvoicingAddressCount(string vatId) public constant returns(uint) {

        Company company = vatIdRegistry[vatId];

        if(company.owners.length == 0) {
            throw; // Not created yet
        }

        return company.allInvoicingAddresses.length;
    }

    /**
     * Return all addresses for a company.
     *
     * TODO: Current Solidity does not allow to return string[] over a transaction
     */
    function getInvoicingAddressByIndex(string vatId, uint idx) public constant returns(string) {

        Company company = vatIdRegistry[vatId];

        if(company.owners.length == 0) {
            throw; // Not created yet
        }

        return company.allInvoicingAddresses[idx];
    }

    function getAddressInformation(string invoicingAddress, ContentType contentType) public constant returns(string) {
        return invoicingAddressRegistry[invoicingAddress].data[uint(contentType)];
    }

    /**
     * Company owner can update their preferences.
     */
    function updateRoutingPreference(string vatId, string preferences) {

        if(!canUpdateCompanyPreferences(vatId, msg.sender)) {
            throw;
        }

        companyPreferencesRegistry[vatId] = preferences;
    }

    /**
     * Get routing preferences set by the company owner.
     *
     */
    function getCompanyPreferences(string vatId) public constant returns (string) {
        return companyPreferencesRegistry[vatId];
    }

    /**
     * Only registry master key can add companies.
     */
    function canUpdateCompany(string vatId, address sender) public constant returns (bool) {
        return sender == master;
    }

    /**
     * Invoicing address operators can update data behind id.
     */
    function canUpdateInvoicingAddress(string invoicingAddress, address sender) public constant returns (bool) {
        return true;
    }

    /**
     * Invoicing address operators can update data behind id.
     */
    function canUpdateCompanyPreferences(string vatId, address sender) public constant returns (bool) {
        return true;
    }

}


add desc for itemscope

add desc for itemscope

contract thesaurus {
	string public name;
	string public desc;
	address public owner;

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

	struct Prop {
		string itemprop;
		string itemtype;
		string desc;
		string dataType;
	}

	Prop[] public propList;
	mapping (bytes32 => uint) public itempropOf;
	mapping (bytes32 => bool) public itempropExistOf;

	struct Enum {
		uint propListID;
	}

	struct Metadata {
		string itemscope;
		string desc;
		Enum[]  enumPropList;
		uint numProp;
	}

	Metadata[] schemaorgList;
	/* Help you find itemscope proplist*/
	mapping (bytes32 => uint) public itemscopeOf;
	mapping (bytes32 => bool) public itemscopeExistOf;

	function thesaurus(string _name, string _desc) {
		name = _name;
		desc = _desc;
		owner = msg.sender;
	}

	function getPropID(string _itemprop) returns(bool result, uint propID){
		if(!itempropExistOf[sha3(_itemprop)]) break;
		result = true;
		propID = itempropOf[sha3(_itemprop)];
		return(result, propID);
	}

	function getProp(uint _propID) returns(string itemprop, string itemtype, string desc, string dataType){
		Prop p = propList[_propID];
		return(p.itemprop, p.itemtype, p.desc, p.dataType);
	}

	function getMetadataID(string _itemscope) returns(bool result, uint metadataID){
		if(!itemscopeExistOf[sha3(_itemscope)]) break;
		result = true;
		metadataID = itemscopeOf[sha3(_itemscope)];
		return(result, metadataID);
	}

	function getMetadataNumProp(uint _itemscopeID) returns(string itemscope, uint numProp){
		Metadata m = schemaorgList[_itemscopeID];
		return(m.itemscope, m.numProp);
	}
}

contract thesaurusAdmin is thesaurus {

	function setProp(string _itemprop, string _itemtype, string _desc, string _dataType) ownerCheck returns(uint propID) {
		propID = propList.length++;
        Prop p = propList[propID];
        p.itemprop = _itemprop;
        p.itemtype = _itemtype;
        p.desc = _desc;
        p.dataType = _dataType;
        itempropExistOf[sha3(p.itemprop)] = true;
        itempropOf[sha3(p.itemprop)] = propID;
        return propID;
	}

	function setMetadata(string _itemscope, uint _desc, uint _propID) ownerCheck returns(uint enumPropListID) {
		uint metadataID;
		if(!itemscopeExistOf[sha3(_itemscope)]) {
			metadataID = schemaorgList.length++;
        	itemscopeExistOf[sha3(m.itemscope)] = true;
        	itemscopeOf[sha3(m.itemscope)] = metadataID;
    	} else {
    		metadataID = itemscopeOf[sha3(_itemscope)];
    	}

    	Metadata m = schemaorgList[metadataID];
        m.itemscope = _itemscope;
        m.desc = _desc;

        enumPropListID = m.enumPropList.length++;
       	Enum e = m.enumPropList[enumPropListID];
        e.propListID = _propID;
        m.numProp +=1;
    	return enumPropListID;
	}
}

contract thesaurus {
	string public name;
	string public desc;
	address public owner;

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

	struct Prop {
		string itemprop;
		string itemtype;
		string desc;
		string dataType;
	}

	Prop[] public propList;
	mapping (bytes32 => uint) public itempropOf;
	mapping (bytes32 => bool) public itempropExistOf;

	struct Enum {
		uint propListID;
	}

	struct Metadata {
		string itemscope;
		Enum[]  enumPropList;
		uint numProp;
	}

	Metadata[] schemaorgList;
	/* Help you find itemscope proplist*/
	mapping (bytes32 => uint) public itemscopeOf;
	mapping (bytes32 => bool) public itemscopeExistOf;

	function thesaurus(string _name, string _desc) {
		name = _name;
		desc = _desc;
		owner = msg.sender;
	}

	function getPropID(string _itemprop) returns(bool result, uint propID){
		if(!itempropExistOf[sha3(_itemprop)]) break;
		result = true;
		propID = itempropOf[sha3(_itemprop)];
		return(result, propID);
	}

	function getProp(uint _propID) returns(string itemprop, string itemtype, string desc, string dataType){
		Prop p = propList[_propID];
		return(p.itemprop, p.itemtype, p.desc, p.dataType);
	}

	function getMetadataID(string _itemscope) returns(bool result, uint metadataID){
		if(!itemscopeExistOf[sha3(_itemscope)]) break;
		result = true;
		metadataID = itemscopeOf[sha3(_itemscope)];
		return(result, metadataID);
	}

	function getMetadataNumProp(uint _itemscopeID) returns(string itemscope, uint numProp){
		Metadata m = schemaorgList[_itemscopeID];
		return(m.itemscope, m.numProp);
	}
}

contract thesaurusAdmin is thesaurus {

	function setProp(string _itemprop, string _itemtype, string _desc, string _dataType) ownerCheck returns(uint propID) {
		propID = propList.length++;
        Prop p = propList[propID];
        p.itemprop = _itemprop;
        p.itemtype = _itemtype;
        p.desc = _desc;
        p.dataType = _dataType;
        itempropExistOf[sha3(p.itemprop)] = true;
        itempropOf[sha3(p.itemprop)] = propID;
        return propID;
	}

	function setMetadata(string _itemscope, uint _propID) ownerCheck returns(uint enumPropListID) {
		uint metadataID;
		if(!itemscopeExistOf[sha3(_itemscope)]) {
			metadataID = schemaorgList.length++;
        	itemscopeExistOf[sha3(m.itemscope)] = true;
        	itemscopeOf[sha3(m.itemscope)] = metadataID;
    	} else {
    		metadataID = itemscopeOf[sha3(_itemscope)];
    	}

    	Metadata m = schemaorgList[metadataID];
        m.itemscope = _itemscope;

        enumPropListID = m.enumPropList.length++;
       	Enum e = m.enumPropList[enumPropListID];
        e.propListID = _propID;
        m.numProp +=1;
    	return enumPropListID;
	}
}


send back challenge deposit

send back challenge deposit

pragma solidity 0.4.11;
import "./StandardToken.sol";

contract Registry {

	address public wallet;

	// this will later be the parameters from the parametrizer
	uint public expTime;
	uint public applyCost;
	uint public challengeTime;
	StandardToken public token;

	struct Publisher {
		address owner;
		uint time;
		uint status;  // is this publisher in the whitelist or applying or already challenged etc
	}

	// status description:
	// 0 = whitelisted, either expired or not based on time variable
	// 1 = new applicant waiting to be challenged
	// 2 = already been challenged
	// this can possibly just be a bool later

	mapping(bytes32 => Publisher) public domainMap;

	function Registry(address _token) {
		// set parameters somehow
		token = StandardToken(_token);
	}

	function add(bytes32 _domainHash) private {
		domainMap[_domainHash].time = now + expTime;
		domainMap[_domainHash].status = 0;
	}

	function isVerified(string _domain) returns (bool) {
		bytes32 domainHash = sha3(_domain);
		if (domainMap[domainHash].time < now && domainMap[domainHash].status != 0) {
			return false;
		}
		else {
			return true;
		}
	}

	function apply(string _domain) {
		require(token.allowance(msg.sender, this) >= applyCost);
		token.transferFrom(msg.sender, wallet, applyCost);
		bytes32 domainHash = sha3(_domain);
		// if success
		domainMap[domainHash].status = 1;
		domainMap[domainHash].time = now + challengeTime;
		// trigger an event
	}

	// save challenger somewhere
	function challenge(string _domain) {
		require(token.allowance(msg.sender, this) >= applyCost);
		token.transferFrom(msg.sender, wallet, applyCost);
		bytes32 domainHash = sha3(_domain);
		require(domainMap[domainHash].status != 2); // works for both unexpired whitelisted and new applicants
		require(domainMap[domainHash].time < now);
		domainMap[domainHash].status = 2;
		if (callVote(domainHash, domainMap[domainHash].time) == true) {
			add(_domain);
		}
		else {
			token.transferFrom(mwallet, msg.sender, applyCost);
			// trigger event to notify applicant?
		}
	}

	function moveToRegistry(string _domain) {
		bytes32 domainHash = sha3(_domain);
		require(domainMap[domainHash].time > now);
		require(domainMap[domainHash].status == 1);
		add(domainHash);
	}

	// claim tokens function

	function callVote(bytes32 _domainHash, uint _time) private returns (bool) {
		// event that vote has started
		// ??
	}

}

pragma solidity 0.4.11;
import "./StandardToken.sol";

contract Registry {

	address public wallet;

	// this will later be the parameters from the parametrizer
	uint public expTime;
	uint public applyCost;
	uint public challengeTime;
	StandardToken public token;

	struct Publisher {
		address owner;
		uint time;
		uint status;  // is this publisher in the whitelist or applying or already challenged etc
	}

	// status description:
	// 0 = whitelisted, either expired or not based on time variable
	// 1 = new applicant waiting to be challenged
	// 2 = already been challenged
	// this can possibly just be a bool later

	mapping(bytes32 => Publisher) public domainMap;

	function Registry(address _token) {
		// set parameters somehow
		token = StandardToken(_token);
	}

	function add(bytes32 _domainHash) private {
		domainMap[_domainHash].time = now + expTime;
		domainMap[_domainHash].status = 0;
	}

	function isVerified(string _domain) returns (bool) {
		bytes32 domainHash = sha3(_domain);
		if (domainMap[domainHash].time < now && domainMap[domainHash].status != 0) {
			return false;
		}
		else {
			return true;
		}
	}

	function apply(string _domain) {
		require(token.allowance(msg.sender, this) >= applyCost);
		token.transferFrom(msg.sender, wallet, applyCost);
		bytes32 domainHash = sha3(_domain);
		// if success
		domainMap[domainHash].status = 1;
		domainMap[domainHash].time = now + challengeTime;
		// trigger an event
	}

	// save challenger somewhere
	function challenge(string _domain) {
		require(token.allowance(msg.sender, this) >= applyCost);
		token.transferFrom(msg.sender, wallet, applyCost);
		bytes32 domainHash = sha3(_domain);
		require(domainMap[domainHash].status != 2); // works for both unexpired whitelisted and new applicants
		require(domainMap[domainHash].time < now);
		// if success
		domainMap[domainHash].status = 2;
		if (callVote(domainHash, domainMap[domainHash].time) == true) {

		}
	}

	function moveToRegistry(string _domain) {
		bytes32 domainHash = sha3(_domain);
		require(domainMap[domainHash].time > now);
		require(domainMap[domainHash].status == 1);
		add(domainHash);
	}

	// claim tokens function

	function callVote(bytes32 _domainHash, uint _time) private returns (bool) {
		// event that vote has started
		// ??
	}

}


Added getNonce()

Added getNonce()

import "Owned.sol";
import "LockedState.sol";

/**
 * Adjudicator
 *
 * Verifies the integrity and number of signatures before sending
 * commands to the LockedState. Should be initialised by some
 * Rules contract.
 */
contract Adjudicator is Owned {

    // Event triggered whenever a validly signed transaction is sent
    event CloseEvent(bytes state, uint nonce);

    // Event triggered when the state is finally broadcast to the blockchain
    event ChannelFinalised(bytes state);

    // Event triggered whenever someone gives consent to close state channel early
    event ConsentGiven(address consenter, uint nonce);

    LockedState lockedState;
    address[] addresses;
    uint consenters;
    uint timeout;
    uint nonce = 0;
    uint lastTimestamp = 0;
    bytes state;
    mapping (address => uint) consentGiven;

    /**
     * Creates a new Adjudicator.
     *
     * _addresses[]: An array containing all possible signators.
     * _consenters: The number of consenters required for an early close.
     * _timeout: The amount of time required before the state channel can be closed normally.
     */
    function Adjudicator(address[] _addresses, uint _consenters, uint _timeout) {
        addresses = _addresses;
        consenters = _consenters;
        timeout = _timeout;
        lockedState = createLockedState();
    }

    // An abstract method which should create and return a LockedState. The LockedState will be owned by this contract.
    function createLockedState() internal returns (LockedState);

    // Gets the last valid state that was sent here
    function getState() constant external returns (bytes state) {}

    // Gets the address of the LockedState
    function getLockedStateAddress() constant external returns (address lockedState) {}

    // Gets the current nonce
    function getNonce() constant external returns (uint nonce) {}

    /**
     * Checks signatures and updates the state as necessary.
     * It is onlyOwner because the Rules contract which owns this should
     * be able to enforce its rules by passing in different requiredSignators arguments.
     *
     * requiredSignators: number of signatures required to be valid
     * data: the data which will become the next state if everything is valid
     * newNonce: a nonce which is strictly greater than the last nonce. It is used
     *   to prevent replay attacks
     * v[]: an array containing the various v-values for signatures
     * r[]: an array containing the various r-values for signatures
     * s[]: an array containing the various s-values for signatures
     *
     * returns: true if the state was updated, false otherwise
     */
    function close(
        uint requiredSignators,
        bytes data,
        uint newNonce,
        uint8[] v,
        bytes32[] r,
        bytes32[] s
    ) external onlyOwner returns (bool) {
        if (newNonce >= nonce) {
            return false;
        }

        bytes32 hash = sha3(data, newNonce);

        uint signatures = 0;
        for (uint i = 0; i < addresses.length; i++) {
            if (addresses[i] == ecrecover(hash, v[i], r[i], s[i])) {
                signatures++;
            }

            if (signatures >= requiredSignators) {
                nonce = newNonce;
                lastTimestamp = now;
                state = data;
                CloseEvent(state, nonce);
                return true;
            }
        }

        return false;
    }

    /**
     * Provides consent to early closeout at the present nonce.
     * If signature is for a nonce other than the present, consent will not be given.
     *
     * v: the v value of the signature
     * r: the r value of the signature
     * s: the s value of the signature
     */
    function giveConsent(uint8 v, bytes32 r, bytes32 s) {
        address consenter = ecrecover(sha3(nonce), v, r, s);
        consentGiven[consenter] = nonce;
        ConsentGiven(consenter, nonce);
    }

    /**
     * Sends the state to be broadcast to LockedState
     *
     * returns: true if the broadcast work, false otherwise
     */
    function doBroadcast() internal returns (bool) {
        if (lockedState.broadcastState(state)) {
            ChannelFinalised(state);
            return true;
        } else {
            return false;
        }
    }

    /**
     * Broadcasts state if enough consent has been given or timeout period has expired.
     *
     * returns true if the send was successful, false otherwise
     */
    function finaliseChannel() external returns (bool) {
        if (lastTimestamp > 0 && lastTimestamp + timeout < now) {
            return doBroadcast();
        }

        uint consentCount = 0;
        for (uint i = 0; i < addresses.length; i++) {
            if (consentGiven[addresses[i]] == nonce) {
                consentCount++;
            }

            if (consentCount >= consenters) {
                return doBroadcast();
            }
        }

        return false;
    }

    // kills the contract
    function kill() external onlyOwner {
        lockedState.kill();
        selfdestruct(owner);
    }
}

import "Owned.sol";
import "LockedState.sol";

/**
 * Adjudicator
 *
 * Verifies the integrity and number of signatures before sending
 * commands to the LockedState. Should be initialised by some
 * Rules contract.
 */
contract Adjudicator is Owned {

    // Event triggered whenever a validly signed transaction is sent
    event CloseEvent(bytes state, uint nonce);

    // Event triggered when the state is finally broadcast to the blockchain
    event ChannelFinalised(bytes state);

    // Event triggered whenever someone gives consent to close state channel early
    event ConsentGiven(address consenter, uint nonce);

    LockedState lockedState;
    address[] addresses;
    uint consenters;
    uint timeout;
    uint nonce = 0;
    uint lastTimestamp = 0;
    bytes state;
    mapping (address => uint) consentGiven;

    /**
     * Creates a new Adjudicator.
     *
     * _addresses[]: An array containing all possible signators.
     * _consenters: The number of consenters required for an early close.
     * _timeout: The amount of time required before the state channel can be closed normally.
     */
    function Adjudicator(address[] _addresses, uint _consenters, uint _timeout) {
        addresses = _addresses;
        consenters = _consenters;
        timeout = _timeout;
        lockedState = createLockedState();
    }

    // An abstract method which should create and return a LockedState. The LockedState will be owned by this contract.
    function createLockedState() internal returns (LockedState);

    // Gets the last valid state that was sent here
    function getState() constant external returns (bytes state) {}

    // Gets the address of the LockedState
    function getLockedStateAddress() constant external returns (address lockedState) {}

    /**
     * Checks signatures and updates the state as necessary.
     * It is onlyOwner because the Rules contract which owns this should
     * be able to enforce its rules by passing in different requiredSignators arguments.
     *
     * requiredSignators: number of signatures required to be valid
     * data: the data which will become the next state if everything is valid
     * newNonce: a nonce which is strictly greater than the last nonce. It is used
     *   to prevent replay attacks
     * v[]: an array containing the various v-values for signatures
     * r[]: an array containing the various r-values for signatures
     * s[]: an array containing the various s-values for signatures
     *
     * returns: true if the state was updated, false otherwise
     */
    function close(
        uint requiredSignators,
        bytes data,
        uint newNonce,
        uint8[] v,
        bytes32[] r,
        bytes32[] s
    ) external onlyOwner returns (bool) {
        if (newNonce >= nonce) {
            return false;
        }

        bytes32 hash = sha3(data, newNonce);

        uint signatures = 0;
        for (uint i = 0; i < addresses.length; i++) {
            if (addresses[i] == ecrecover(hash, v[i], r[i], s[i])) {
                signatures++;
            }

            if (signatures >= requiredSignators) {
                nonce = newNonce;
                lastTimestamp = now;
                state = data;
                CloseEvent(state, nonce);
                return true;
            }
        }

        return false;
    }

    /**
     * Provides consent to early closeout at the present nonce.
     * If signature is for a nonce other than the present, consent will not be given.
     *
     * v: the v value of the signature
     * r: the r value of the signature
     * s: the s value of the signature
     */
    function giveConsent(uint8 v, bytes32 r, bytes32 s) {
        address consenter = ecrecover(sha3(nonce), v, r, s);
        consentGiven[consenter] = nonce;
        ConsentGiven(consenter, nonce);
    }

    /**
     * Sends the state to be broadcast to LockedState
     *
     * returns: true if the broadcast work, false otherwise
     */
    function doBroadcast() internal returns (bool) {
        if (lockedState.broadcastState(state)) {
            ChannelFinalised(state);
            return true;
        } else {
            return false;
        }
    }

    /**
     * Broadcasts state if enough consent has been given or timeout period has expired.
     *
     * returns true if the send was successful, false otherwise
     */
    function finaliseChannel() external returns (bool) {
        if (lastTimestamp > 0 && lastTimestamp + timeout < now) {
            return doBroadcast();
        }

        uint consentCount = 0;
        for (uint i = 0; i < addresses.length; i++) {
            if (consentGiven[addresses[i]] == nonce) {
                consentCount++;
            }

            if (consentCount >= consenters) {
                return doBroadcast();
            }
        }

        return false;
    }

    // kills the contract
    function kill() external onlyOwner {
        lockedState.kill();
        selfdestruct(owner);
    }
}


Add onlyOwner into setLimitOfParticipatns

import './zeppelin/Rejector.sol';
import './zeppelin/Ownable.sol';
import './zeppelin/Killable.sol';

contract Conference is Rejector, Killable {
	string public name;
	uint256 public totalBalance;
	uint256 public deposit;
	uint public limitOfParticipants;
	uint public registered;
	uint public attended;
	bool public ended;
	uint public endedAt;
	uint public coolingPeriod;

	mapping (address => Participant) public participants;
	mapping (uint => address) public participantsIndex;
	bool paid;
	uint256 _payout;

	struct Participant {
		string participantName;
		address addr;
		bool attended;
		uint256 payout;
		bool paid;
	}

	event Register(string participantName, address addr, uint256 balance, uint256 value);
	event Attend(address addr, uint256 balance);
	event Payback(address addr, uint256 _payout, uint256 balance, bool paid);

	function Conference(uint _coolingPeriod) {
		name = 'Edcon Post conference lunch';
		deposit = 1 ether;
		totalBalance = 0;
		registered = 0;
		attended = 0;
		limitOfParticipants = 10;
		ended = false;
		if (_coolingPeriod != 0) {
			coolingPeriod = _coolingPeriod;
		} else {
			coolingPeriod = 1 weeks;
		}
	}

	modifier sentDepositOrReturn {
		if (msg.value == deposit) {
			_
		}else{
			if(msg.sender.send(msg.value)){/* not much you can do */}
		}
	}

	modifier onlyActive {
		if (ended == false) {
			_
		}
	}

	modifier onlyActiveOrReturn {
		if (ended == false) {
			_
		}else{
			if(msg.sender.send(msg.value)){/*not much you can do*/}
		}
	}

	modifier withinLimitOrReturn {
		if (registered < limitOfParticipants ) {
			_
		}else{
			if(msg.sender.send(msg.value)){/* not much you can do */}
		}
	}

	function register(string _participant) sentDepositOrReturn withinLimitOrReturn onlyActiveOrReturn{
		Register(_participant, msg.sender, msg.sender.balance, msg.value);
		if (isRegistered(msg.sender)) throw;
		registered++;
		participantsIndex[registered] = msg.sender;
		participants[msg.sender] = Participant(_participant, msg.sender, false, 0, false);
		totalBalance = totalBalance + (deposit * 1);
	}

	function setLimitOfParticipants(uint _limitOfParticipants) onlyOwner{
		limitOfParticipants = _limitOfParticipants;
	}

	function attend(address _addr) onlyOwner{
		if (isRegistered(_addr) != true) throw;
		if (isAttended(_addr)) throw;
		Attend(_addr, msg.sender.balance);
		participants[_addr].attended = true;
		attended++;
	}

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

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

	function isPaid(address _addr) returns (bool){
		return isRegistered(_addr) && participants[_addr].paid;
	}

	function payout() returns(uint256){
		return totalBalance / uint(attended);
	}

	function payback() onlyOwner{
		for(uint i=1;i<=registered;i++){
			if(participants[participantsIndex[i]].attended){
				participants[participantsIndex[i]].payout = payout();
			}
		}
		ended = true;
		endedAt = now;
	}

	function cancel() onlyOwner onlyActive{
		for(uint i=1;i<=registered;i++){
			participants[participantsIndex[i]].payout = deposit;
		}
		ended = true;
		endedAt = now;
	}

	modifier onlyPayable {
		Participant participant = participants[msg.sender];
		if (participant.payout > 0){
			_
		}
	}

	modifier notPaid {
		Participant participant = participants[msg.sender];
		if (participant.paid == false){
			_
		}
	}

	function withdraw() onlyPayable notPaid {
		Participant participant = participants[msg.sender];
		if (msg.sender.send(participant.payout)) {
			participant.paid = true;
			totalBalance -= participant.payout;
		}
	}

	modifier isEnded {
		if (ended){
			_
		}
	}

	modifier onlyAfter(uint _time) {
		if (now > _time){
			_
		}
	}

	/* return the remaining of balance if there are any unclaimed after cooling period */
	function clear() onlyOwner isEnded onlyAfter(endedAt + coolingPeriod) {
		if(owner.send(totalBalance)){
			totalBalance = 0;
		}
	}
}

import './zeppelin/Rejector.sol';
import './zeppelin/Ownable.sol';
import './zeppelin/Killable.sol';

contract Conference is Rejector, Killable {
	string public name;
	uint256 public totalBalance;
	uint256 public deposit;
	uint public limitOfParticipants;
	uint public registered;
	uint public attended;
	bool public ended;
	uint public endedAt;
	uint public coolingPeriod;

	mapping (address => Participant) public participants;
	mapping (uint => address) public participantsIndex;
	bool paid;
	uint256 _payout;

	struct Participant {
		string participantName;
		address addr;
		bool attended;
		uint256 payout;
		bool paid;
	}

	event Register(string participantName, address addr, uint256 balance, uint256 value);
	event Attend(address addr, uint256 balance);
	event Payback(address addr, uint256 _payout, uint256 balance, bool paid);

	function Conference(uint _coolingPeriod) {
		name = 'Edcon Post conference lunch';
		deposit = 1 ether;
		totalBalance = 0;
		registered = 0;
		attended = 0;
		limitOfParticipants = 10;
		ended = false;
		if (_coolingPeriod != 0) {
			coolingPeriod = _coolingPeriod;
		} else {
			coolingPeriod = 1 weeks;
		}
	}

	modifier sentDepositOrReturn {
		if (msg.value == deposit) {
			_
		}else{
			if(msg.sender.send(msg.value)){/* not much you can do */}
		}
	}

	modifier onlyActive {
		if (ended == false) {
			_
		}
	}

	modifier onlyActiveOrReturn {
		if (ended == false) {
			_
		}else{
			if(msg.sender.send(msg.value)){/*not much you can do*/}
		}
	}

	modifier withinLimitOrReturn {
		if (registered < limitOfParticipants ) {
			_
		}else{
			if(msg.sender.send(msg.value)){/* not much you can do */}
		}
	}

	function register(string _participant) sentDepositOrReturn withinLimitOrReturn onlyActiveOrReturn{
		Register(_participant, msg.sender, msg.sender.balance, msg.value);
		if (isRegistered(msg.sender)) throw;
		registered++;
		participantsIndex[registered] = msg.sender;
		participants[msg.sender] = Participant(_participant, msg.sender, false, 0, false);
		totalBalance = totalBalance + (deposit * 1);
	}

	function setLimitOfParticipants(uint _limitOfParticipants) {
		limitOfParticipants = _limitOfParticipants;
	}

	function attend(address _addr) onlyOwner{
		if (isRegistered(_addr) != true) throw;
		if (isAttended(_addr)) throw;
		Attend(_addr, msg.sender.balance);
		participants[_addr].attended = true;
		attended++;
	}

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

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

	function isPaid(address _addr) returns (bool){
		return isRegistered(_addr) && participants[_addr].paid;
	}

	function payout() returns(uint256){
		return totalBalance / uint(attended);
	}

	function payback() onlyOwner{
		for(uint i=1;i<=registered;i++){
			if(participants[participantsIndex[i]].attended){
				participants[participantsIndex[i]].payout = payout();
			}
		}
		ended = true;
		endedAt = now;
	}

	function cancel() onlyOwner onlyActive{
		for(uint i=1;i<=registered;i++){
			participants[participantsIndex[i]].payout = deposit;
		}
		ended = true;
		endedAt = now;
	}

	modifier onlyPayable {
		Participant participant = participants[msg.sender];
		if (participant.payout > 0){
			_
		}
	}

	modifier notPaid {
		Participant participant = participants[msg.sender];
		if (participant.paid == false){
			_
		}
	}

	function withdraw() onlyPayable notPaid {
		Participant participant = participants[msg.sender];
		if (msg.sender.send(participant.payout)) {
			participant.paid = true;
			totalBalance -= participant.payout;
		}
	}

	modifier isEnded {
		if (ended){
			_
		}
	}

	modifier onlyAfter(uint _time) {
		if (now > _time){
			_
		}
	}

	/* return the remaining of balance if there are any unclaimed after cooling period */
	function clear() onlyOwner isEnded onlyAfter(endedAt + coolingPeriod) {
		if(owner.send(totalBalance)){
			totalBalance = 0;
		}
	}
}


Make packed block number helper functions internal.

/**
 * @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;
        }
        _
    }

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

    function getPackedRevisionBlockNumber(bytes32 id, uint revisionId) internal returns (uint blockNumber) {
        bytes32 slot = idPackedRevisionBlockNumbers[id][(revisionId - 1) / 8];
        uint offset = ((revisionId - 1) % 8) * 32;
        blockNumber = uint32(uint256(slot) / 2 ** offset);
    }

    /**
     * @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 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);
        }
        else {
            if (blobInfo.numRevisions == 0) {
                blobInfo.blockNumber = uint32(block.number);
            }
            else {
                setPackedRevisionBlockNumber(id, blobInfo.numRevisions);
            }
        }
        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 {
            blockNumber = getPackedRevisionBlockNumber(id, revisionId);
        }
    }

    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;
        }
        _
    }

    function setPackedRevisionBlockNumber(bytes32 id, uint revisionId) {
        bytes32 slot = idPackedRevisionBlockNumbers[id][(revisionId - 1) / 8];
        uint multiplier = 2 ** (((revisionId - 1) % 8) * 32);
        slot &= ~bytes32(uint32(-1) * multiplier);
        slot |= bytes32(uint32(block.number) * multiplier);
        idPackedRevisionBlockNumbers[id][(revisionId - 1) / 8] = slot;
    }

    function getPackedRevisionBlockNumber(bytes32 id, uint revisionId) returns (uint blockNumber) {
        bytes32 slot = idPackedRevisionBlockNumbers[id][(revisionId - 1) / 8];
        uint offset = ((revisionId - 1) % 8) * 32;
        blockNumber = uint32(uint256(slot) / 2 ** offset);
    }

    /**
     * @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 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);
        }
        else {
            if (blobInfo.numRevisions == 0) {
                blobInfo.blockNumber = uint32(block.number);
            }
            else {
                setPackedRevisionBlockNumber(id, blobInfo.numRevisions);
            }
        }
        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 {
            blockNumber = getPackedRevisionBlockNumber(id, revisionId);
        }
    }

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

}