Restrict execute to owners.

Restrict execute to owners.

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

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

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

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

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

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

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

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

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

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

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

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

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

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


fix allowance check

fix allowance check

contract TokenInterface {
  function transfer( address to, uint value) returns (bool ok);
  function transferFrom( address from, address to, uint value) returns (bool ok);
  function allowance(address owner, address spender) constant returns (uint _allowance);
}

contract DeployRelay {
  struct Deployment {
    address requester;
    address deployer;
    bytes32 codeHash;
    address token;
    uint fee;
    bool deployed;
  }
  uint256 public numDeployments;
  bool public something;

  mapping (uint256 => Deployment) public deployments;

  event NewDeployment(address indexed _deployer, bytes32 _codeHash, uint256 deploymentId);
  event Deployed(address indexed from, address indexed deployedBy, address deployedAddress, bytes32 codeHash, uint fee);

  function DeployRelay() {
  }

  function reserveDeployment(address requesterAddress, bytes32 codeHash, address tokenAddress, uint tokenNum, uint8 v, bytes32 r, bytes32 s) {
    address signatureAddress = ecrecover(codeHash, v, r, s);
    if (signatureAddress != requesterAddress) throw;

    uint256 deploymentId = ++numDeployments;

    Deployment deployment = deployments[deploymentId];
    deployment.requester = requesterAddress;
    deployment.deployer  = msg.sender;
    deployment.codeHash = codeHash;
    deployment.token = tokenAddress;
    deployment.fee = tokenNum;

    NewDeployment(msg.sender, codeHash, deploymentId);
  }

  function confirmDeployment(uint256 deploymentId, address deployedAddress, bytes32 codeHash) {
    Deployment deployment = deployments[deploymentId];
    if (deployment.requester == 0x0) throw;
    if (deployment.deployed) throw;

    if (deployment.codeHash != codeHash) throw;
    if (!verifyDeployment(deployedAddress, codeHash)) throw;

    TokenInterface token = TokenInterface(deployment.token);
    if (token.allowance(deployment.requester, this) < deployment.fee) throw;

    if (token.transferFrom(deployment.requester, msg.sender, deployment.fee)) {
      deployment.deployed = true;
      Deployed(deployment.requester, msg.sender, deployedAddress, codeHash, deployment.fee);
    }
  }

  function verifyDeployment(address addr, bytes32 expectedHash) constant returns (bool result) {
    bytes32 deployedHash;

    assembly {
      let size := extcodesize(addr)
      let o_code := mload(0x40)
      mstore(0x40, add(o_code, and(add(add(size, 0x20), 0x1f), not(0x1f))))
      mstore(o_code, size)
      extcodecopy(addr, add(o_code, 0x20), 0, size)
      deployedHash := sha3(add(o_code, 0x20), size)
    }

    result = (deployedHash == expectedHash);
  }

  function verifySignature(address from, uint num, bytes32 code) constant returns (bool result) {
    bytes32 expectedSignatureHash;
    expectedSignatureHash = sha3(from, num);

    result = (expectedSignatureHash == code);
  }

  function recoverAddress(bytes32 hash2, uint8 v, bytes32 r, bytes32 s) constant returns(address addr) {
    addr = ecrecover(hash2, v, r, s);
  }

}

contract TokenInterface {
  function transfer( address to, uint value) returns (bool ok);
  function transferFrom( address from, address to, uint value) returns (bool ok);
  function allowance(address owner, address spender) constant returns (uint _allowance);
}

contract DeployRelay {
  struct Deployment {
    address requester;
    address deployer;
    bytes32 codeHash;
    address token;
    uint fee;
    bool deployed;
  }
  uint256 public numDeployments;
  bool public something;

  mapping (uint256 => Deployment) public deployments;

  event NewDeployment(address indexed _deployer, bytes32 _codeHash, uint256 deploymentId);
  event Deployed(address indexed from, address indexed deployedBy, address deployedAddress, bytes32 codeHash, uint fee);

  function DeployRelay() {
  }

  function reserveDeployment(address requesterAddress, bytes32 codeHash, address tokenAddress, uint tokenNum, uint8 v, bytes32 r, bytes32 s) {
    address signatureAddress = ecrecover(codeHash, v, r, s);
    if (signatureAddress != requesterAddress) throw;

    uint256 deploymentId = ++numDeployments;

    Deployment deployment = deployments[deploymentId];
    deployment.requester = requesterAddress;
    deployment.deployer  = msg.sender;
    deployment.codeHash = codeHash;
    deployment.token = tokenAddress;
    deployment.fee = tokenNum;

    NewDeployment(msg.sender, codeHash, deploymentId);
  }

  function confirmDeployment(uint256 deploymentId, address deployedAddress, bytes32 codeHash) {
    Deployment deployment = deployments[deploymentId];
    if (deployment.requester == 0x0) throw;
    if (deployment.deployed) throw;

    if (deployment.codeHash != codeHash) throw;
    if (!verifyDeployment(deployedAddress, codeHash)) throw;

    TokenInterface token = TokenInterface(deployment.token);
    if (token.allowance(deployment.requester, msg.sender) < deployment.fee) throw;

    if (token.transferFrom(deployment.requester, msg.sender, deployment.fee)) {
      deployment.deployed = true;
      Deployed(deployment.requester, msg.sender, deployedAddress, codeHash, deployment.fee);
    }
  }

  function verifyDeployment(address addr, bytes32 expectedHash) constant returns (bool result) {
    bytes32 deployedHash;

    assembly {
      let size := extcodesize(addr)
      let o_code := mload(0x40)
      mstore(0x40, add(o_code, and(add(add(size, 0x20), 0x1f), not(0x1f))))
      mstore(o_code, size)
      extcodecopy(addr, add(o_code, 0x20), 0, size)
      deployedHash := sha3(add(o_code, 0x20), size)
    }

    result = (deployedHash == expectedHash);
  }

  function verifySignature(address from, uint num, bytes32 code) constant returns (bool result) {
    bytes32 expectedSignatureHash;
    expectedSignatureHash = sha3(from, num);

    result = (expectedSignatureHash == code);
  }

  function recoverAddress(bytes32 hash2, uint8 v, bytes32 r, bytes32 s) constant returns(address addr) {
    addr = ecrecover(hash2, v, r, s);
  }

}


Fix ECRecovery contract indentation

Fix ECRecovery contract indentation

Fix ident on github

Fix ident github

Fix ident on github

pragma solidity ^0.4.11;

