Add accessors for state variables.

Add accessors for state variables.

//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 public m_required;
    // pointer used to find a free slot in m_owners
    uint public m_numOwners;
    // list of owners
    uint[256] public m_owners;
    uint constant c_maxOwners = 250;
    // index on the list of owners to allow reverse lookup
    mapping(uint => uint) public m_ownerIndex;
    // the ongoing operations.
    mapping(bytes32 => PendingState) public m_pending;
    bytes32[] public 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 public m_spentToday;
    uint public m_dailyLimit;
    uint public 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) public 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;
}


Add create() methods to proxy contract.

Add create() methods to proxy contract.

pragma solidity ^0.4.24;

import "./item_store_interface.sol";
import "./item_store_ipfs_sha256.sol";

/**
 * @title ItemStoreIpfsSha256Proxy
 * @author Jonathan Brown <jbrown@mix-blockchain.org>
 * @dev Proxy contract for accessing a ItemStoreIpfsSha256 contract from a different address for testing purposes.
 */
contract ItemStoreIpfsSha256Proxy is ItemStoreInterface {

    ItemStoreIpfsSha256 itemStore;

    /**
     * @param _itemStore Real ItemStore contract to proxy to.
     */
    constructor (ItemStoreIpfsSha256 _itemStore) public {
        itemStore = _itemStore;
    }

    function getNewItemId(bytes32 nonce) public view returns (bytes32 itemId) {
        itemId = itemStore.getNewItemId(nonce);
    }

    function create(bytes32 flagsNonce, bytes32 ipfsHash) external returns (bytes32 itemId) {
        itemId = itemStore.create(flagsNonce, ipfsHash);
    }

    function createWithParent(bytes32 flagsNonce, bytes32 ipfsHash, bytes32 parentId) external returns (bytes32 itemId) {
        itemId = itemStore.createWithParent(flagsNonce, ipfsHash, parentId);
    }

    function createWithParents(bytes32 flagsNonce, bytes32 ipfsHash, bytes32[] parentIds) external returns (bytes32 itemId) {
        itemId = itemStore.createWithParents(flagsNonce, ipfsHash, parentIds);
    }

    function addForeignChild(bytes32 itemId, bytes32 child) external {
        itemStore.addForeignChild(itemId, child);
    }

    function createNewRevision(bytes32 itemId, bytes32 ipfsHash) external returns (uint revisionId) {
        revisionId = itemStore.createNewRevision(itemId, ipfsHash);
    }

    function updateLatestRevision(bytes32 itemId, bytes32 ipfsHash) external {
        itemStore.updateLatestRevision(itemId, ipfsHash);
    }

    function retractLatestRevision(bytes32 itemId) external {
        itemStore.retractLatestRevision(itemId);
    }

    function restart(bytes32 itemId, bytes32 ipfsHash) external {
        itemStore.restart(itemId, ipfsHash);
    }

    function retract(bytes32 itemId) external {
        itemStore.retract(itemId);
    }

    function transfer(bytes32 itemId, address recipient) external {
        itemStore.transfer(itemId, recipient);
    }

    function disown(bytes32 itemId) external {
        itemStore.disown(itemId);
    }

    function setEnforceRevisions(bytes32 itemId) external {
        itemStore.setEnforceRevisions(itemId);
    }

    function setNotRetractable(bytes32 itemId) external {
        itemStore.setNotRetractable(itemId);
    }

    function setNotTransferable(bytes32 itemId) external {
        itemStore.setNotTransferable(itemId);
    }

    function transferEnable(bytes32 itemId) external {
        itemStore.transferEnable(itemId);
    }

    function transferDisable(bytes32 itemId) external {
        itemStore.transferDisable(itemId);
    }

    function setNotUpdatable(bytes32 itemId) external {
        itemStore.setNotUpdatable(itemId);
    }

    function getAbiVersion() external view returns (uint) {
        return itemStore.getAbiVersion();
    }

    function getContractId() external view returns (bytes8) {
        return itemStore.getContractId();
    }

    function getInUse(bytes32 itemId) public view returns (bool) {
        return itemStore.getInUse(itemId);
    }

    function getUpdatable(bytes32 itemId) external view returns (bool) {
        return itemStore.getUpdatable(itemId);
    }

    function getEnforceRevisions(bytes32 itemId) external view returns (bool) {
        return itemStore.getEnforceRevisions(itemId);
    }

    function getRetractable(bytes32 itemId) external view returns (bool) {
        return itemStore.getRetractable(itemId);
    }

    function getTransferable(bytes32 itemId) external view returns (bool) {
        return itemStore.getTransferable(itemId);
    }

    function getOwner(bytes32 itemId) external view returns (address) {
        return itemStore.getOwner(itemId);
    }

    function getRevisionCount(bytes32 itemId) external view returns (uint) {
        return itemStore.getRevisionCount(itemId);
    }

    function getParentCount(bytes32 itemId) external view returns (uint) {
        return itemStore.getParentCount(itemId);
    }

    function getParentId(bytes32 itemId, uint i) external view returns (bytes32) {
        return itemStore.getParentId(itemId, i);
    }

    function getChildCount(bytes32 itemId) external view returns (uint) {
        return itemStore.getChildCount(itemId);
    }

    function getChildId(bytes32 itemId, uint i) external view returns (bytes32) {
        return itemStore.getChildId(itemId, i);
    }

}

pragma solidity ^0.4.24;

import "./item_store_interface.sol";
import "./item_store_ipfs_sha256.sol";

/**
 * @title ItemStoreIpfsSha256Proxy
 * @author Jonathan Brown <jbrown@mix-blockchain.org>
 * @dev Proxy contract for accessing a ItemStoreIpfsSha256 contract from a different address for testing purposes.
 */
