if msg.data[0] == 0:
    new_id = contract.storage[-1]
    # store [from, to, value, maxvalue, timeout] in contract storage
    contract.storage[new_id] = msg.sender
    contract.storage[new_id + 1] = msg.data[1]
    contract.storage[new_id + 2] = 0
    contract.storage[new_id + 3] = msg.value
    contract.storage[new_id + 4] = 2^254
    # increment next id
    contract.storage[-1] = new_id + 10
    # return id of this channel
    return(new_id)

# Increase payment on channel: [1, id, value, v, r, s]
elif msg.data[0] == 1:
    # Ecrecover native extension; will be a different address in testnet and live
    ecrecover = 0x46a8d0b21b1336d83b06829f568d7450df36883f
    # Message data parameters
    id = msg.data[1] % 2^160
    value = msg.data[2]
    # Determine sender from signature
    h = sha3([id, value], 2)
    sender = call(ecrecover, [h, msg.data[3], msg.data[4], msg.data[5]], 4)
    # Check sender matches and new value is greater than old
    if sender == contract.storage[id]:
        if value > contract.storage[id + 2] and value <= contract.storage[id + 3]:
            # Update channel, increasing value and setting timeout
            contract.storage[id + 2] = value
            contract.storage[id + 4] = block.number + 1000

# Cash out channel: [2, id]
elif msg.data[0] == 2:
    id = msg.data[1] % 2^160
    # Check if timeout has run out
    if block.number >= contract.storage[id + 3]:
        # Send funds
        send(contract.storage[id + 1], contract.storage[id + 2])
        # Send refund
        send(contract.storage[id], contract.storage[id + 3] - contract.storage[id + 2])
        # Clear storage
        contract.storage[id] = 0
        contract.storage[id + 1] = 0
        contract.storage[id + 2] = 0
        contract.storage[id + 3] = 0
        contract.storage[id + 4] = 0