/**
* Eliptic curve signature operations
* Based on https://gist.github.com/axic/5b33912c6f61ae6fd96d6c4a47afde6d
*/
library ECRecovery {

  // Duplicate Solidity's ecrecover, but catching the CALL return value
  function safeRecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) {
    // We do our own memory management here. Solidity uses memory offset
    // 0x40 to store the current end of memory. We write past it (as
    // writes are memory extensions), but don't update the offset so
    // Solidity will reuse it. The memory used here is only needed for
    // this context.

    bool ret;
    address addr;

    assembly {
      let size := mload(0x40)
      mstore(size, hash)
      mstore(add(size, 32), v)
      mstore(add(size, 64), r)
      mstore(add(size, 96), s)

      // NOTE: we can reuse the request memory because we deal with
      //       the return code
      ret := call(3000, 1, 0, size, 128, size, 32)
      addr := mload(size)
    }

    return (ret, addr);
  }

  function recover(bytes32 hash, bytes sig) internal returns (address) {
    bytes32 r;
    bytes32 s;
    uint8 v;

    if (sig.length != 65)
      return (address(0));

    assembly {
      r := mload(add(sig, 32))
      s := mload(add(sig, 64))
      v := byte(0, mload(add(sig, 96)))
    }

    // albeit non-transactional signatures are not specified by the YP, one would expect it
    // to match the YP range of [27, 28]
    //
    // geth uses [0, 1] and some clients have followed. This might change, see:
    //  https://github.com/ethereum/go-ethereum/issues/2053
    if (v < 27)
     v += 27;

    if (v != 27 && v != 28)
      return (address(0));

    bool ret;
    address addr;
    (ret, addr) = safeRecover(hash, v, r, s);
    return addr;
  }

}


Create tokenDecimals.sol

Create tokenDecimals.sol

Token with decimals.

import 'common/Mortal.sol';

/**
 * @title Token contract represents any asset in digital economy
 */
contract Token is Mortal {
    /* Short description of token */
    string public name;
    string public symbol;
    uint8 public decimals;

    /* Total count of tokens exist */
    uint public totalSupply;

    /* Token approvement system */
    mapping(address => uint) public balanceOf;
    mapping(address => mapping (address => uint)) public approveOf;

    /**
     * @return available balance of `sender` account (self balance)
     */
    function getBalance() constant returns (uint)
    { return balanceOf[msg.sender]; }

    /**
     * @dev This method returns non zero result when sender is approved by
     *      argument address and target address have non zero self balance
     * @param _address target address
     * @return available for `sender` balance of given address
     */
    function getBalance(address _address) constant returns (uint) {
        return approveOf[_address][msg.sender]
             > balanceOf[_address] ? balanceOf[_address]
                                   : approveOf[_address][msg.sender];
    }

    /**
     * @return `true` wnen `sender` have non zero available balance for target address
     * @dev Synonym for getBalance(address _address)
     */
    function isApproved(address _address) constant returns (bool)
    { return approveOf[_address][msg.sender] > 0; }

    /* Token constructor */
    function Token(string _name, string _symbol) {
        name   = _name;
        symbol = _symbol;
    }

    /*
     * Token manipulation methods only for owner
     */

    /**
     * @dev Token emission
     * @param _value amount of token values to emit
     * @notice owner balance will be increased by `_value`
     */
    function emission(uint _value) onlyOwner {
        totalSupply      += _value;
        balanceOf[owner] += _value;
    }

    /**
     * @dev Burn the token values from owner balance and from total
     * @param _value amount of token values for burn
     * @notice owner balance will be decreased by `_value`
     */
    function burn(uint _value) onlyOwner {
        if (balanceOf[owner] >= _value) {
            balanceOf[owner] -= _value;
            totalSupply      -= _value;
        }
    }

    /*
     * Public token methods for everyone
     */

    /**
     * @dev Transfer self tokens to given address
     * @param _to destination address
     * @param _value amount of token values to send
     * @notice `_value` tokens will be sended to `_to`
     * @return `true` when transfer done
     */
    function transfer(address _to, uint _value) returns (bool) {
        if (balanceOf[msg.sender] >= _value) {
            balanceOf[msg.sender] -= _value;
            balanceOf[_to]        += _value;
            return true;
        }
        return false;
    }

    /**
     * @dev Transfer with approvement mechainsm
     * @param _from source address, `_value` tokens shold be approved for `sender`
     * @param _to destination address
     * @param _value amount of token values to send
     * @notice from `_from` will be sended `_value` tokens to `_to`
     * @return `true` when transfer is done
     */
    function transferFrom(address _from, address _to, uint _value) returns (bool) {
        var avail = approveOf[_from][msg.sender]
                  > balanceOf[_from] ? balanceOf[_from]
                                     : approveOf[_from][msg.sender];
        if (avail >= _value) {
            approveOf[_from][msg.sender] -= _value;
            balanceOf[_from] -= _value;
            balanceOf[_to]   += _value;
            return true;
        }
        return false;
    }

    /**
     * @dev Give to target address ability for self token manipulation without sending
     * @param _address target address
     * @param _value amount of token values for approving
     */
    function approve(address _address, uint _value)
    { approveOf[msg.sender][_address] += _value; }

    /**
     * @dev Reset count of tokens approved for given address
     * @param _address target address
     */
    function unapprove(address _address)
    { approveOf[msg.sender][_address] = 0; }
}

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


removed commented code

removed commented code

import "Owned";