contract ItemStoreIpfsSha256Proxy is ItemStoreInterface {

    ItemStoreIpfsSha256 itemStore;

    /**
     * @param _itemStore Real ItemStore contract to proxy to.
     */
    constructor (ItemStoreIpfsSha256 _itemStore) public {
        itemStore = _itemStore;
    }

    function getNewItemId(bytes32 nonce) public view returns (bytes32 itemId) {
        itemId = itemStore.getNewItemId(nonce);
    }

    function addForeignChild(bytes32 itemId, bytes32 child) external {
        itemStore.addForeignChild(itemId, child);
    }

    function createNewRevision(bytes32 itemId, bytes32 ipfsHash) external returns (uint revisionId) {
        revisionId = itemStore.createNewRevision(itemId, ipfsHash);
    }

    function updateLatestRevision(bytes32 itemId, bytes32 ipfsHash) external {
        itemStore.updateLatestRevision(itemId, ipfsHash);
    }

    function retractLatestRevision(bytes32 itemId) external {
        itemStore.retractLatestRevision(itemId);
    }

    function restart(bytes32 itemId, bytes32 ipfsHash) external {
        itemStore.restart(itemId, ipfsHash);
    }

    function retract(bytes32 itemId) external {
        itemStore.retract(itemId);
    }

    function transfer(bytes32 itemId, address recipient) external {
        itemStore.transfer(itemId, recipient);
    }

    function disown(bytes32 itemId) external {
        itemStore.disown(itemId);
    }

    function setEnforceRevisions(bytes32 itemId) external {
        itemStore.setEnforceRevisions(itemId);
    }

    function setNotRetractable(bytes32 itemId) external {
        itemStore.setNotRetractable(itemId);
    }

    function setNotTransferable(bytes32 itemId) external {
        itemStore.setNotTransferable(itemId);
    }

    function transferEnable(bytes32 itemId) external {
        itemStore.transferEnable(itemId);
    }

    function transferDisable(bytes32 itemId) external {
        itemStore.transferDisable(itemId);
    }

    function setNotUpdatable(bytes32 itemId) external {
        itemStore.setNotUpdatable(itemId);
    }

    function getAbiVersion() external view returns (uint) {
        return itemStore.getAbiVersion();
    }

    function getContractId() external view returns (bytes8) {
        return itemStore.getContractId();
    }

    function getInUse(bytes32 itemId) public view returns (bool) {
        return itemStore.getInUse(itemId);
    }

    function getUpdatable(bytes32 itemId) external view returns (bool) {
        return itemStore.getUpdatable(itemId);
    }

    function getEnforceRevisions(bytes32 itemId) external view returns (bool) {
        return itemStore.getEnforceRevisions(itemId);
    }

    function getRetractable(bytes32 itemId) external view returns (bool) {
        return itemStore.getRetractable(itemId);
    }

    function getTransferable(bytes32 itemId) external view returns (bool) {
        return itemStore.getTransferable(itemId);
    }

    function getOwner(bytes32 itemId) external view returns (address) {
        return itemStore.getOwner(itemId);
    }

    function getRevisionCount(bytes32 itemId) external view returns (uint) {
        return itemStore.getRevisionCount(itemId);
    }

    function getParentCount(bytes32 itemId) external view returns (uint) {
        return itemStore.getParentCount(itemId);
    }

    function getParentId(bytes32 itemId, uint i) external view returns (bytes32) {
        return itemStore.getParentId(itemId, i);
    }

    function getChildCount(bytes32 itemId) external view returns (uint) {
        return itemStore.getChildCount(itemId);
    }

    function getChildId(bytes32 itemId, uint i) external view returns (bytes32) {
        return itemStore.getChildId(itemId, i);
    }

}


stopped overwriting settleTimeout and renamed some variables to more explaining names

import "StandardToken.sol";