contract PredictionMarket is Owned
{
	struct Order
	{
		address seller;
		address buyer;
		uint odds;				// in %
		uint sellerQuantity;	// in wei
		uint buyerQuantity;		// in wei
	}

	Order[] public orders;

	function ordersLength() constant
		returns(uint result)
	{
		return orders.length;
	}

	function sellOrder(uint odds)
	{
		var seller = msg.sender;
		var sellerQuantity = msg.value;

		while(sellerQuantity > 0)
		{
			var maxOddsFound = false;
			var maxOddsIndex = 0;
			var maxOdds = odds - 1;

			for(var i = 0; i < orders.length; i++)
			{
				var o = orders[i];

				if(o.seller == 0 && o.odds > maxOdds)
				{
					maxOddsFound = true;
					maxOddsIndex = i;
					maxOdds = o.odds;
				}
			}

			if(maxOddsFound)
			{
				var mo = orders[maxOddsIndex];

				if(sellerQuantity >= mo.sellerQuantity)
				{
					// maxOdds only partially fills order

					mo.seller = seller;
					sellerQuantity -= mo.sellerQuantity;
				}
				else
				{
					// maxOdds completely fills order

					var mBuyerQuantity = sellerQuantity * 100 / (100 - mo.odds) - sellerQuantity;

					if(mBuyerQuantity < mo.buyerQuantity)
					{
						// create a new order that represents the completed trade
						var completedOrder = Order(seller, mo.buyer, mo.odds, sellerQuantity, mBuyerQuantity);
						orders.push(completedOrder);

						// adjust maxOdds in place to preserve the order's priority
						mo.buyerQuantity -= mBuyerQuantity;
						mo.sellerQuantity -= sellerQuantity;

						sellerQuantity = 0;
					}
					else
					{
						// everything must just be off by a rounding error, so just call it even
						// I'm not sure that it is even possible to get here

						mo.seller = seller;
						sellerQuantity = 0;
					}
				}
			}
			else
			{
				// no suitable existing order found, so create a new one

				var buyerQuantity = sellerQuantity * 100 / (100 - odds) - sellerQuantity;

				var order = Order(seller, 0, odds, sellerQuantity, buyerQuantity);
				orders.push(order);

				sellerQuantity = 0;
			}
		}
	}

	function buyOrder(uint odds)
	{
		var buyer = msg.sender;
		var buyerQuantity = msg.value;

		while(buyerQuantity > 0)
		{
			var minOddsFound = false;
			var minOddsIndex = 0;
			var minOdds = odds + 1;

			for(var i = 0; i < orders.length; i++)
			{
				var o = orders[i];

				if(o.buyer == 0 && o.odds < minOdds)
				{
					minOddsFound = true;
					minOddsIndex = i;
					minOdds = o.odds;
				}
			}

			if(minOddsFound)
			{
				var mo = orders[minOddsIndex];

				if(buyerQuantity >= mo.buyerQuantity)
				{
					// minOdds only partially fills order

					mo.buyer = buyer;
					buyerQuantity -= mo.buyerQuantity;
				}
				else
				{
					// minOdds completely fills order

					var mSellerQuantity = buyerQuantity * 100 / mo.odds - buyerQuantity;

					if(mSellerQuantity < mo.sellerQuantity)
					{
						// create a new order that represents the completed trade
						var completedOrder = Order(mo.seller, buyer, mo.odds, mSellerQuantity, buyerQuantity);
						orders.push(completedOrder);

						// adjust minOdds in place to preserve the order's priority
						mo.buyerQuantity -= buyerQuantity;
						mo.sellerQuantity -= mSellerQuantity;

						buyerQuantity = 0;
					}
					else
					{
						// everything must just be off by a rounding error, so just call it even
						// I'm not sure that it is even possible to get here

						mo.buyer = buyer;
						buyerQuantity = 0;
					}
				}
			}
			else
			{
				// no suitable existing order found, so create a new one

				var sellerQuantity = buyerQuantity * 100 / odds - buyerQuantity;

				var order = Order(0, buyer, odds, sellerQuantity, buyerQuantity);
				orders.push(order);

				buyerQuantity = 0;
			}
		}
	}

	function cancelOrder(uint odds, uint quantity)
	{

	}

	function awardBuyers() onlyowner
	{

	}

	function awardSellers() onlyowner
	{

	}

	function revert() onlyowner
	{

	}
}

import "Owned";

contract PredictionMarket is Owned
{
	struct Order
	{
		address seller;
		address buyer;
		uint odds;				// in %
		uint sellerQuantity;	// in wei
		uint buyerQuantity;		// in wei
	}

	Order[] public orders;

	function ordersLength() constant
		returns(uint result)
	{
		return orders.length;
	}

	function sellOrder(uint odds)
	{
		var seller = msg.sender;
		var sellerQuantity = msg.value;

		//var buyerQuantity = sellerQuantity * 100 / (100 - odds) - sellerQuantity;
		//var order = Order(seller, 0, odds, sellerQuantity, buyerQuantity);
		//orders.push(order);

		while(sellerQuantity > 0)
		{
			var maxOddsFound = false;
			var maxOddsIndex = 0;
			var maxOdds = odds - 1;

			for(var i = 0; i < orders.length; i++)
			{
				var o = orders[i];

				if(o.seller == 0 && o.odds > maxOdds)
				{
					maxOddsFound = true;
					maxOddsIndex = i;
					maxOdds = o.odds;
				}
			}

			if(maxOddsFound)
			{
				var mo = orders[maxOddsIndex];

				if(sellerQuantity >= mo.sellerQuantity)
				{
					// maxOdds only partially fills order

					mo.seller = seller;
					sellerQuantity -= mo.sellerQuantity;
				}
				else
				{
					// maxOdds completely fills order

					var mBuyerQuantity = sellerQuantity * 100 / (100 - mo.odds) - sellerQuantity;

					if(mBuyerQuantity < mo.buyerQuantity)
					{
						// create a new order that represents the completed trade
						var completedOrder = Order(seller, mo.buyer, mo.odds, sellerQuantity, mBuyerQuantity);
						orders.push(completedOrder);

						// adjust maxOdds in place to preserve the order's priority
						mo.buyerQuantity -= mBuyerQuantity;
						mo.sellerQuantity -= sellerQuantity;

						sellerQuantity = 0;
					}
					else
					{
						// everything must just be off by a rounding error, so just call it even
						// I'm not sure that it is even possible to get here

						mo.seller = seller;
						sellerQuantity = 0;
					}
				}
			}
			else
			{
				// no suitable existing order found, so create a new one

				var buyerQuantity = sellerQuantity * 100 / (100 - odds) - sellerQuantity;

				var order = Order(seller, 0, odds, sellerQuantity, buyerQuantity);
				orders.push(order);

				sellerQuantity = 0;
			}
		}
	}

	function buyOrder(uint odds)
	{
		var buyer = msg.sender;
		var buyerQuantity = msg.value;

		while(buyerQuantity > 0)
		{
			var minOddsFound = false;
			var minOddsIndex = 0;
			var minOdds = odds + 1;

			for(var i = 0; i < orders.length; i++)
			{
				var o = orders[i];

				if(o.buyer == 0 && o.odds < minOdds)
				{
					minOddsFound = true;
					minOddsIndex = i;
					minOdds = o.odds;
				}
			}

			if(minOddsFound)
			{
				var mo = orders[minOddsIndex];

				if(buyerQuantity >= mo.buyerQuantity)
				{
					// minOdds only partially fills order

					mo.buyer = buyer;
					buyerQuantity -= mo.buyerQuantity;
				}
				else
				{
					// minOdds completely fills order

					var mSellerQuantity = buyerQuantity * 100 / mo.odds - buyerQuantity;

					if(mSellerQuantity < mo.sellerQuantity)
					{
						// create a new order that represents the completed trade
						var completedOrder = Order(mo.seller, buyer, mo.odds, mSellerQuantity, buyerQuantity);
						orders.push(completedOrder);

						// adjust minOdds in place to preserve the order's priority
						mo.buyerQuantity -= buyerQuantity;
						mo.sellerQuantity -= mSellerQuantity;

						buyerQuantity = 0;
					}
					else
					{
						// everything must just be off by a rounding error, so just call it even
						// I'm not sure that it is even possible to get here

						mo.buyer = buyer;
						buyerQuantity = 0;
					}
				}
			}
			else
			{
				// no suitable existing order found, so create a new one

				var sellerQuantity = buyerQuantity * 100 / odds - buyerQuantity;

				var order = Order(0, buyer, odds, sellerQuantity, buyerQuantity);
				orders.push(order);

				buyerQuantity = 0;
			}
		}
	}

	function cancelOrder(uint odds, uint quantity)
	{

	}

	function awardBuyers() onlyowner
	{

	}

	function awardSellers() onlyowner
	{

	}

	function revert() onlyowner
	{

	}
}


fix for loop, move return statement

fix for loop, move return statement

import ../user.sol
import ../userMaster.sol

contract GroupRegistry
{
  mapping (address => address[]) groups;
  mapping (address => address) conceptFromGroup;
  address userMasterAddress;

  modifier onlyUser()
  {
    if(userMaster(userMasterAddress).getTokenBalance(msg.sender) <= 0)
    {
      throw;
    }
    _;
  }

  function GroupRegistry(address _userMasterAddress)
  {
    userMasterAddress = _userMasterAddress;
  }

  function addMember(address group) returns (bool success) onlyUser() payable()
  {
    for (uint i = 0, i < Group(group).members.length(), i++)
    {
      if(User(msg.sender).getConceptPassed(Group.requirements[i]) == false)
      {
        return false;
      }
      if (Group(group).members.length() = Group(group.size))
      {
        return false;
      }
      Group(group).addMember(msg.sender);
    }
    return true;
  }

  function addGroup(address concept, uint size)
  {
    Group newGroup = new Group(concept, size, msg.sender);
    groups[concept].push(address(Group));
    conceptFromGroup[address(group)] = concept;
  }
}

contract Group
{
  uint public size;
  address[] public members;
  address[] public requirements;
  address concept;
  address registry;

  modifier onlyRegistry()
  {
    if (msg.sender != registry)
    {
      throw;
    }
    _;
  }

  function Group(address _concept, uint _size, address member)
  {
    concept = _concept;
    registry = msg.sender;
    requirements = _size;
    members.push(member);
    size = _size;
  }

  function addMember(address member) onlyRegistry()
  {
    members.push(member);
  }
}

import ../user.sol
import ../userMaster.sol

contract GroupRegistry
{
  mapping (address => address[]) groups;
  mapping (address => address) conceptFromGroup;
  address userMasterAddress;

  modifier onlyUser()
  {
    if(userMaster(userMasterAddress).getTokenBalance(msg.sender) <= 0)
    {
      throw;
    }
    _;
  }

  function GroupRegistry(address _userMasterAddress)
  {
    userMasterAddress = _userMasterAddress;
  }

  function addMember(address group) returns (bool success) onlyUser() payable()
  {
    for (uint i = 0, if i < Group(group).members.length(), i++)
    {
      if(User(msg.sender).getConceptPassed(Group.requirements[i]) == false)
      {
        return false;
      }
      if (Group(group).members.length() = Group(group.size))
      {
        return false;
      }
      Group(group).addMember(msg.sender);
      return true;
    }
  }

  function addGroup(address concept, uint size)
  {
    Group newGroup = new Group(concept, size, msg.sender);
    groups[concept].push(address(Group));
    conceptFromGroup[address(group)] = concept;
  }
}

contract Group
{
  uint public size;
  address[] public members;
  address[] public requirements;
  address concept;
  address registry;

  modifier onlyRegistry()
  {
    if (msg.sender != registry)
    {
      throw;
    }
    _;
  }

  function Group(address _concept, uint _size, address member)
  {
    concept = _concept;
    registry = msg.sender;
    requirements = _size;
    members.push(member);
    size = _size;
  }

  function addMember(address member) onlyRegistry()
  {
    members.push(member);
  }
}


Initial memory hashing routine.

Initial memory hashing routine.

pragma solidity ^0.4.0;

import {ScryptFramework} from "./scryptFramework.sol";

contract ScryptRunner is ScryptFramework {
    function initMemory(State memory state) pure internal {
        state.fullMemory = new uint[](4 * 1024);
    }

    function run(bytes input, uint upToStep) pure returns (uint[4] vars, bytes proof, uint readIndex, uint[4] varsout, uint[4] read) {
        State memory s = inputToState(input);
        Proofs memory proofs;
        if (upToStep > 0) {
            uint internalStep = upToStep - 1;
            for (uint i = 0; i < internalStep; i++) {
                runStep(s, i, proofs);
            }
            proofs.generateProofs = true;
            if (internalStep < 2048) {
                runStep(s, internalStep, proofs);
            } else {
                proofs.proofs = finalStateToOutput(s);
            }
        }
        vars[0] = s.vars[0];
        vars[1] = s.vars[1];
        vars[2] = s.vars[2];
        vars[3] = s.vars[3];
        proof = proofs.proofs;
        readIndex = proofs.readIndex;
        varsout = proofs.vars;
        read = proofs.read;
    }

    function readMemory(State memory state, uint index, Proofs memory /*proofs*/) pure internal returns (uint a, uint b, uint c, uint d) {
        require(index < 1024);
        uint pos = 0x20 * 4 * index;
        uint[] memory fullMem = state.fullMemory;
        assembly {
            pos := add(pos, 0x20)
            a := mload(add(fullMem, pos))
            pos := add(pos, 0x20)
            b := mload(add(fullMem, pos))
            pos := add(pos, 0x20)
            c := mload(add(fullMem, pos))
            pos := add(pos, 0x20)
            d := mload(add(fullMem, pos))
        }
    }
    function writeMemory(State memory state, uint index, uint[4] values, Proofs memory proofs) pure internal {
        require(index < 1024);
        uint pos = 0x20 * 4 * index;
        uint[] memory fullMem = state.fullMemory;
        var (a, b, c, d) = (values[0], values[1], values[2], values[3]);
        assembly {
            pos := add(pos, 0x20)
            mstore(add(fullMem, pos), a)
            pos := add(pos, 0x20)
            mstore(add(fullMem, pos), b)
            pos := add(pos, 0x20)
            mstore(add(fullMem, pos), c)
            pos := add(pos, 0x20)
            mstore(add(fullMem, pos), d)
        }
        if (proofs.generateProofs) {
            proofs.proofs = generateMemoryProof(state.fullMemory, index);
        }
    }
    // Generate a proof that shows that the memory root hash was updated correctly.
    // This assumes that index is multiplied by four.
    // Returns a list of hashes of siblings.
    // Since we know that memory is only written in sequence, this might be
    // optimized, but we keep it general for now.
    function generateMemoryProof(uint[] fullMem, uint index) internal pure returns (bytes) {
        uint access = index;
        bytes32[] memory siblings = new bytes32[](12);
        bytes32[] memory hashes = new bytes32[](1024);
        for (uint i = 0; i < 1024; i++)
            hashes[i] = keccak256(fullMem[4 * i], fullMem[4 * i + 1], fullMem[4 * i + 2], fullMem[4 * i + 3]);
        uint numHashes = 1024;
        for (uint step = 0; step < 12; step++) {
            siblings[step] = hashes[access ^ 1];
            access /= 2;
            numHashes /= 2;
            for (i = 0; i < numHashes; i++) {
                hashes[i] = keccak256(hashes[2 * i], hashes[2 * i + 1]);
            }
        }
        uint size = siblings.length;
        bytes memory proof = new bytes(32 * size);
        assembly {
            for { let j := 0 } lt(j, size) { j := add(j, 1) } {
                let offset := mul(0x20, add(1, j))
                mstore(add(proof, offset), mload(add(siblings, offset)))
            }
        }
        return proof;
    }
}