contract NettingChannelContract {
    uint public settleTimeout;
    address public assetAddress;
    uint public opened;
    uint public closed;
    uint public settled;
    address public closingAddress;
    StandardToken public assetToken;

    struct Lock
    {
        uint8 expiration;
        uint amount;
        bytes32 hashlock;
    }
    struct Participant
    {
        address addr; // 0
        uint deposit; // 1
        uint netted; // 2
        uint transferedAmount; // 3
        uint amount; // 4
        bytes merkleProof; // 5
        bytes32 hashlock; // 6
        bytes32 secret; // 7
        uint expiration; // 8
        address sender; // 9
        uint nonce; // 10
        address asset; // 11
        address recipient; // 12
        bytes32 locksroot; // 13
        Lock[] unlocked; //14
    }
    Participant[2] public participants; // We only have two participants at all times

    event ChannelOpened(address assetAdr, address participant1,
                        address participant2, uint deposit1, uint deposit2);
    event ChannelClosed(address closingAddress, uint blockNumber);
    event ChannelSettled(uint blockNumber);
    event ChannelSecretRevealed(bytes32 secret); //TODO

    /// @dev modifier ensuring that only a participant of the channel can call a function
    modifier inParticipants {
        if (msg.sender != participants[0].addr &&
            msg.sender != participants[1].addr) throw;
        _
    }

    /// @dev modifier ensuring that function can only be called if a channel
    /// is closed, but not yet settled.
    modifier notSettled {
        // if channel is already settled or hasn't been closed yet
        if (settled > 0 || closed == 0) throw;
        _
    }

    function NettingChannelContract(address assetAdr, address participant1, address participant2, uint timeout) {
        assetToken = StandardToken(assetAdr);
        assetAddress = assetAdr;
        participants[0].addr = participant1;
        participants[1].addr = participant2;
        if (settleTimeout < 30) settleTimeout = 30; else settleTimeout = timeout;
    }

    /// @notice atIndex(address) to get the index of an address (0 or 1)
    /// @dev get the index of an address
    /// @param addr (address) the address you want the index of
    function atIndex(address addr) private returns (uint index) {
        if (addr == participants[0].addr) return 0;
        if (addr == participants[1].addr) return 1;
        else throw;
    }

    /// @notice deposit(uint) to deposit amount to channel.
    /// @dev Deposit an amount to the channel. At least one of the participants
    /// must deposit before the channel is opened.
    /// @param amount (uint) the amount to be deposited to the address
    function deposit(uint256 amount) inParticipants {
        if (assetToken.balanceOf(msg.sender) <= amount) throw;
        bool success = assetToken.transferFrom(msg.sender, address(this), amount);
        if (success == true) participants[atIndex(msg.sender)].deposit += amount;
        if(isOpen() && opened == 0) open();
    }

    /// @notice isOpen() to check if a channel is open
    /// @dev Check if a channel is open and both parties have deposited to the channel
    /// @return open (bool) the status of the channel
    function isOpen() private returns (bool) {
        if (closed > 0) throw;
        if (participants[0].deposit > 0 || participants[1].deposit > 0) return true;
        else return false;
    }

    /// @notice open() to set the opened to be the current block and triggers
    /// the event ChannelOpened()
    /// @dev Sets the value of `opened` to be the value of the current block.
    /// param none
    /// returns none, but changes the value of `opened` and triggers the event ChannelOpened.
    function open() private {
        opened = block.number;
        // trigger event
        ChannelOpened(assetAddress, participants[0].addr,
                      participants[1].addr, participants[0].deposit, participants[1].deposit);
    }

    /// @notice partner() to get the partner or other participant of the channel
    /// @dev Get the other participating party of the channel
    /// @param ownAddress (address) address of the calling party
    /// @return partnerAddress (address) the partner of the calling party
    function partner(address ownAddress) private returns (address partnerAddress) {
        if (ownAddress == participants[0].addr) return participants[1].addr;
        else return participants[0].addr;
    }

    /// @notice addrAndDep() to get the addresses and deposits of the participants
    /// @dev get the addresses and deposits of the participants
    /// @return par1 (address) address of one of the participants
    /// @return par2 (address) address of the the other participant
    /// @return dep1 (uint) the deposit of the first participant
    /// @return dep2 (uint) the deposit of the second participant
    function addrAndDep() returns (address par1, uint dep1, address par2, uint dep2) {
        par1 = participants[0].addr;
        dep1 = participants[0].deposit;
        par2 = participants[1].addr;
        dep2 = participants[1].deposit;
    }

    /// @notice close(bytes) to close a channel between to parties
    /// @dev Close the channel between two parties
    /// @param firstEncoded (bytes) the last sent transfer of the msg.sender
    function closeSingleFunded(bytes firstEncoded) inParticipants {
        if (settled > 0) throw; // channel already settled
        if (closed > 0) throw; // close has already been called

        // check if sender of message is a participant
        if (getSender(firstEncoded) != participants[0].addr &&
            getSender(firstEncoded) != participants[1].addr) throw;

        uint partnerId = atIndex(partner(msg.sender));
        uint senderId = atIndex(msg.sender);

        decode(firstEncoded);

        // mark closed
        closed = block.number;
        closingAddress = msg.sender;

        uint amount1 = participants[senderId].transferedAmount;
        uint amount2 = participants[partnerId].transferedAmount;

        uint allowance = participants[senderId].deposit + participants[partnerId].deposit;
        uint difference;
        if(amount1 > amount2) {
            difference = amount1 - amount2;
        } else {
            difference = amount2 - amount1;
        }

        // TODO
        // if (difference > allowance) penalize();

        // trigger event
        ChannelClosed(closingAddress, closed);
    }

    /// @notice close(bytes, bytes) to close a channel between to parties
    /// @dev Close the channel between two parties
    /// @param firstEncoded (bytes) the last sent transfer of the msg.sender
    /// @param secondEncoded (bytes) the last sent transfer of the msg.sender
    function closeBiFunded(bytes firstEncoded, bytes secondEncoded) inParticipants {
        if (settled > 0) throw; // channel already settled
        if (closed > 0) throw; // close has already been called
        address firstSender = getSender(firstEncoded);
        address secondSender = getSender(secondEncoded);

        // Don't allow both transfers to be from the same sender
        if (firstSender == secondSender) throw;

        // check if the sender of either of the messages is a participant
        if (firstSender != participants[0].addr &&
            firstSender != participants[1].addr) throw;
        if (secondSender != participants[0].addr &&
            secondSender!= participants[1].addr) throw;

        uint partnerId = atIndex(partner(msg.sender));
        uint senderId = atIndex(msg.sender);

        decode(firstEncoded);
        decode(secondEncoded);

        // mark closed
        closed = block.number;
        closingAddress = msg.sender;

        uint amount1 = participants[senderId].transferedAmount;
        uint amount2 = participants[partnerId].transferedAmount;

        uint allowance = participants[senderId].deposit + participants[partnerId].deposit;
        uint difference;
        if(amount1 > amount2) {
            difference = amount1 - amount2;
        } else {
            difference = amount2 - amount1;
        }

        // TODO
        // if (difference > allowance) penalize();

        // trigger event
        ChannelClosed(closingAddress, closed);
    }

    /// @notice updateTransfer(bytes) to update last known transfer
    /// @dev Allow the partner to update the last known transfer
    /// @param message (bytes) the encoded transfer message
    function updateTransfer(bytes message) inParticipants notSettled {
        if (closed + settleTimeout > block.number) throw; //if locked time has expired throw
        if (msg.sender == closingAddress) throw; // don't allow closer to update
        if (closingAddress == getSender(message)) throw;

        decode(message);

        // TODO check if tampered and penalize
        // TODO check if outdated and penalize
    }

    /// @notice unlock(bytes, bytes, bytes32) to unlock a locked transfer
    /// @dev Unlock a locked transfer
    /// @param lockedEncoded (bytes) the lock
    /// @param merkleProof (bytes) the merkle proof
    /// @param secret (bytes32) the secret
    function unlock(bytes lockedEncoded, bytes merkleProof, bytes32 secret) inParticipants notSettled{
        var(expiration, amount, hashlock) = decodeLock(lockedEncoded);
        if (expiration > closed) throw;
        if (hashlock != sha3(secret)) throw;

        uint partnerId = atIndex(partner(msg.sender));
        uint senderId = atIndex(msg.sender);

        if (participants[partnerId].nonce == 0) throw;

        // merkle proof
        bytes32 h = sha3(lockedEncoded);
        for (uint i = 0; i < merkleProof.length; i += 64) {
            bytes32 left;
            left = bytesToBytes32(slice(merkleProof, i, i + 32), left);
            bytes32 right;
            right = bytesToBytes32(slice(merkleProof, i + 32, i + 64), right);
            if (h != left && h != right) throw;
            h = sha3(left, right);
        }

        if (participants[partnerId].locksroot != h) throw;

        ChannelSecretRevealed(secret);
        participants[partnerId].unlocked.push(Lock(expiration, amount, hashlock));
    }

    /// @notice settle() to settle the balance between the two parties
    /// @dev Settles the balances of the two parties fo the channel
    /// @return participants (Participant[]) the participants with netted balances
    function settle() inParticipants notSettled {
        if (closed + settleTimeout < block.number) throw; //timeout is not yet over

        // update the netted balance of both participants
        for (uint i = 0; i < 2; i++) { // Always exactly two participants
            participants[i].netted = getNetted(i);
        }

        // Update the netted balance from the locks
        for (uint j = 0; j < 2; j++) { // Always exactly two participants
            uint otherIdx;
            if (j == 0) otherIdx = 1; else otherIdx = 0;
            for (uint k = 0; k < participants[j].unlocked.length; k++) {
                participants[j].netted += participants[j].unlocked[k].amount;
                participants[otherIdx].netted -= participants[j].unlocked[k].amount;
            }
        }
        settled = block.number;
        payOut();
        // trigger event
        ChannelSettled(settled);
    }

    function payOut() private {
        uint totalNetted = participants[0].netted + participants[1].netted;
        uint totalDeposit = participants[0].deposit + participants[1].deposit;
        if (totalNetted > totalDeposit) throw;
        assetToken.transfer(participants[0].addr, participants[0].netted);
        assetToken.transfer(participants[1].addr, participants[1].netted);
    }

    function getNetted(uint i) private returns (uint netted) {
        uint other;
        if (i == 0) other = 1; else other = 0;
        uint ownDeposit = participants[i].deposit;
        uint otherTransferedAmount = participants[other].transferedAmount;
        uint ownTransferedAmount = participants[i].transferedAmount;
        netted = ownDeposit + otherTransferedAmount - ownTransferedAmount;
    }

    function decode(bytes message) private {
        address sender;
        // Secret
        if (decideCMD(message) == 4) {
            assignSecret(message);
        }
        // Direct Transfer
        if (decideCMD(message) == 5) {
            assignDirect(message);
        }
        // Locked Transfer
        if (decideCMD(message) == 6) {
            assignLocked(message);
        }
        // Mediated Transfer
        if (decideCMD(message) == 7) {
            sender = assignMediated1(message);
            assignMediated2(message, sender);
        }
        // Cancel Transfer
        if (decideCMD(message) == 8) {
            assignCancel(message);
        }
        /*else throw;*/
    }

    function decideCMD(bytes message) private returns (uint number) {
        number = uint(message[0]);
    }

    function assignSecret(bytes message) private {
        address sender = getSender(message);
        uint i = atIndex(sender);
        var(sec) = decodeSecret(message);
        participants[atIndex(msg.sender)].secret = sec;
        participants[i].sender = sender;
    }
    function assignDirect(bytes message) private {
        address sender = getSender(message);
        uint i = atIndex(sender);
        var(cmd, non, ass, rec, trn, loc, sec) = decodeTransfer(message);
        participants[i].nonce = non;
        participants[i].asset = ass;
        participants[i].recipient = rec;
        participants[i].transferedAmount = trn;
        participants[i].hashlock = loc;
        participants[i].secret = sec;
        participants[i].sender = sender;
    }
    function assignLocked(bytes message) private {
        address sender = getSender(message);
        uint i = atIndex(sender);
        var(non, exp, ass, rec, loc, trn, amo, has) = decodeLockedTransfer(message);
        participants[i].nonce = non;
        participants[i].expiration = exp;
        participants[i].asset = ass;
        participants[i].recipient = rec;
        participants[i].locksroot = loc;
        participants[i].transferedAmount = trn;
        participants[i].amount = amo;
        participants[i].hashlock = has;
        participants[i].sender = sender;
    }
    function assignMediated1(bytes message) private returns (address sender) {
        sender = getSender(message);
        uint i = atIndex(sender);
        var(non, exp, ass, rec, tar, ini, loc) = decodeMediatedTransfer1(message);
        participants[i].nonce = non;
        participants[i].expiration = exp;
        participants[i].asset = ass;
        participants[i].recipient = rec;
        participants[i].locksroot = loc;
    }
    function assignMediated2(bytes message, address sender) private {
        bytes32 lock;
        uint i = atIndex(sender);
        var(has, trn, amo, fee) = decodeMediatedTransfer2(message);
        participants[i].hashlock = has;
        participants[i].transferedAmount = trn;
        participants[i].amount = amo;
        participants[i].sender = sender;
    }
    function assignCancel(bytes message) private {
        address sender = getSender(message);
        uint i = atIndex(sender);
        var(non, exp, ass, rec, loc, trn, amo, has) = decodeCancelTransfer(message);
        participants[i].nonce = non;
        participants[i].expiration = exp;
        participants[i].asset = ass;
        participants[i].recipient = rec;
        participants[i].locksroot = loc;
        participants[i].transferedAmount = trn;
        participants[i].amount = amo;
        participants[i].hashlock = has;
        participants[i].sender = sender;
    }

    /* DECODERS */

    function decodeSecret(bytes m) returns (bytes32 secret) {
        if (m.length != 101) throw;
        secret = bytesToBytes32(slice(m, 4, 36), secret);
    }

    function decodeTransfer(bytes m)
        returns
        (bytes4 cmdIdPad,
        uint8 nonce,
        address asset,
        address recipient,
        uint transferedAmount,
        bytes32 optionalLocksroot,
        bytes32 optionalSecret)
    {
        if (m.length != 213) throw;
        cmdIdPad = bytesToBytes4(slice(m, 0, 4), cmdIdPad);
        nonce = bytesToIntEight(slice(m, 4, 12), nonce);
        uint160 ia;
        asset = bytesToAddress(slice(m, 12, 32), ia);
        uint160 ir;
        recipient = bytesToAddress(slice(m, 32, 52), ir);
        transferedAmount = bytesToInt(slice(m, 52, 84), transferedAmount);
        optionalLocksroot = bytesToBytes32(slice(m, 84, 116), optionalLocksroot);
        optionalSecret = bytesToBytes32(slice(m, 116, 148), optionalSecret);
    }

    function decodeLockedTransfer(bytes m)
        returns
        (uint8 nonce,
        uint8 expiration,
        address asset,
        address recipient,
        bytes32 locksroot,
        uint transferedAmount,
        uint amount,
        bytes32 hashlock)
    {
        if (m.length != 253) throw;
        nonce = bytesToIntEight(slice(m, 4, 12), nonce);
        expiration = bytesToIntEight(slice(m, 12, 20), expiration);
        uint160 ia;
        asset = bytesToAddress(slice(m, 20, 40), ia);
        uint160 ir;
        recipient = bytesToAddress(slice(m, 40, 60), ir);
        locksroot = bytesToBytes32(slice(m, 60, 92), locksroot);
        transferedAmount = bytesToInt(slice(m, 92, 124), transferedAmount);
        amount = bytesToInt(slice(m, 124, 156), amount);
        hashlock = bytesToBytes32(slice(m, 156, 188), hashlock);
    }

    function decodeMediatedTransfer1(bytes m)
        returns
        (uint8 nonce,
        uint8 expiration,
        address asset,
        address recipient,
        address target,
        address initiator,
        bytes32 locksroot)
    {
        if (m.length != 325) throw;
        nonce = bytesToIntEight(slice(m, 4, 12), nonce);
        expiration = bytesToIntEight(slice(m, 12, 20), expiration);
        uint160 ia;
        asset = bytesToAddress(slice(m, 20, 40), ia);
        uint160 ir;
        recipient = bytesToAddress(slice(m, 40, 60), ir);
        uint160 it;
        target = bytesToAddress(slice(m, 60, 80), it);
        uint160 ii;
        initiator = bytesToAddress(slice(m, 80, 100), ii);
        locksroot = bytesToBytes32(slice(m, 100, 132), locksroot);
    }

    function decodeMediatedTransfer2(bytes m)
        returns
        (bytes32 hashlock,
        uint transferedAmount,
        uint amount,
        uint fee)
    {
        if (m.length != 325) throw;
        hashlock = bytesToBytes32(slice(m, 132, 164), hashlock);
        transferedAmount = bytesToInt(slice(m, 164, 196), transferedAmount);
        amount = bytesToInt(slice(m, 196, 228), amount);
        fee = bytesToInt(slice(m, 228, 260), fee);
    }

    function decodeCancelTransfer(bytes m)
        returns
        (uint8 nonce,
        uint8 expiration,
        address asset,
        address recipient,
        bytes32 locksroot,
        uint transferedAmount,
        uint amount,
        bytes32 hashlock)
    {
        if (m.length != 253) throw;
        nonce = bytesToIntEight(slice(m, 4, 12), nonce);
        expiration = bytesToIntEight(slice(m, 12, 20), expiration);
        uint160 ia;
        asset = bytesToAddress(slice(m, 20, 40), ia);
        uint160 ir;
        recipient = bytesToAddress(slice(m, 40, 60), ir);
        locksroot = bytesToBytes32(slice(m, 60, 92), locksroot);
        transferedAmount = bytesToInt(slice(m, 92, 124), transferedAmount);
        amount = bytesToInt(slice(m, 124, 156), amount);
        hashlock = bytesToBytes32(slice(m, 156, 188), hashlock);
    }

    function decodeLock(bytes m)
        returns
        (uint8 expiration,
        uint amount,
        bytes32 hashlock)
    {
        if (m.length != 62) throw;
        expiration = bytesToIntEight(slice(m, 0, 8), expiration);
        amount = bytesToInt(slice(m, 8, 40), amount);
        hashlock = bytesToBytes32(slice(m, 40, 62), hashlock);
    }

    // Gets the sender of a last sent transfer
    function getSender(bytes message) returns (address sndr) {
        bytes memory mes;
        bytes memory sig;
        // Secret
        if (decideCMD(message) == 4) {
            mes = slice(message, 0, 36);
            sig = slice(message, 36, 101);
            sndr = ecRec(mes, sig);
        }
        // Direct Transfer
        if (decideCMD(message) == 5) {
            mes = slice(message, 0, 148);
            sig = slice(message, 148, 213);
            sndr = ecRec(mes, sig);
        }
        // Locked Transfer
        if (decideCMD(message) == 6) {
            mes = slice(message, 0, 188);
            sig = slice(message, 188, 253);
            sndr = ecRec(mes, sig);
        }
        // Mediated Transfer
        if (decideCMD(message) == 7) {
            mes = slice(message, 0, 260);
            sig = slice(message, 260, 325);
            sndr = ecRec(mes, sig);
        }
        // Cancel Transfer
        if (decideCMD(message) == 8) {
            mes = slice(message, 0, 188);
            sig = slice(message, 188, 253);
            sndr = ecRec(mes, sig);
        }
        /*else throw;*/
    }

    // Function for ECRecovery
    function ecRec(bytes message, bytes sig) private returns (address sndr) {
        bytes32 hash = sha3(message);
        var(r, s, v) = sigSplit(sig);
        sndr = ecrecover(hash, v, r, s);
    }

    /* HELPER FUNCTIONS */
    function sigSplit(bytes message) private returns (bytes32 r, bytes32 s, uint8 v) {
        if (message.length != 65) throw;

        // The signature format is a compact form of:
        //   {bytes32 r}{bytes32 s}{uint8 v}
        // Compact means, uint8 is not padded to 32 bytes.
        assembly {
            r := mload(add(message, 32))
            s := mload(add(message, 64))
            // Here we are loading the last 32 bytes, including 31 bytes
            // of 's'. There is no 'mload8' to do this.
            //
            // 'byte' is not working due to the Solidity parser, so lets
            // use the second best option, 'and'
            v := and(mload(add(message, 65)), 1)

        }
        // old geth sends a `v` value of [0,1], while the new, in line with the YP sends [27,28]
        if(v < 27) v += 27;
    }

    function slice(bytes a, uint start, uint end) private returns (bytes n) {
        if (a.length < end) throw;
        if (start < 0) throw;
        n = new bytes(end-start);
        for ( uint i = start; i < end; i ++) { //python style slice
            n[i-start] = a[i];
        }
    }

    function bytesToIntEight(bytes b, uint8 i) private returns (uint8 res) {
        assembly { i := mload(add(b, 0x8)) }
        res = i;
    }

    function bytesToInt(bytes b, uint i) private returns (uint res) {
        assembly { i := mload(add(b, 0x20)) }
        res = i;
    }

    function bytesToAddress(bytes b, uint160 i) private returns (address add) {
        assembly { i := mload(add(b, 0x14)) }
        uint160 a = uint160(i);
        add = address(i);
    }

    function bytesToBytes4(bytes b, bytes4 i) private returns (bytes4 bts) {
        assembly { i := mload(add(b, 0x20)) }
        bts = i;
    }

    function bytesToBytes32(bytes b, bytes32 i) private returns (bytes32 bts) {
        assembly { i := mload(add(b, 0x20)) }
        bts = i;
    }

    // empty function to handle wrong calls
    function () { throw; }
}