pragma solidity ^0.4.0;

import {ScryptFramework} from "./scryptFramework.sol";

contract ScryptRunner is ScryptFramework {
    function initMemory(State memory state) pure internal {
        state.fullMemory = new uint[](4 * 1024);
    }

    function run(bytes input, uint upToStep) pure returns (uint[4] vars, bytes proof, uint readIndex, uint[4] varsout, uint[4] read) {
        State memory s = inputToState(input);
        Proofs memory proofs;
        if (upToStep > 0) {
            uint internalStep = upToStep - 1;
            for (uint i = 0; i < internalStep; i++) {
                runStep(s, i, proofs);
            }
            proofs.generateProofs = true;
            if (internalStep < 2048) {
                runStep(s, internalStep, proofs);
            } else {
                proofs.proofs = finalStateToOutput(s);
            }
        }
        vars[0] = s.vars[0];
        vars[1] = s.vars[1];
        vars[2] = s.vars[2];
        vars[3] = s.vars[3];
        proof = proofs.proofs;
        readIndex = proofs.readIndex;
        varsout = proofs.vars;
        read = proofs.read;
    }

    function readMemory(State memory state, uint index, Proofs memory /*proofs*/) pure internal returns (uint a, uint b, uint c, uint d) {
        require(index < 1024);
        uint pos = 0x20 * 4 * index;
        uint[] memory fullMem = state.fullMemory;
        assembly {
            pos := add(pos, 0x20)
            a := mload(add(fullMem, pos))
            pos := add(pos, 0x20)
            b := mload(add(fullMem, pos))
            pos := add(pos, 0x20)
            c := mload(add(fullMem, pos))
            pos := add(pos, 0x20)
            d := mload(add(fullMem, pos))
        }
    }
    function writeMemory(State memory state, uint index, uint[4] values, Proofs memory /*proofs*/) pure internal {
        require(index < 1024);
        uint pos = 0x20 * 4 * index;
        uint[] memory fullMem = state.fullMemory;
        var (a, b, c, d) = (values[0], values[1], values[2], values[3]);
        assembly {
            pos := add(pos, 0x20)
            mstore(add(fullMem, pos), a)
            pos := add(pos, 0x20)
            mstore(add(fullMem, pos), b)
            pos := add(pos, 0x20)
            mstore(add(fullMem, pos), c)
            pos := add(pos, 0x20)
            mstore(add(fullMem, pos), d)
        }
    }
}


Update getValue function signature

Update getValue function signature

pragma solidity ^0.4.11;

contract locker {
    // Nested mapping: funds[initiator][intermediary][receiver] contains the value of ETH locked up by that triple.
    mapping (address => mapping (address => mapping (address => uint))) funds;

    // The account from where ETH is received is the initiator.
    function storeInContract(address intermediary, address receiver) payable {
        funds[msg.sender][intermediary][receiver] += msg.value;
    }

    // Get amount of ETH locked up with a triple.
    function getValue(address initiator, address intermediary, address receiver) constant returns (uint) {
        return funds[initiator][intermediary][receiver];
    }

    // Common function used to check is sufficient balance is present in a
    // trio and send it to the target if that is the case.
    function sendToTarget(address initiator, address intermediary, address receiver, address target, uint amount) {
        if (funds[initiator][intermediary][receiver] >= amount) {
            funds[initiator][intermediary][receiver] -= amount;
            target.transfer(amount);
        }
        else {
            throw;
        }
    }

    // Send ETH to the receiver from the initiator.
    function sendToReceiver(address intermediary, address receiver, uint amount) {
        sendToTarget(msg.sender, intermediary, receiver, receiver, amount);
    }

    // Send ETH to the receiver from the intermediary.
    function moveToReceiver(address initiator, address receiver, uint amount) {
        sendToTarget(initiator, msg.sender, receiver, receiver, amount);
    }

    // Send ETH to the initiator from the intermediary.
    function moveToInitiator(address initiator, address receiver, uint amount) {
        sendToTarget(initiator, msg.sender, receiver, initiator, amount);
    }
}

pragma solidity ^0.4.11;

contract locker {
    // Nested mapping: funds[initiator][intermediary][receiver] contains the value of ETH locked up by that triple.
    mapping (address => mapping (address => mapping (address => uint))) funds;

    // The account from where ETH is received is the initiator.
    function storeInContract(address intermediary, address receiver) payable {
        funds[msg.sender][intermediary][receiver] += msg.value;
    }

    // Get amount of ETH locked up with a triple.
    function getValue(address initiator, address intermediary, address receiver) {
        return funds[initiator][intermediary][receiver];
    }

    // Common function used to check is sufficient balance is present in a
    // trio and send it to the target if that is the case.
    function sendToTarget(address initiator, address intermediary, address receiver, address target, uint amount) {
        if (funds[initiator][intermediary][receiver] >= amount) {
            funds[initiator][intermediary][receiver] -= amount;
            target.transfer(amount);
        }
        else {
            throw;
        }
    }

    // Send ETH to the receiver from the initiator.
    function sendToReceiver(address intermediary, address receiver, uint amount) {
        sendToTarget(msg.sender, intermediary, receiver, receiver, amount);
    }

    // Send ETH to the receiver from the intermediary.
    function moveToReceiver(address initiator, address receiver, uint amount) {
        sendToTarget(initiator, msg.sender, receiver, receiver, amount);
    }

    // Send ETH to the initiator from the intermediary.
    function moveToInitiator(address initiator, address receiver, uint amount) {
        sendToTarget(initiator, msg.sender, receiver, initiator, amount);
    }
}


removed redundant import

removed redundant import

pragma solidity ^0.4.8;

/**
      @notice Base Token contract according to ERC20
      https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 {
  uint public totalSupply;
  function balanceOf(address who) constant returns (uint);
  function allowance(address owner, address spender) constant returns (uint);
  function transfer(address to, uint value) returns (bool ok);
  function transferFrom(address from, address to, uint value) returns (bool ok);
  function approve(address spender, uint value) returns (bool ok);
  event Transfer(address indexed from, address indexed to, uint value);
  event Approval(address indexed owner, address indexed spender, uint value);
}

pragma solidity ^0.4.8;

import "./SafeMath.sol";

/**
      @notice Base Token contract according to ERC20
      https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 {
  uint public totalSupply;
  function balanceOf(address who) constant returns (uint);
  function allowance(address owner, address spender) constant returns (uint);
  function transfer(address to, uint value) returns (bool ok);
  function transferFrom(address from, address to, uint value) returns (bool ok);
  function approve(address spender, uint value) returns (bool ok);
  event Transfer(address indexed from, address indexed to, uint value);
  event Approval(address indexed owner, address indexed spender, uint value);
}


Gender of signer is irrelevant and distracting (#822)

pragma solidity ^0.4.18;

/**
 * @title Eliptic curve signature operations
 *
 * @dev Based on https://gist.github.com/axic/5b33912c6f61ae6fd96d6c4a47afde6d
 */

library ECRecovery {

  /**
   * @dev Recover signer address from a message by using their signature
   * @param hash bytes32 message, the hash is the signed message. What is recovered is the signer address.
   * @param sig bytes signature, the signature is generated using web3.eth.sign()
   */
  function recover(bytes32 hash, bytes sig) public pure returns (address) {
    bytes32 r;
    bytes32 s;
    uint8 v;

    //Check the signature length
    if (sig.length != 65) {
      return (address(0));
    }

    // Divide the signature in r, s and v variables
    assembly {
      r := mload(add(sig, 32))
      s := mload(add(sig, 64))
      v := byte(0, mload(add(sig, 96)))
    }

    // Version of signature should be 27 or 28, but 0 and 1 are also possible versions
    if (v < 27) {
      v += 27;
    }

    // If the version is correct return the signer address
    if (v != 27 && v != 28) {
      return (address(0));
    } else {
      return ecrecover(hash, v, r, s);
    }
  }

}

pragma solidity ^0.4.18;

/**
 * @title Eliptic curve signature operations
 *
 * @dev Based on https://gist.github.com/axic/5b33912c6f61ae6fd96d6c4a47afde6d
 */

library ECRecovery {

  /**
   * @dev Recover signer address from a message by using his signature
   * @param hash bytes32 message, the hash is the signed message. What is recovered is the signer address.
   * @param sig bytes signature, the signature is generated using web3.eth.sign()
   */
  function recover(bytes32 hash, bytes sig) public pure returns (address) {
    bytes32 r;
    bytes32 s;
    uint8 v;

    //Check the signature length
    if (sig.length != 65) {
      return (address(0));
    }

    // Divide the signature in r, s and v variables
    assembly {
      r := mload(add(sig, 32))
      s := mload(add(sig, 64))
      v := byte(0, mload(add(sig, 96)))
    }

    // Version of signature should be 27 or 28, but 0 and 1 are also possible versions
    if (v < 27) {
      v += 27;
    }

    // If the version is correct return the signer address
    if (v != 27 && v != 28) {
      return (address(0));
    } else {
      return ecrecover(hash, v, r, s);
    }
  }

}


TestableMarketContractOraclize: Remove oracleQueryRepeatSeconds.

The argument was removed from MarketContractOraclize.

Issue: #57