import "StandardToken.sol";

contract NettingChannelContract {
    uint public settleTimeout;
    address public assetAddress;
    uint public opened;
    uint public closed;
    uint public settled;
    address public closingAddress;
    StandardToken public assetToken;

    struct Lock
    {
        uint8 expiration;
        uint amount;
        bytes32 hashlock;
    }
    struct Participant
    {
        address addr; // 0
        uint deposit; // 1
        uint netted; // 2
        uint transferedAmount; // 3
        uint amount; // 4
        bytes merkleProof; // 5
        bytes32 hashlock; // 6
        bytes32 secret; // 7
        uint expiration; // 8
        address sender; // 9
        uint nonce; // 10
        address asset; // 11
        address recipient; // 12
        bytes32 locksroot; // 13
        Lock[] unlocked; //14
    }
    Participant[2] public participants; // We only have two participants at all times

    event ChannelOpened(address assetAdr, address participant1,
                        address participant2, uint deposit1, uint deposit2);
    event ChannelClosed(address closingAddress, uint blockNumber);
    event ChannelSettled(uint blockNumber);
    event ChannelSecretRevealed(bytes32 secret); //TODO

    /// @dev modifier ensuring that only a participant of the channel can call a function
    modifier inParticipants {
        if (msg.sender != participants[0].addr &&
            msg.sender != participants[1].addr) throw;
        _
    }

    /// @dev modifier ensuring that function can only be called if a channel
    /// is closed, but not yet settled.
    modifier notSettled {
        // if channel is already settled or hasn't been closed yet
        if (settled > 0 || closed == 0) throw;
        _
    }

    function NettingChannelContract(address assetAdr, address participant1, address participant2, uint timeout) {
        assetToken = StandardToken(assetAdr);
        assetAddress = assetAdr;
        participants[0].addr = participant1;
        participants[1].addr = participant2;
        if (settleTimeout < 30) settleTimeout = 30; else settleTimeout = timeout;
    }

    /// @notice atIndex(address) to get the index of an address (0 or 1)
    /// @dev get the index of an address
    /// @param addr (address) the address you want the index of
    function atIndex(address addr) private returns (uint index) {
        if (addr == participants[0].addr) return 0;
        if (addr == participants[1].addr) return 1;
        else throw;
    }

    /// @notice deposit(uint) to deposit amount to channel.
    /// @dev Deposit an amount to the channel. At least one of the participants
    /// must deposit before the channel is opened.
    /// @param amount (uint) the amount to be deposited to the address
    function deposit(uint256 amount) inParticipants {
        if (assetToken.balanceOf(msg.sender) <= amount) throw;
        bool s = assetToken.transferFrom(msg.sender, address(this), amount);
        if (s == true) participants[atIndex(msg.sender)].deposit += amount;
        if(isOpen() && opened == 0) open();
    }

    /// @notice isOpen() to check if a channel is open
    /// @dev Check if a channel is open and both parties have deposited to the channel
    /// @return open (bool) the status of the channel
    function isOpen() private returns (bool) {
        if (closed > 0) throw;
        if (participants[0].deposit > 0 || participants[1].deposit > 0) return true;
        else return false;
    }

    /// @notice open() to set the opened to be the current block and triggers
    /// the event ChannelOpened()
    /// @dev Sets the value of `opened` to be the value of the current block.
    /// param none
    /// returns none, but changes the value of `opened` and triggers the event ChannelOpened.
    function open() private {
        opened = block.number;
        // trigger event
        ChannelOpened(assetAddress, participants[0].addr,
                      participants[1].addr, participants[0].deposit, participants[1].deposit);
    }

    /// @notice partner() to get the partner or other participant of the channel
    /// @dev Get the other participating party of the channel
    /// @return p (address) the partner of the calling party
    function partner(address a) private returns (address p) {
        if (a == participants[0].addr) return participants[1].addr;
        else return participants[0].addr;
    }

    /// @notice addrAndDep() to get the addresses and deposits of the participants
    /// @dev get the addresses and deposits of the participants
    /// @return par1 (address) address of one of the participants
    /// @return par2 (address) address of the the other participant
    /// @return dep1 (uint) the deposit of the first participant
    /// @return dep2 (uint) the deposit of the second participant
    function addrAndDep() returns (address par1, uint dep1, address par2, uint dep2) {
        par1 = participants[0].addr;
        dep1 = participants[0].deposit;
        par2 = participants[1].addr;
        dep2 = participants[1].deposit;
    }

    /// @notice close(bytes) to close a channel between to parties
    /// @dev Close the channel between two parties
    /// @param firstEncoded (bytes) the last sent transfer of the msg.sender
    function closeSingleFunded(bytes firstEncoded) inParticipants {
        if (settled > 0) throw; // channel already settled
        if (closed > 0) throw; // close has already been called

        // check if sender of message is a participant
        if (getSender(firstEncoded) != participants[0].addr &&
            getSender(firstEncoded) != participants[1].addr) throw;

        uint partnerId = atIndex(partner(msg.sender));
        uint senderId = atIndex(msg.sender);

        decode(firstEncoded);

        // mark closed
        closed = block.number;
        closingAddress = msg.sender;

        uint amount1 = participants[senderId].transferedAmount;
        uint amount2 = participants[partnerId].transferedAmount;

        uint allowance = participants[senderId].deposit + participants[partnerId].deposit;
        uint difference;
        if(amount1 > amount2) {
            difference = amount1 - amount2;
        } else {
            difference = amount2 - amount1;
        }

        // TODO
        // if (difference > allowance) penalize();

        // trigger event
        ChannelClosed(closingAddress, closed);
    }

    /// @notice close(bytes, bytes) to close a channel between to parties
    /// @dev Close the channel between two parties
    /// @param firstEncoded (bytes) the last sent transfer of the msg.sender
    /// @param secondEncoded (bytes) the last sent transfer of the msg.sender
    function closeBiFunded(bytes firstEncoded, bytes secondEncoded) inParticipants {
        if (settled > 0) throw; // channel already settled
        if (closed > 0) throw; // close has already been called
        address firstSender = getSender(firstEncoded);
        address secondSender = getSender(secondEncoded);

        // Don't allow both transfers to be from the same sender
        if (firstSender == secondSender) throw;

        // check if the sender of either of the messages is a participant
        if (firstSender != participants[0].addr &&
            firstSender != participants[1].addr) throw;
        if (secondSender != participants[0].addr &&
            secondSender!= participants[1].addr) throw;

        uint partnerId = atIndex(partner(msg.sender));
        uint senderId = atIndex(msg.sender);

        decode(firstEncoded);
        decode(secondEncoded);

        // mark closed
        closed = block.number;
        closingAddress = msg.sender;

        uint amount1 = participants[senderId].transferedAmount;
        uint amount2 = participants[partnerId].transferedAmount;

        uint allowance = participants[senderId].deposit + participants[partnerId].deposit;
        uint difference;
        if(amount1 > amount2) {
            difference = amount1 - amount2;
        } else {
            difference = amount2 - amount1;
        }

        // TODO
        // if (difference > allowance) penalize();

        // trigger event
        ChannelClosed(closingAddress, closed);
    }

    /// @notice updateTransfer(bytes) to update last known transfer
    /// @dev Allow the partner to update the last known transfer
    /// @param message (bytes) the encoded transfer message
    function updateTransfer(bytes message) inParticipants notSettled {
        if (closed + settleTimeout > block.number) throw; //if locked time has expired throw
        if (msg.sender == closingAddress) throw; // don't allow closer to update
        if (closingAddress == getSender(message)) throw;

        decode(message);

        // TODO check if tampered and penalize
        // TODO check if outdated and penalize
    }

    /// @notice unlock(bytes, bytes, bytes32) to unlock a locked transfer
    /// @dev Unlock a locked transfer
    /// @param lockedEncoded (bytes) the lock
    /// @param merkleProof (bytes) the merkle proof
    /// @param secret (bytes32) the secret
    function unlock(bytes lockedEncoded, bytes merkleProof, bytes32 secret) inParticipants notSettled{
        var(expiration, amount, hashlock) = decodeLock(lockedEncoded);
        if (expiration > closed) throw;
        if (hashlock != sha3(secret)) throw;

        uint partnerId = atIndex(partner(msg.sender));
        uint senderId = atIndex(msg.sender);

        if (participants[partnerId].nonce == 0) throw;

        // merkle proof
        bytes32 h = sha3(lockedEncoded);
        for (uint i = 0; i < merkleProof.length; i += 64) {
            bytes32 left;
            left = bytesToBytes32(slice(merkleProof, i, i + 32), left);
            bytes32 right;
            right = bytesToBytes32(slice(merkleProof, i + 32, i + 64), right);
            if (h != left && h != right) throw;
            h = sha3(left, right);
        }

        if (participants[partnerId].locksroot != h) throw;

        ChannelSecretRevealed(secret);
        participants[partnerId].unlocked.push(Lock(expiration, amount, hashlock));
    }

    /// @notice settle() to settle the balance between the two parties
    /// @dev Settles the balances of the two parties fo the channel
    /// @return participants (Participant[]) the participants with netted balances
    function settle() inParticipants notSettled {
        if (closed + settleTimeout < block.number) throw; //timeout is not yet over

        // update the netted balance of both participants
        for (uint i = 0; i < 2; i++) { // Always exactly two participants
            participants[i].netted = getNetted(i);
        }

        // Update the netted balance from the locks
        for (uint j = 0; j < 2; j++) { // Always exactly two participants
            uint otherIdx;
            if (j == 0) otherIdx = 1; else otherIdx = 0;
            for (uint k = 0; k < participants[j].unlocked.length; k++) {
                participants[j].netted += participants[j].unlocked[k].amount;
                participants[otherIdx].netted -= participants[j].unlocked[k].amount;
            }
        }
        settled = block.number;
        payOut();
        // trigger event
        ChannelSettled(settled);
    }

    function payOut() private {
        uint totalNetted = participants[0].netted + participants[1].netted;
        uint totalDeposit = participants[0].deposit + participants[1].deposit;
        if (totalNetted > totalDeposit) throw;
        assetToken.transfer(participants[0].addr, participants[0].netted);
        assetToken.transfer(participants[1].addr, participants[1].netted);
    }

    function getNetted(uint i) private returns (uint netted) {
        uint other;
        if (i == 0) other = 1; else other = 0;
        uint ownDeposit = participants[i].deposit;
        uint otherTransferedAmount = participants[other].transferedAmount;
        uint ownTransferedAmount = participants[i].transferedAmount;
        netted = ownDeposit + otherTransferedAmount - ownTransferedAmount;
    }

    function decode(bytes message) private {
        address sender;
        // Secret
        if (decideCMD(message) == 4) {
            assignSecret(message);
        }
        // Direct Transfer
        if (decideCMD(message) == 5) {
            assignDirect(message);
        }
        // Locked Transfer
        if (decideCMD(message) == 6) {
            assignLocked(message);
        }
        // Mediated Transfer
        if (decideCMD(message) == 7) {
            sender = assignMediated1(message);
            assignMediated2(message, sender);
        }
        // Cancel Transfer
        if (decideCMD(message) == 8) {
            assignCancel(message);
        }
        /*else throw;*/
    }

    function decideCMD(bytes message) private returns (uint number) {
        number = uint(message[0]);
    }

    function assignSecret(bytes message) private {
        address sender = getSender(message);
        uint i = atIndex(sender);
        var(sec) = decodeSecret(message);
        participants[atIndex(msg.sender)].secret = sec;
        participants[i].sender = sender;
    }
    function assignDirect(bytes message) private {
        address sender = getSender(message);
        uint i = atIndex(sender);
        var(cmd, non, ass, rec, trn, loc, sec) = decodeTransfer(message);
        participants[i].nonce = non;
        participants[i].asset = ass;
        participants[i].recipient = rec;
        participants[i].transferedAmount = trn;
        participants[i].hashlock = loc;
        participants[i].secret = sec;
        participants[i].sender = sender;
    }
    function assignLocked(bytes message) private {
        address sender = getSender(message);
        uint i = atIndex(sender);
        var(non, exp, ass, rec, loc, trn, amo, has) = decodeLockedTransfer(message);
        participants[i].nonce = non;
        settleTimeout = exp;
        participants[i].asset = ass;
        participants[i].recipient = rec;
        participants[i].locksroot = loc;
        participants[i].transferedAmount = trn;
        participants[i].amount = amo;
        participants[i].hashlock = has;
        participants[i].sender = sender;
    }
    function assignMediated1(bytes message) private returns (address sender) {
        sender = getSender(message);
        uint i = atIndex(sender);
        var(non, exp, ass, rec, tar, ini, loc) = decodeMediatedTransfer1(message);
        participants[i].nonce = non;
        settleTimeout = exp;
        participants[i].asset = ass;
        participants[i].recipient = rec;
        participants[i].locksroot = loc;
    }
    function assignMediated2(bytes message, address sender) private {
        bytes32 lock;
        uint i = atIndex(sender);
        var(has, trn, amo, fee) = decodeMediatedTransfer2(message);
        participants[i].hashlock = has;
        participants[i].transferedAmount = trn;
        participants[i].amount = amo;
        participants[i].sender = sender;
    }
    function assignCancel(bytes message) private {
        address sender = getSender(message);
        uint i = atIndex(sender);
        var(non, exp, ass, rec, loc, trn, amo, has) = decodeCancelTransfer(message);
        participants[i].nonce = non;
        settleTimeout = exp;
        participants[i].asset = ass;
        participants[i].recipient = rec;
        participants[i].locksroot = loc;
        participants[i].transferedAmount = trn;
        participants[i].transferedAmount = amo;
        participants[i].hashlock = has;
        participants[i].sender = sender;
    }

    /* DECODERS */

    function decodeSecret(bytes m) returns (bytes32 secret) {
        if (m.length != 101) throw;
        secret = bytesToBytes32(slice(m, 4, 36), secret);
    }

    function decodeTransfer(bytes m)
        returns
        (bytes4 cmdIdPad,
        uint8 nonce,
        address asset,
        address recipient,
        uint transferedAmount,
        bytes32 optionalLocksroot,
        bytes32 optionalSecret)
    {
        if (m.length != 213) throw;
        cmdIdPad = bytesToBytes4(slice(m, 0, 4), cmdIdPad);
        nonce = bytesToIntEight(slice(m, 4, 12), nonce);
        uint160 ia;
        asset = bytesToAddress(slice(m, 12, 32), ia);
        uint160 ir;
        recipient = bytesToAddress(slice(m, 32, 52), ir);
        transferedAmount = bytesToInt(slice(m, 52, 84), transferedAmount);
        optionalLocksroot = bytesToBytes32(slice(m, 84, 116), optionalLocksroot);
        optionalSecret = bytesToBytes32(slice(m, 116, 148), optionalSecret);
    }

    function decodeLockedTransfer(bytes m)
        returns
        (uint8 nonce,
        uint8 expiration,
        address asset,
        address recipient,
        bytes32 locksroot,
        uint transferedAmount,
        uint amount,
        bytes32 hashlock)
    {
        if (m.length != 253) throw;
        nonce = bytesToIntEight(slice(m, 4, 12), nonce);
        expiration = bytesToIntEight(slice(m, 12, 20), expiration);
        uint160 ia;
        asset = bytesToAddress(slice(m, 20, 40), ia);
        uint160 ir;
        recipient = bytesToAddress(slice(m, 40, 60), ir);
        locksroot = bytesToBytes32(slice(m, 60, 92), locksroot);
        transferedAmount = bytesToInt(slice(m, 92, 124), transferedAmount);
        amount = bytesToInt(slice(m, 124, 156), amount);
        hashlock = bytesToBytes32(slice(m, 156, 188), hashlock);
    }

    function decodeMediatedTransfer1(bytes m)
        returns
        (uint8 nonce,
        uint8 expiration,
        address asset,
        address recipient,
        address target,
        address initiator,
        bytes32 locksroot)
    {
        if (m.length != 325) throw;
        nonce = bytesToIntEight(slice(m, 4, 12), nonce);
        expiration = bytesToIntEight(slice(m, 12, 20), expiration);
        uint160 ia;
        asset = bytesToAddress(slice(m, 20, 40), ia);
        uint160 ir;
        recipient = bytesToAddress(slice(m, 40, 60), ir);
        uint160 it;
        target = bytesToAddress(slice(m, 60, 80), it);
        uint160 ii;
        initiator = bytesToAddress(slice(m, 80, 100), ii);
        locksroot = bytesToBytes32(slice(m, 100, 132), locksroot);
    }

    function decodeMediatedTransfer2(bytes m)
        returns
        (bytes32 hashlock,
        uint transferedAmount,
        uint amount,
        uint fee)
    {
        if (m.length != 325) throw;
        hashlock = bytesToBytes32(slice(m, 132, 164), hashlock);
        transferedAmount = bytesToInt(slice(m, 164, 196), transferedAmount);
        amount = bytesToInt(slice(m, 196, 228), amount);
        fee = bytesToInt(slice(m, 228, 260), fee);
    }

    function decodeCancelTransfer(bytes m)
        returns
        (uint8 nonce,
        uint8 expiration,
        address asset,
        address recipient,
        bytes32 locksroot,
        uint transferedAmount,
        uint amount,
        bytes32 hashlock)
    {
        if (m.length != 253) throw;
        nonce = bytesToIntEight(slice(m, 4, 12), nonce);
        expiration = bytesToIntEight(slice(m, 12, 20), expiration);
        uint160 ia;
        asset = bytesToAddress(slice(m, 20, 40), ia);
        uint160 ir;
        recipient = bytesToAddress(slice(m, 40, 60), ir);
        locksroot = bytesToBytes32(slice(m, 60, 92), locksroot);
        transferedAmount = bytesToInt(slice(m, 92, 124), transferedAmount);
        amount = bytesToInt(slice(m, 124, 156), amount);
        hashlock = bytesToBytes32(slice(m, 156, 188), hashlock);
    }

    function decodeLock(bytes m)
        returns
        (uint8 expiration,
        uint amount,
        bytes32 hashlock)
    {
        if (m.length != 62) throw;
        expiration = bytesToIntEight(slice(m, 0, 8), expiration);
        amount = bytesToInt(slice(m, 8, 40), amount);
        hashlock = bytesToBytes32(slice(m, 40, 62), hashlock);
    }

    // Gets the sender of a last sent transfer
    function getSender(bytes message) returns (address sndr) {
        bytes memory mes;
        bytes memory sig;
        // Secret
        if (decideCMD(message) == 4) {
            mes = slice(message, 0, 36);
            sig = slice(message, 36, 101);
            sndr = ecRec(mes, sig);
        }
        // Direct Transfer
        if (decideCMD(message) == 5) {
            mes = slice(message, 0, 148);
            sig = slice(message, 148, 213);
            sndr = ecRec(mes, sig);
        }
        // Locked Transfer
        if (decideCMD(message) == 6) {
            mes = slice(message, 0, 188);
            sig = slice(message, 188, 253);
            sndr = ecRec(mes, sig);
        }
        // Mediated Transfer
        if (decideCMD(message) == 7) {
            mes = slice(message, 0, 260);
            sig = slice(message, 260, 325);
            sndr = ecRec(mes, sig);
        }
        // Cancel Transfer
        if (decideCMD(message) == 8) {
            mes = slice(message, 0, 188);
            sig = slice(message, 188, 253);
            sndr = ecRec(mes, sig);
        }
        /*else throw;*/
    }

    // Function for ECRecovery
    function ecRec(bytes message, bytes sig) private returns (address sndr) {
        bytes32 hash = sha3(message);
        var(r, s, v) = sigSplit(sig);
        sndr = ecrecover(hash, v, r, s);
    }

    /* HELPER FUNCTIONS */
    function sigSplit(bytes message) private returns (bytes32 r, bytes32 s, uint8 v) {
        if (message.length != 65) throw;

        // The signature format is a compact form of:
        //   {bytes32 r}{bytes32 s}{uint8 v}
        // Compact means, uint8 is not padded to 32 bytes.
        assembly {
            r := mload(add(message, 32))
            s := mload(add(message, 64))
            // Here we are loading the last 32 bytes, including 31 bytes
            // of 's'. There is no 'mload8' to do this.
            //
            // 'byte' is not working due to the Solidity parser, so lets
            // use the second best option, 'and'
            v := and(mload(add(message, 65)), 1)

        }
        // old geth sends a `v` value of [0,1], while the new, in line with the YP sends [27,28]
        if(v < 27) v += 27;
    }

    function slice(bytes a, uint start, uint end) private returns (bytes n) {
        if (a.length < end) throw;
        if (start < 0) throw;
        n = new bytes(end-start);
        for ( uint i = start; i < end; i ++) { //python style slice
            n[i-start] = a[i];
        }
    }

    function bytesToIntEight(bytes b, uint8 i) private returns (uint8 res) {
        assembly { i := mload(add(b, 0x8)) }
        res = i;
    }

    function bytesToInt(bytes b, uint i) private returns (uint res) {
        assembly { i := mload(add(b, 0x20)) }
        res = i;
    }

    function bytesToAddress(bytes b, uint160 i) private returns (address add) {
        assembly { i := mload(add(b, 0x14)) }
        uint160 a = uint160(i);
        add = address(i);
    }

    function bytesToBytes4(bytes b, bytes4 i) private returns (bytes4 bts) {
        assembly { i := mload(add(b, 0x20)) }
        bts = i;
    }

    function bytesToBytes32(bytes b, bytes32 i) private returns (bytes32 bts) {
        assembly { i := mload(add(b, 0x20)) }
        bts = i;
    }

    // empty function to handle wrong calls
    function () { throw; }
}


Let nonce be equal if signators required is 0

0 signators indicates that it is being sent by Rules contract so it's
allowed to do whatever it wants

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 timeout
    function getTimeout() constant external returns (uint timeout) {}
    // Gets the current nonce
    function getNonce() constant external returns (uint nonce) {}

    // Gets the last timestamp
    function getLastTimestamp() constant external returns (uint lastTimestamp) {}

    /**
     * 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.
	 *
	 * If requiredSignators is 0, the nonce can be equal to the old nonce because,
	 * in this case, we are assuming that Rules is making a ruling on something and, thus,
	 * it updates the state without updating the nonce.
     *
     * 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 || (newNonce == nonce && requiredSignators == 0)) {
            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;
        } else {
            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) {}

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

    // Gets the last timestamp
    function getLastTimestamp() constant external returns (uint lastTimestamp) {}

    /**
     * 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 return true to makeAssessmentFrom

add return true to makeAssessmentFrom