/*
    Copyright 2017-2018 Phillip A. Elsasser

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

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

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

pragma solidity ^0.4.18;

import "./MarketContractOraclize.sol";

/// @title Testable version of MarketContractOraclize that exposes a function to manually update last price.
/// This is deployed to the test network in place of the actual MarketContractOraclize
/// @author Perfect Makanju <root@perfect.engineering>
contract TestableMarketContractOraclize is MarketContractOraclize {

    /// @param contractName viewable name of this contract (BTC/ETH, LTC/ETH, etc)
    /// @param marketTokenAddress address of our member token
    /// @param baseTokenAddress address of the ERC20 token that will be used for collateral and pricing
    /// @param contractSpecs array of unsigned integers including:
    /// floorPrice minimum tradeable price of this contract, contract enters settlement if breached
    /// capPrice maximum tradeable price of this contract, contract enters settlement if breached
    /// priceDecimalPlaces number of decimal places to convert our queried price from a floating point to
    /// an integer
    /// qtyMultiplier multiply traded qty by this value from base units of collateral token.
    /// expirationTimeStamp - seconds from epoch that this contract expires and enters settlement
    /// @param oracleDataSource a data-source such as "URL", "WolframAlpha", "IPFS"dv
    /// see http://docs.oraclize.it/#ethereum-quick-start-simple-query
    /// @param oracleQuery see http://docs.oraclize.it/#ethereum-quick-start-simple-query for examples
    function TestableMarketContractOraclize(
        string contractName,
        address marketTokenAddress,
        address baseTokenAddress,
        uint[5] contractSpecs,
        string oracleDataSource,
        string oracleQuery
    ) MarketContractOraclize(
        contractName,
        marketTokenAddress,
        baseTokenAddress,
        contractSpecs,
        oracleDataSource,
        oracleQuery
    ) public payable { }

    /// @notice allows the creator of the contract to manually set a last price and check for settlement
    /// @param price lastPrice to be set
    function updateLastPrice(uint price) public {
        lastPrice = price;
        checkSettlement();
    }
}

/*
    Copyright 2017-2018 Phillip A. Elsasser

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

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

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

pragma solidity ^0.4.18;

import "./MarketContractOraclize.sol";

/// @title Testable version of MarketContractOraclize that exposes a function to manually update last price.
/// This is deployed to the test network in place of the actual MarketContractOraclize
/// @author Perfect Makanju <root@perfect.engineering>
contract TestableMarketContractOraclize is MarketContractOraclize {

    /// @param contractName viewable name of this contract (BTC/ETH, LTC/ETH, etc)
    /// @param marketTokenAddress address of our member token
    /// @param baseTokenAddress address of the ERC20 token that will be used for collateral and pricing
    /// @param contractSpecs array of unsigned integers including:
    /// floorPrice minimum tradeable price of this contract, contract enters settlement if breached
    /// capPrice maximum tradeable price of this contract, contract enters settlement if breached
    /// priceDecimalPlaces number of decimal places to convert our queried price from a floating point to
    /// an integer
    /// qtyMultiplier multiply traded qty by this value from base units of collateral token.
    /// expirationTimeStamp - seconds from epoch that this contract expires and enters settlement
    /// @param oracleDataSource a data-source such as "URL", "WolframAlpha", "IPFS"dv
    /// see http://docs.oraclize.it/#ethereum-quick-start-simple-query
    /// @param oracleQuery see http://docs.oraclize.it/#ethereum-quick-start-simple-query for examples
    /// @param oracleQueryRepeatSeconds how often to repeat this callback to check for settlement, more frequent
    /// queries require more gas and may not be needed.
    function TestableMarketContractOraclize(
        string contractName,
        address marketTokenAddress,
        address baseTokenAddress,
        uint[5] contractSpecs,
        string oracleDataSource,
        string oracleQuery,
        uint oracleQueryRepeatSeconds
    ) MarketContractOraclize(
        contractName,
        marketTokenAddress,
        baseTokenAddress,
        contractSpecs,
        oracleDataSource,
        oracleQuery,
        oracleQueryRepeatSeconds
    ) public payable { }

    /// @notice allows the creator of the contract to manually set a last price and check for settlement
    /// @param price lastPrice to be set
    function updateLastPrice(uint price) public {
        lastPrice = price;
        checkSettlement();
    }
}


get it compiling

get it compiling

// Grove v0.3
import "libraries/GroveLib.sol";

/// @title Grove - queryable indexes for ordered data.
/// @author Piper Merriam <pipermerriam@gmail.com>
contract Grove {
        /*
         *  Indexes for ordered data
         *
         *  Address: 0x8017f24a47c889b1ee80501ff84beb3c017edf0b
         */
        // Map index_id to index
        mapping (bytes32 => GroveLib.Index) index_lookup;

        // Map node_id to index_id.
        mapping (bytes32 => bytes32) node_to_index;

        /// @notice Computes the id for a Grove index which is sha3(owner, indexName)
        /// @param owner The address of the index owner.
        /// @param indexName The name of the index.
        function computeIndexId(address owner, bytes32 indexName) constant returns (bytes32) {
                return sha3(owner, indexName);
        }

        /// @notice Computes the id for a node in a given Grove index which is sha3(indexId, id)
        /// @param indexId The id for the index the node belongs to.
        /// @param id The unique identifier for the data this node represents.
        function computeNodeId(bytes32 indexId, bytes32 id) constant returns (bytes32) {
                return sha3(indexId, id);
        }

        /*
         *  Node getters
         */
        /// @notice Retrieves the id of the root node for this index.
        /// @param indexId The id of the index.
        function getIndexRoot(bytes32 indexId) constant returns (bytes32) {
            return index_lookup[indexId].root;
        }

        /// @dev Retrieve the index id for the node.
        /// @param nodeId The id for the node
        function getNodeIndexId(bytes32 nodeId) constant returns (bytes32) {
            return node_to_index[nodeId];
        }

        /// @dev Retrieve the value of the node.
        /// @param nodeId The id for the node
        function getNodeValue(bytes32 nodeId) constant returns (int) {
            return GroveLib.getNodeValue(index_lookup[node_to_index[nodeId]], nodeId);
        }

        /// @dev Retrieve the height of the node.
        /// @param nodeId The id for the node
        function getNodeHeight(bytes32 nodeId) constant returns (uint) {
            return GroveLib.getNodeHeight(index_lookup[node_to_index[nodeId]], nodeId);
        }

        /// @dev Retrieve the parent id of the node.
        /// @param nodeId The id for the node
        function getNodeParent(bytes32 nodeId) constant returns (bytes32) {
            return GroveLib.getNodeParent(index_lookup[node_to_index[nodeId]], nodeId);
        }

        /// @dev Retrieve the left child id of the node.
        /// @param nodeId The id for the node
        function getNodeLeftChild(bytes32 nodeId) constant returns (bytes32) {
            return GroveLib.getNodeLeftChild(index_lookup[node_to_index[nodeId]], nodeId);
        }

        /// @dev Retrieve the right child id of the node.
        /// @param nodeId The id for the node
        function getNodeRightChild(bytes32 nodeId) constant returns (bytes32) {
            return GroveLib.getNodeRightChild(index_lookup[node_to_index[nodeId]], nodeId);
        }

        /** @dev Retrieve the id of the node that comes immediately before this
         *  one.  Returns 0x0 if there is no previous node.
         */
        /// @param nodeId The id for the node
        function getPreviousNode(bytes32 nodeId) constant returns (bytes32) {
            return GroveLib.getPreviousNode(index_lookup[node_to_index[nodeId]], nodeId);
        }

        /** @dev Retrieve the id of the node that comes immediately after this
         *  one.  Returns 0x0 if there is no previous node.
         */
        /// @param nodeId The id for the node
        function getNextNode(bytes32 nodeId) constant returns (bytes32) {
            return GroveLib.getNextNode(index_lookup[node_to_index[nodeId]], nodeId);
        }

        /** @dev Update or Insert a data element represented by the unique
         *  identifier `id` into the index.
         */
        /// @param indexName The human readable name for the index that the node should be upserted into.
        /// @param id The unique identifier that the index node represents.
        /// @param value The number which represents this data elements total ordering.
        function insert(bytes32 indexName, bytes32 id, int value) public {
                bytes32 indexId = computeIndexId(msg.sender, indexName);
                var index = index_lookup[indexId];

                // Store the mapping from nodeId to the indexId
                node_to_index[computeNodeId(indexId, id)] = indexId;

                GroveLib.insert(index, id, value);
        }

        /// @dev Query whether a node exists within the specified index for the unique identifier.
        /// @param indexId The id for the index.
        /// @param id The unique identifier of the data element.
        function exists(bytes32 indexId, bytes32 id) constant returns (bool) {
            return GroveLib.exists(index_lookup[indexId], id);
        }

        /// @dev Remove the index node for the given unique identifier.
        /// @param indexName The name of the index.
        /// @param id The unique identifier of the data element.
        function remove(bytes32 indexName, bytes32 id) public {
            GroveLib.remove(index_lookup[computeIndexId(msg.sender, indexName)], id);
        }

        /** @dev Query the index for the edge-most node that satisfies the
         * given query.  For >, >=, and ==, this will be the left-most node
         * that satisfies the comparison.  For < and <= this will be the
         * right-most node that satisfies the comparison.
         */
        /// @param indexId The id of the index that should be queried
        /** @param operator One of '>', '>=', '<', '<=', '==' to specify what
         *  type of comparison operator should be used.
         */
        function query(bytes32 indexId, bytes2 operator, int value) public returns (bytes32) {
                return GroveLib.query(index_lookup[indexId], operator, value);
        }
}

// Grove v0.3

/// @title Grove - queryable indexes for ordered data.
/// @author Piper Merriam <pipermerriam@gmail.com>
contract Grove {
        /*
         *  Indexes for ordered data
         *
         *  Address: 0x8017f24a47c889b1ee80501ff84beb3c017edf0b
         */
        // Map index_id to index
        mapping (bytes32 => GroveLib.Index) index_lookup;

        // Map node_id to index_id.
        mapping (bytes32 => bytes32) node_to_index;

        /// @notice Computes the id for a Grove index which is sha3(owner, indexName)
        /// @param owner The address of the index owner.
        /// @param indexName The name of the index.
        function computeIndexId(address owner, bytes32 indexName) constant returns (bytes32) {
                return GroveLib.computeIndexId(owner, indexName);
        }

        /// @notice Computes the id for a node in a given Grove index which is sha3(indexId, id)
        /// @param indexId The id for the index the node belongs to.
        /// @param id The unique identifier for the data this node represents.
        function computeNodeId(bytes32 indexId, bytes32 id) constant returns (bytes32) {
                return GroveLib.computeNodeId(indexId, id);
        }

        /*
         *  Node getters
         */
        /// @notice Retrieves the name of an index.
        /// @param indexId The id of the index.
        function getIndexName(bytes32 indexId) constant returns (bytes32) {
            return index_lookup[indexId].name;
        }

        /// @notice Retrieves the id of the root node for this index.
        /// @param indexId The id of the index.
        function getIndexRoot(bytes32 indexId) constant returns (bytes32) {
            return index_lookup[indexId].root;
        }

        /// @dev Retrieve the unique identifier this node represents.
        /// @param nodeId The id for the node
        function getNodeId(bytes32 nodeId) constant returns (bytes32) {
            return GroveLib.getNodeId(index_lookup[node_to_index[nodeId]], nodeId);
        }

        /// @dev Retrieve the index id for the node.
        /// @param nodeId The id for the node
        function getNodeIndexId(bytes32 nodeId) constant returns (bytes32) {
            return GroveLib.getNodeIndexId(index_lookup[node_to_index[nodeId]], nodeId);
        }

        /// @dev Retrieve the value of the node.
        /// @param nodeId The id for the node
        function getNodeValue(bytes32 nodeId) constant returns (int) {
            return GroveLib.getNodeValue(index_lookup[node_to_index[nodeId]], nodeId);
        }

        /// @dev Retrieve the height of the node.
        /// @param nodeId The id for the node
        function getNodeHeight(bytes32 nodeId) constant returns (uint) {
            return GroveLib.getNodeHeight(index_lookup[node_to_index[nodeId]], nodeId);
        }

        /// @dev Retrieve the parent id of the node.
        /// @param nodeId The id for the node
        function getNodeParent(bytes32 nodeId) constant returns (bytes32) {
            return GroveLib.getNodeParent(index_lookup[node_to_index[nodeId]], nodeId);
        }

        /// @dev Retrieve the left child id of the node.
        /// @param nodeId The id for the node
        function getNodeLeftChild(bytes32 nodeId) constant returns (bytes32) {
            return GroveLib.getNodeLeftChild(index_lookup[node_to_index[nodeId]], nodeId);
        }

        /// @dev Retrieve the right child id of the node.
        /// @param nodeId The id for the node
        function getNodeRightChild(bytes32 nodeId) constant returns (bytes32) {
            return GroveLib.getNodeRightChild(index_lookup[node_to_index[nodeId]], nodeId);
        }

        /** @dev Retrieve the id of the node that comes immediately before this
         *  one.  Returns 0x0 if there is no previous node.
         */
        /// @param nodeId The id for the node
        function getPreviousNode(bytes32 nodeId) constant returns (bytes32) {
            return GroveLib.getPreviousNode(index_lookup[node_to_index[nodeId]], nodeId);
        }

        /** @dev Retrieve the id of the node that comes immediately after this
         *  one.  Returns 0x0 if there is no previous node.
         */
        /// @param nodeId The id for the node
        function getNextNode(bytes32 nodeId) constant returns (bytes32) {
            return GroveLib.getNextNode(index_lookup[node_to_index[nodeId]], nodeId);
        }

        /** @dev Update or Insert a data element represented by the unique
         *  identifier `id` into the index.
         */
        /// @param indexName The human readable name for the index that the node should be upserted into.
        /// @param id The unique identifier that the index node represents.
        /// @param value The number which represents this data elements total ordering.
        function insert(bytes32 indexName, bytes32 id, int value) public {
                bytes32 indexId = computeIndexId(msg.sender, indexName);
                var index = index_lookup[indexId];

                if (index.name != indexName) {
                        // If this is a new index, store it's name and id
                        index.name = indexName;
                        index.id = indexId;
                }

                // Store the mapping from nodeId to the indexId
                node_to_index[computeNodeId(indexId, id)] = indexId;

                GroveLib.insert(index, id, value);
        }

        /// @dev Query whether a node exists within the specified index for the unique identifier.
        /// @param indexId The id for the index.
        /// @param id The unique identifier of the data element.
        function exists(bytes32 indexId, bytes32 id) constant returns (bool) {
            return GroveLib.exists(index_lookup[indexId], id);
        }

        /// @dev Remove the index node for the given unique identifier.
        /// @param indexName The name of the index.
        /// @param id The unique identifier of the data element.
        function remove(bytes32 indexName, bytes32 id) public {
            GroveLib.remove(index_lookup[computeIndexId(msg.sender, indexName)], id);
        }

        /** @dev Query the index for the edge-most node that satisfies the
         * given query.  For >, >=, and ==, this will be the left-most node
         * that satisfies the comparison.  For < and <= this will be the
         * right-most node that satisfies the comparison.
         */
        /// @param indexId The id of the index that should be queried
        /** @param operator One of '>', '>=', '<', '<=', '==' to specify what
         *  type of comparison operator should be used.
         */
        function query(bytes32 indexId, bytes2 operator, int value) public returns (bytes32) {
                return GroveLib.query(index_lookup[indexId], operator, value);
        }
}