commented out debugging stuff from initialize method

pragma solidity ^0.4.16;

interface JudgeInterface {
    function judge(bytes32[13] res, uint q,
                        bytes32[] _proof, bytes32[] _proof2,
                        bytes32 vm_, bytes32 op, uint[4] regs,
                        bytes32[10] roots, uint[4] pointers) external returns (uint);
    function judgeCustom(bytes32 state1, bytes32 state2, bytes32 ex_state, uint ex_reg, bytes32 op, uint[4] regs, bytes32[10] roots, uint[4] pointers, bytes32[] proof) external;

    function checkFileProof(bytes32 state, bytes32[10] roots, uint[4] pointers, bytes32[] proof, uint loc) external returns (bool);
    function checkProof(bytes32 hash, bytes32 root, bytes32[] proof, uint loc) external returns (bool);

    function calcStateHash(bytes32[10] roots, uint[4] pointers) external returns (bytes32);
    function calcIOHash(bytes32[10] roots) external returns (bytes32);
}

interface CustomJudge {
    // Initializes a new custom verification game
    function init(bytes32 state, uint state_size, uint r3, address solver, address verifier) external returns (bytes32);

    // Last time the task was updated
    function clock(bytes32 id) external returns (uint);

    // Check if has resolved into correct state: merkle root of output data and output size
    function resolved(bytes32 id, bytes32 state, uint size) external returns (bool);
}

contract Interactive {

    constructor(address addr) public {
        judge = JudgeInterface(addr);
    }

    JudgeInterface judge;

    mapping (uint => uint) blocked;
    mapping (uint => bool) rejected;

    enum State {
        Started,
        Running, // First and last state have been set up ... but this will mean that the verification game is running now
        Finished, // Winner has been chosen
        NeedPhases,
        PostedPhases,
        SelectedPhase,

        // Special states for custom judges
        Custom
    }

    struct Record {
        uint256 task_id;

        address prover;
        address challenger;

        bytes32 start_state; // actually initial code + input
        bytes32 end_state; // actually output

        // Maybe number of steps should be finished
        uint256 steps;

        address winner;
        address next;

        address manager;

        uint256 size;
        uint256 timeout;
        uint256 clock;

        uint256 idx1;
        uint256 idx2;

        uint256 phase;

        bytes32[] proof;
        bytes32[13] result;

        State state;

        //
        CustomJudge judge;
        bytes32 sub_task;
        bytes32 ex_state; // result from the custom judge
        uint ex_size;
    }

    mapping (bytes32 => Record) records;
    mapping (uint64 => CustomJudge) judges;

    // who should be able to
    function registerJudge(uint64 id, address addr) public {
        judges[id] = CustomJudge(addr);
    }

    event StartChallenge(address p, address c, bytes32 s, bytes32 e, uint256 par, uint to, bytes32 uniq);

    uint nonce;

    function make(uint task_id, address p, address c, bytes32 s, bytes32 e, uint256 par, uint to) public returns (bytes32) {
        bytes32 uniq = keccak256(task_id, p, c, s, e, par, to, nonce++);
        Record storage r = records[uniq];
        r.task_id = task_id;
        r.prover = p;
        r.challenger = c;
        r.start_state = s;
        r.end_state = e;
        r.timeout = to;
        r.clock = block.number;
        r.next = r.prover;
        r.idx1 = 0;
        r.phase = 16;
        r.size = par;
        r.state = State.Started;
        r.manager = msg.sender;
        emit StartChallenge(p, c, s, e, r.size, to, uniq);
        blocked[task_id] = r.clock + r.timeout;
        return uniq;
    }

    uint constant FINAL_STATE = 0xffffffffff;

    function initialize(bytes32 id, bytes32[10] s_roots, uint[4] s_pointers, uint _steps,
                                    bytes32[10] e_roots, uint[4] e_pointers) public returns (bool) {
        Record storage r = records[id];
        require(msg.sender == r.next && r.state == State.Started);
        // check first state here
        // if (r.start_state != judge.calcIOHash(s_roots)) return false;
        require (r.start_state == judge.calcIOHash(s_roots));
        // then last one
        // if (r.end_state != judge.calcIOHash(e_roots)) return false;
        require (r.end_state == judge.calcIOHash(e_roots));

        // need to check that the start state is empty
        // stack
        require(s_roots[1] == 0xb4c11951957c6f8f642c4af61cd6b24640fec6dc7fc607ee8206a99e92410d30);
        // memory
        require(s_roots[2] == 0xb4c11951957c6f8f642c4af61cd6b24640fec6dc7fc607ee8206a99e92410d30);
        // call stack
        require(s_roots[3] == 0xb4c11951957c6f8f642c4af61cd6b24640fec6dc7fc607ee8206a99e92410d30);
        // globals
        require(s_roots[4] == 0xb4c11951957c6f8f642c4af61cd6b24640fec6dc7fc607ee8206a99e92410d30);
        // call table (check if resizing works)
        require(s_roots[5] == 0x7bf9aa8e0ce11d87877e8b7a304e8e7105531771dbff77d1b00366ecb1549624);
        //require(s_roots[5] == 0xc024f071f70ef04cc1aaa7cb371bd1c4f7df06b0edb57b81adbcc9cdb1dfc910);
        // call types
        require(s_roots[6] == 0xb4c11951957c6f8f642c4af61cd6b24640fec6dc7fc607ee8206a99e92410d30);
        // pointers
        require(s_pointers[0] == 0 && s_pointers[1] == 0 && s_pointers[2] == 0 && s_pointers[3] == 0);

        // check final state
        require(e_pointers[0] == FINAL_STATE);

        // Now we can initialize
        r.steps = _steps;
        if (r.size > r.steps - 2) r.size = r.steps-2;
        r.idx2 = r.steps-1;
        r.proof.length = r.steps;
        r.proof[0] = judge.calcStateHash(s_roots, s_pointers);
        r.proof[r.steps-1] = judge.calcStateHash(e_roots, e_pointers);
        r.state = State.Running;
        return true;
    }

    function getDescription(bytes32 id) public view returns (bytes32 init, uint steps, bytes32 last) {
        Record storage r = records[id];
        return (r.proof[0], r.steps, r.proof[r.steps-1]);
    }

    function getChallenger(bytes32 id) public view returns (address) {
       return records[id].challenger;
    }

    function getProver(bytes32 id) public view returns (address) {
       return records[id].prover;
    }

    function getIndices(bytes32 id) public view returns (uint idx1, uint idx2) {
        Record storage r = records[id];
        return (r.idx1, r.idx2);
    }

    function getTask(bytes32 id) public view returns (uint) {
        Record storage r = records[id];
        return r.task_id;
    }

    function deleteChallenge(bytes32 id) public {
        Record storage r = records[id];
        require (msg.sender == r.manager);
        rejected[r.task_id] = false;
        delete records[id];
    }

    function checkTimeout(bytes32 id) internal returns (bool) {
        Record storage r = records[id];
        if (r.state == State.Custom) return block.number >= r.judge.clock(r.sub_task) + r.timeout;
        return block.number >= r.clock + r.timeout && r.state != State.Finished;
   }

    function gameOver(bytes32 id) public returns (bool) {
        Record storage r = records[id];
        if (!checkTimeout(id)) return false;
        require(checkTimeout(id));
        if (r.next == r.prover) {
            r.winner = r.challenger;
            rejected[r.task_id] = true;
        }
        else {
            r.winner = r.prover;
            blocked[r.task_id] = 0;
        }
        emit WinnerSelected(id);
        r.state = State.Finished;
        return true;
    }

    function clock(bytes32 id) public returns (uint) {
        Record storage r = records[id];
        if (r.sub_task != 0) return r.judge.clock(r.sub_task);
        else return r.clock;
    }

    function isRejected(uint id) public view returns (bool) {
        return rejected[id];
    }

    function blockedTime(uint id) public view returns (uint) {
        return blocked[id] + 5;
    }

    function getIter(bytes32 id) internal view returns (uint it, uint i1, uint i2) {
        Record storage r = records[id];
        it = (r.idx2-r.idx1)/(r.size+1);
        i1 = r.idx1;
        i2 = r.idx2;
    }

    event Reported(bytes32 id, uint idx1, uint idx2, bytes32[] arr);

    function report(bytes32 id, uint i1, uint i2, bytes32[] arr) public returns (bool) {
        Record storage r = records[id];
        require(r.state == State.Running && arr.length == r.size && i1 == r.idx1 && i2 == r.idx2 &&
                msg.sender == r.prover && r.prover == r.next);
        r.clock = block.number;
        blocked[r.task_id] = r.clock + r.timeout;
        uint iter = (r.idx2-r.idx1)/(r.size+1);
        for (uint i = 0; i < arr.length; i++) {
            r.proof[r.idx1+iter*(i+1)] = arr[i];
        }
        r.next = r.challenger;
        emit Reported(id, i1, i2, arr);
        return true;
    }

    function getStateAt(bytes32 id, uint loc) public view returns (bytes32) {
        return records[id].proof[loc];
    }

    event Queried(bytes32 id, uint idx1, uint idx2);

    function query(bytes32 id, uint i1, uint i2, uint num) public {
        Record storage r = records[id];
        require(r.state == State.Running && num <= r.size && i1 == r.idx1 && i2 == r.idx2 && msg.sender == r.challenger && r.challenger == r.next);
        r.clock = block.number;
        blocked[r.task_id] = r.clock + r.timeout;
        uint iter = (r.idx2-r.idx1)/(r.size+1);
        r.idx1 = r.idx1+iter*num;
        // If last segment was selected, do not change last index
        if (num != r.size) r.idx2 = r.idx1+iter;
        if (r.size > r.idx2-r.idx1-1) r.size = r.idx2-r.idx1-1;
        // size eventually becomes zero here
        r.next = r.prover;
        emit Queried(id, r.idx1, r.idx2);
        if (r.size == 0) r.state = State.NeedPhases;
    }

    function getStep(bytes32 id, uint idx) public view returns (bytes32) {
        Record storage r = records[id];
        return r.proof[idx];
    }

    event PostedPhases(bytes32 id, uint idx1, bytes32[13] arr);

    function postPhases(bytes32 id, uint i1, bytes32[13] arr) public {
        Record storage r = records[id];
        require(r.state == State.NeedPhases && msg.sender == r.prover && r.next == r.prover && r.idx1 == i1);
        require(r.proof[r.idx1] == arr[0] && r.proof[r.idx1+1] == arr[12] && arr[12] != bytes32(0));
        r.clock = block.number;
        r.state = State.PostedPhases;
        blocked[r.task_id] = r.clock + r.timeout;
        r.result = arr;
        r.next = r.challenger;
        emit PostedPhases(id, i1, arr);
    }

    function getResult(bytes32 id)  public view returns (bytes32[13]) {
        return records[id].result;
    }

    event SelectedPhase(bytes32 id, uint idx1, uint phase);

    function selectPhase(bytes32 id, uint i1, bytes32 st, uint q) public {
        Record storage r = records[id];
        require(r.state == State.PostedPhases && msg.sender == r.challenger && r.idx1 == i1 && r.result[q] == st &&
                r.next == r.challenger && q < 13);
        r.clock = block.number;
        blocked[r.task_id] = r.clock + r.timeout;
        r.phase = q;
        emit SelectedPhase(id, i1, q);
        r.next = r.prover;
        r.state = State.SelectedPhase;
    }

    function getState(bytes32 id) public view returns (State) {
        return records[id].state;
    }

    function getPhase(bytes32 id) public view returns (uint) {
        return records[id].phase;
    }

    function getWinner(bytes32 id) public view returns (address) {
        return records[id].winner;
    }

    event WinnerSelected(bytes32 id);

    function callJudge(bytes32 id, uint i1, uint q,
                        bytes32[] proof, bytes32[] proof2,
                        bytes32 vm, bytes32 op, uint[4] regs,
                        bytes32[10] roots, uint[4] pointers) public {
        Record storage r = records[id];
        require(r.state == State.SelectedPhase && r.phase == q && msg.sender == r.prover && r.idx1 == i1 && r.next == r.prover);
        // for custom judge, use another method
        // uint alu_hint = (uint(op)/2**(8*3))&0xff; require (q != 5 || alu_hint != 0xff);

        judge.judge(r.result, r.phase, proof, proof2, vm, op, regs, roots, pointers);
        emit WinnerSelected(id);
        r.winner = r.prover;
        blocked[r.task_id] = 0;
        r.state = State.Finished;
    }

    event SubGoal(bytes32 id, uint64 judge, bytes32 init_data, uint init_size, bytes32 ret_data, uint ret_size);

    function resolveCustom(bytes32 id) public returns (bool) {
        Record storage r = records[id];
        if (r.sub_task == 0 || !r.judge.resolved(r.sub_task, r.ex_state, r.ex_size)) return false;
        emit WinnerSelected(id);
        r.winner = r.prover;
        blocked[r.task_id] = 0;
        r.state = State.Finished;
        return true;
    }

    // some register should have the input size?
    function callCustomJudge(bytes32 id, uint i1,
                        bytes32 op, uint[4] regs,
                        bytes32 custom_result, uint custom_size, bytes32[] custom_proof,
                        bytes32[10] roots, uint[4] pointers) public {

        Record storage r = records[id];
        require(r.state == State.SelectedPhase && r.phase == 6 && msg.sender == r.prover && r.idx1 == i1 &&
                r.next == r.prover);

        uint hint = (uint(op)/2**(8*5))&0xff;
        require (hint == 0x16);

        r.judge = judges[uint64(regs[3])];

        // uint256 init_size = regs[0] % 2 == 0 ? uint(custom_size_proof[0]) : uint(custom_size_proof[1]);
        bytes32 init_data = regs[0] % 2 == 0 ? custom_proof[0] : custom_proof[1];

        r.sub_task = r.judge.init(init_data, regs[1], regs[2], r.prover, r.challenger);
        r.ex_state = custom_result;
        r.ex_size = custom_size;
        judge.judgeCustom(r.result[5], r.result[6], custom_result, custom_size, op, regs, roots, pointers, custom_proof);
        r.state = State.Custom;

        emit SubGoal(id, uint64(regs[3]), init_data, regs[1], custom_result, custom_size);

        return;
    }

    function checkFileProof(bytes32 state, bytes32[10] roots, uint[4] pointers, bytes32[] proof, uint loc) public returns (bool) {
        return judge.checkFileProof(state, roots, pointers, proof, loc);
    }

    function checkProof(bytes32 hash, bytes32 root, bytes32[] proof, uint loc) public returns (bool) {
        return judge.checkProof(hash, root, proof, loc);
    }

    function calcStateHash(bytes32[10] roots, uint[4] pointers) public returns (bytes32) {
        return judge.calcStateHash(roots, pointers);
    }

}

pragma solidity ^0.4.16;

interface JudgeInterface {
    function judge(bytes32[13] res, uint q,
                        bytes32[] _proof, bytes32[] _proof2,
                        bytes32 vm_, bytes32 op, uint[4] regs,
                        bytes32[10] roots, uint[4] pointers) external returns (uint);
    function judgeCustom(bytes32 state1, bytes32 state2, bytes32 ex_state, uint ex_reg, bytes32 op, uint[4] regs, bytes32[10] roots, uint[4] pointers, bytes32[] proof) external;

    function checkFileProof(bytes32 state, bytes32[10] roots, uint[4] pointers, bytes32[] proof, uint loc) external returns (bool);
    function checkProof(bytes32 hash, bytes32 root, bytes32[] proof, uint loc) external returns (bool);

    function calcStateHash(bytes32[10] roots, uint[4] pointers) external returns (bytes32);
    function calcIOHash(bytes32[10] roots) external returns (bytes32);
}

interface CustomJudge {
    // Initializes a new custom verification game
    function init(bytes32 state, uint state_size, uint r3, address solver, address verifier) external returns (bytes32);

    // Last time the task was updated
    function clock(bytes32 id) external returns (uint);

    // Check if has resolved into correct state: merkle root of output data and output size
    function resolved(bytes32 id, bytes32 state, uint size) external returns (bool);
}

contract Interactive {

    constructor(address addr) public {
        judge = JudgeInterface(addr);
    }

    JudgeInterface judge;

    mapping (uint => uint) blocked;
    mapping (uint => bool) rejected;

    enum State {
        Started,
        Running, // First and last state have been set up ... but this will mean that the verification game is running now
        Finished, // Winner has been chosen
        NeedPhases,
        PostedPhases,
        SelectedPhase,

        // Special states for custom judges
        Custom
    }

    struct Record {
        uint256 task_id;

        address prover;
        address challenger;

        bytes32 start_state; // actually initial code + input
        bytes32 end_state; // actually output

        // Maybe number of steps should be finished
        uint256 steps;

        address winner;
        address next;

        address manager;

        uint256 size;
        uint256 timeout;
        uint256 clock;

        uint256 idx1;
        uint256 idx2;

        uint256 phase;

        bytes32[] proof;
        bytes32[13] result;

        State state;

        //
        CustomJudge judge;
        bytes32 sub_task;
        bytes32 ex_state; // result from the custom judge
        uint ex_size;
    }

    mapping (bytes32 => Record) records;
    mapping (uint64 => CustomJudge) judges;

    // who should be able to
    function registerJudge(uint64 id, address addr) public {
        judges[id] = CustomJudge(addr);
    }

    event StartChallenge(address p, address c, bytes32 s, bytes32 e, uint256 par, uint to, bytes32 uniq);

    uint nonce;

    function make(uint task_id, address p, address c, bytes32 s, bytes32 e, uint256 par, uint to) public returns (bytes32) {
        bytes32 uniq = keccak256(task_id, p, c, s, e, par, to, nonce++);
        Record storage r = records[uniq];
        r.task_id = task_id;
        r.prover = p;
        r.challenger = c;
        r.start_state = s;
        r.end_state = e;
        r.timeout = to;
        r.clock = block.number;
        r.next = r.prover;
        r.idx1 = 0;
        r.phase = 16;
        r.size = par;
        r.state = State.Started;
        r.manager = msg.sender;
        emit StartChallenge(p, c, s, e, r.size, to, uniq);
        blocked[task_id] = r.clock + r.timeout;
        return uniq;
    }

    uint constant FINAL_STATE = 0xffffffffff;

    function initialize(bytes32 id, bytes32[10] s_roots, uint[4] s_pointers, uint _steps,
                                    bytes32[10] e_roots, uint[4] e_pointers) public returns (bool) {
        Record storage r = records[id];
        require(msg.sender == r.next && r.state == State.Started);
        // check first state here
        if (r.start_state != judge.calcIOHash(s_roots)) return false;
        require (r.start_state == judge.calcIOHash(s_roots));
        // then last one
        if (r.end_state != judge.calcIOHash(e_roots)) return false;
        require (r.end_state == judge.calcIOHash(e_roots));

        // need to check that the start state is empty
        // stack
        require(s_roots[1] == 0xb4c11951957c6f8f642c4af61cd6b24640fec6dc7fc607ee8206a99e92410d30);
        // memory
        require(s_roots[2] == 0xb4c11951957c6f8f642c4af61cd6b24640fec6dc7fc607ee8206a99e92410d30);
        // call stack
        require(s_roots[3] == 0xb4c11951957c6f8f642c4af61cd6b24640fec6dc7fc607ee8206a99e92410d30);
        // globals
        require(s_roots[4] == 0xb4c11951957c6f8f642c4af61cd6b24640fec6dc7fc607ee8206a99e92410d30);
        // call table (check if resizing works)
        require(s_roots[5] == 0x7bf9aa8e0ce11d87877e8b7a304e8e7105531771dbff77d1b00366ecb1549624);
        //require(s_roots[5] == 0xc024f071f70ef04cc1aaa7cb371bd1c4f7df06b0edb57b81adbcc9cdb1dfc910);
        // call types
        require(s_roots[6] == 0xb4c11951957c6f8f642c4af61cd6b24640fec6dc7fc607ee8206a99e92410d30);
        // pointers
        require(s_pointers[0] == 0 && s_pointers[1] == 0 && s_pointers[2] == 0 && s_pointers[3] == 0);

        // check final state
        require(e_pointers[0] == FINAL_STATE);

        // Now we can initialize
        r.steps = _steps;
        if (r.size > r.steps - 2) r.size = r.steps-2;
        r.idx2 = r.steps-1;
        r.proof.length = r.steps;
        r.proof[0] = judge.calcStateHash(s_roots, s_pointers);
        r.proof[r.steps-1] = judge.calcStateHash(e_roots, e_pointers);
        r.state = State.Running;
        return true;
    }

    function getDescription(bytes32 id) public view returns (bytes32 init, uint steps, bytes32 last) {
        Record storage r = records[id];
        return (r.proof[0], r.steps, r.proof[r.steps-1]);
    }

    function getChallenger(bytes32 id) public view returns (address) {
       return records[id].challenger;
    }

    function getProver(bytes32 id) public view returns (address) {
       return records[id].prover;
    }

    function getIndices(bytes32 id) public view returns (uint idx1, uint idx2) {
        Record storage r = records[id];
        return (r.idx1, r.idx2);
    }

    function getTask(bytes32 id) public view returns (uint) {
        Record storage r = records[id];
        return r.task_id;
    }

    function deleteChallenge(bytes32 id) public {
        Record storage r = records[id];
        require (msg.sender == r.manager);
        rejected[r.task_id] = false;
        delete records[id];
    }

    function checkTimeout(bytes32 id) internal returns (bool) {
        Record storage r = records[id];
        if (r.state == State.Custom) return block.number >= r.judge.clock(r.sub_task) + r.timeout;
        return block.number >= r.clock + r.timeout && r.state != State.Finished;
   }

    function gameOver(bytes32 id) public returns (bool) {
        Record storage r = records[id];
        if (!checkTimeout(id)) return false;
        require(checkTimeout(id));
        if (r.next == r.prover) {
            r.winner = r.challenger;
            rejected[r.task_id] = true;
        }
        else {
            r.winner = r.prover;
            blocked[r.task_id] = 0;
        }
        emit WinnerSelected(id);
        r.state = State.Finished;
        return true;
    }

    function clock(bytes32 id) public returns (uint) {
        Record storage r = records[id];
        if (r.sub_task != 0) return r.judge.clock(r.sub_task);
        else return r.clock;
    }

    function isRejected(uint id) public view returns (bool) {
        return rejected[id];
    }

    function blockedTime(uint id) public view returns (uint) {
        return blocked[id] + 5;
    }

    function getIter(bytes32 id) internal view returns (uint it, uint i1, uint i2) {
        Record storage r = records[id];
        it = (r.idx2-r.idx1)/(r.size+1);
        i1 = r.idx1;
        i2 = r.idx2;
    }

    event Reported(bytes32 id, uint idx1, uint idx2, bytes32[] arr);

    function report(bytes32 id, uint i1, uint i2, bytes32[] arr) public returns (bool) {
        Record storage r = records[id];
        require(r.state == State.Running && arr.length == r.size && i1 == r.idx1 && i2 == r.idx2 &&
                msg.sender == r.prover && r.prover == r.next);
        r.clock = block.number;
        blocked[r.task_id] = r.clock + r.timeout;
        uint iter = (r.idx2-r.idx1)/(r.size+1);
        for (uint i = 0; i < arr.length; i++) {
            r.proof[r.idx1+iter*(i+1)] = arr[i];
        }
        r.next = r.challenger;
        emit Reported(id, i1, i2, arr);
        return true;
    }

    function getStateAt(bytes32 id, uint loc) public view returns (bytes32) {
        return records[id].proof[loc];
    }

    event Queried(bytes32 id, uint idx1, uint idx2);

    function query(bytes32 id, uint i1, uint i2, uint num) public {
        Record storage r = records[id];
        require(r.state == State.Running && num <= r.size && i1 == r.idx1 && i2 == r.idx2 && msg.sender == r.challenger && r.challenger == r.next);
        r.clock = block.number;
        blocked[r.task_id] = r.clock + r.timeout;
        uint iter = (r.idx2-r.idx1)/(r.size+1);
        r.idx1 = r.idx1+iter*num;
        // If last segment was selected, do not change last index
        if (num != r.size) r.idx2 = r.idx1+iter;
        if (r.size > r.idx2-r.idx1-1) r.size = r.idx2-r.idx1-1;
        // size eventually becomes zero here
        r.next = r.prover;
        emit Queried(id, r.idx1, r.idx2);
        if (r.size == 0) r.state = State.NeedPhases;
    }

    function getStep(bytes32 id, uint idx) public view returns (bytes32) {
        Record storage r = records[id];
        return r.proof[idx];
    }

    event PostedPhases(bytes32 id, uint idx1, bytes32[13] arr);

    function postPhases(bytes32 id, uint i1, bytes32[13] arr) public {
        Record storage r = records[id];
        require(r.state == State.NeedPhases && msg.sender == r.prover && r.next == r.prover && r.idx1 == i1);
        require(r.proof[r.idx1] == arr[0] && r.proof[r.idx1+1] == arr[12] && arr[12] != bytes32(0));
        r.clock = block.number;
        r.state = State.PostedPhases;
        blocked[r.task_id] = r.clock + r.timeout;
        r.result = arr;
        r.next = r.challenger;
        emit PostedPhases(id, i1, arr);
    }

    function getResult(bytes32 id)  public view returns (bytes32[13]) {
        return records[id].result;
    }

    event SelectedPhase(bytes32 id, uint idx1, uint phase);

    function selectPhase(bytes32 id, uint i1, bytes32 st, uint q) public {
        Record storage r = records[id];
        require(r.state == State.PostedPhases && msg.sender == r.challenger && r.idx1 == i1 && r.result[q] == st &&
                r.next == r.challenger && q < 13);
        r.clock = block.number;
        blocked[r.task_id] = r.clock + r.timeout;
        r.phase = q;
        emit SelectedPhase(id, i1, q);
        r.next = r.prover;
        r.state = State.SelectedPhase;
    }

    function getState(bytes32 id) public view returns (State) {
        return records[id].state;
    }

    function getPhase(bytes32 id) public view returns (uint) {
        return records[id].phase;
    }

    function getWinner(bytes32 id) public view returns (address) {
        return records[id].winner;
    }

    event WinnerSelected(bytes32 id);

    function callJudge(bytes32 id, uint i1, uint q,
                        bytes32[] proof, bytes32[] proof2,
                        bytes32 vm, bytes32 op, uint[4] regs,
                        bytes32[10] roots, uint[4] pointers) public {
        Record storage r = records[id];
        require(r.state == State.SelectedPhase && r.phase == q && msg.sender == r.prover && r.idx1 == i1 && r.next == r.prover);
        // for custom judge, use another method
        // uint alu_hint = (uint(op)/2**(8*3))&0xff; require (q != 5 || alu_hint != 0xff);

        judge.judge(r.result, r.phase, proof, proof2, vm, op, regs, roots, pointers);
        emit WinnerSelected(id);
        r.winner = r.prover;
        blocked[r.task_id] = 0;
        r.state = State.Finished;
    }

    event SubGoal(bytes32 id, uint64 judge, bytes32 init_data, uint init_size, bytes32 ret_data, uint ret_size);

    function resolveCustom(bytes32 id) public returns (bool) {
        Record storage r = records[id];
        if (r.sub_task == 0 || !r.judge.resolved(r.sub_task, r.ex_state, r.ex_size)) return false;
        emit WinnerSelected(id);
        r.winner = r.prover;
        blocked[r.task_id] = 0;
        r.state = State.Finished;
        return true;
    }

    // some register should have the input size?
    function callCustomJudge(bytes32 id, uint i1,
                        bytes32 op, uint[4] regs,
                        bytes32 custom_result, uint custom_size, bytes32[] custom_proof,
                        bytes32[10] roots, uint[4] pointers) public {

        Record storage r = records[id];
        require(r.state == State.SelectedPhase && r.phase == 6 && msg.sender == r.prover && r.idx1 == i1 &&
                r.next == r.prover);

        uint hint = (uint(op)/2**(8*5))&0xff;
        require (hint == 0x16);

        r.judge = judges[uint64(regs[3])];

        // uint256 init_size = regs[0] % 2 == 0 ? uint(custom_size_proof[0]) : uint(custom_size_proof[1]);
        bytes32 init_data = regs[0] % 2 == 0 ? custom_proof[0] : custom_proof[1];

        r.sub_task = r.judge.init(init_data, regs[1], regs[2], r.prover, r.challenger);
        r.ex_state = custom_result;
        r.ex_size = custom_size;
        judge.judgeCustom(r.result[5], r.result[6], custom_result, custom_size, op, regs, roots, pointers, custom_proof);
        r.state = State.Custom;

        emit SubGoal(id, uint64(regs[3]), init_data, regs[1], custom_result, custom_size);

        return;
    }

    function checkFileProof(bytes32 state, bytes32[10] roots, uint[4] pointers, bytes32[] proof, uint loc) public returns (bool) {
        return judge.checkFileProof(state, roots, pointers, proof, loc);
    }

    function checkProof(bytes32 hash, bytes32 root, bytes32[] proof, uint loc) public returns (bool) {
        return judge.checkProof(hash, root, proof, loc);
    }

    function calcStateHash(bytes32[10] roots, uint[4] pointers) public returns (bytes32) {
        return judge.calcStateHash(roots, pointers);
    }

}


Basic transaction contract added

Basic transaction contract added

pragma solidity ^0.4.11;

contract transaction {

	address seller;
	address buyer;
	uint value;

	enum State {Created, Confirmed, Disabled}
	State state;

	modifier  onlySeller(address person) { require(person == seller); _; }
	modifier checkValue(uint addedValue) { require(addedValue == 2*value); _; }
	modifier inState(State s) { require(s == state); _; }
	modifier  onlyBuyer(address person) { require(person == buyer); _; }

	event purchaseConfirmed();
	event receiveConfirmed();
	event refundConfirmed();

	function purchase () public
	    payable
	{
		seller = msg.sender;
		value = (msg.value*1)/2;
	}

	function confirmPurchase() public
		checkValue(msg.value)
		inState(State.Created)
		payable
	{
		buyer = msg.sender;
		state = State.Confirmed;
		purchaseConfirmed();
	}

	function confirmReceived() public
		inState(State.Confirmed)
		onlyBuyer(msg.sender)
	{
		buyer.transfer(value);
		seller.transfer(this.balance);
		state = State.Disabled;
		receiveConfirmed();
	}

	function refundBuyer() public
		inState(State.Confirmed)
		onlySeller(msg.sender)
	{
		buyer.transfer(2*value);
		seller.transfer(this.balance);
		state = State.Disabled;
		refundConfirmed();
	}

}

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


Update Context.sol (#1892)

Update Context.sol (#1892)

Fix typos in instructions

(cherry picked from commit 2836b066c9f9450376dba95c629637547428140a)

pragma solidity ^0.5.0;

/*
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with GSN meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
contract Context {
    // Empty internal constructor, to prevent people from mistakenly deploying
    // an instance of this contract, which should be used via inheritance.
    constructor () internal { }
    // solhint-disable-previous-line no-empty-blocks

    function _msgSender() internal view returns (address) {
        return msg.sender;
    }

    function _msgData() internal view returns (bytes memory) {
        this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
        return msg.data;
    }
}

pragma solidity ^0.5.0;

/*
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they not should not be accessed in such a direct
 * manner, since when dealing with GSN meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
contract Context {
    // Empty internal constructor, to prevent people from mistakenly deploying
    // an instance of this contract, with should be used via inheritance.
    constructor () internal { }
    // solhint-disable-previous-line no-empty-blocks

    function _msgSender() internal view returns (address) {
        return msg.sender;
    }

    function _msgData() internal view returns (bytes memory) {
        this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
        return msg.data;
    }
}


fix contract

fix contract

contract GovContracts {

	struct Contract {
		uint128		id;
		bytes		termsHash;
		bool		projectDone
	};

	struct Milestone {
		uint128 	id;
		uint128 	contractId;
		uint128 	duration;
		uint128		targetBudget
	};

}

contract GovContracts {

	struct Contract {
		uint128		id;
		bytes		termsHash;
		bool		projectDone
	}

	struct Milestone {
		uint128 	id;
		uint128 	contractId;
		uint128 	duration;
		uint128		targetBudget
	}

}


Use address type

Use address type

pragma solidity ^0.4.11;

import './ERC20Basic.sol';
import './SafeERC20.sol';
import '../ownership/Ownable.sol';
import '../math/Math.sol';
import '../math/SafeMath.sol';

/**
 * @title TokenVesting
 * @dev A token holder contract that can release its token balance gradually like a
 * typical vesting scheme, with a cliff and vesting period. Optionally revocable by the
 * owner.
 */
contract TokenVesting is Ownable {
  using SafeMath for uint256;
  using SafeERC20 for ERC20Basic;

  event Released(uint256 amount);
  event Revoked();

  // beneficiary of tokens after they are released
  address public beneficiary;

  uint256 public cliff;
  uint256 public start;
  uint256 public duration;

  bool public revocable;

  mapping (address => uint256) public released;
  mapping (address => bool) public revoked;

  /**
   * @dev Creates a vesting contract that vests its balance of any ERC20 token to the
   * _beneficiary, gradually in a linear fashion until _start + _duration. By then all
   * of the balance will have vested.
   * @param _beneficiary address of the beneficiary to whom vested tokens are transferred
   * @param _cliff duration in seconds of the cliff in which tokens will begin to vest
   * @param _duration duration in seconds of the period in which the tokens will vest
   * @param _revocable whether the vesting is revocable or not
   */
  function TokenVesting(address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable) {
    require(_beneficiary != address(0));
    require(_cliff <= _duration);

    beneficiary = _beneficiary;
    revocable = _revocable;
    duration = _duration;
    cliff = _start.add(_cliff);
    start = _start;
  }

  /**
   * @notice Transfers vested tokens to beneficiary.
   * @param token ERC20 token which is being vested
   */
  function release(ERC20Basic token) public {
    uint256 unreleased = releasableAmount(token);

    require(unreleased > 0);

    released[token] = released[token].add(unreleased);

    token.safeTransfer(beneficiary, unreleased);

    Released(unreleased);
  }

  /**
   * @notice Allows the owner to revoke the vesting. Tokens already vested
   * remain in the contract, the rest are returned to the owner.
   * @param token ERC20 token which is being vested
   */
  function revoke(ERC20Basic token) public onlyOwner {
    require(revocable);
    require(!revoked[token]);

    uint256 balance = token.balanceOf(this);

    uint256 unreleased = releasableAmount(token);
    uint256 refund = balance.sub(unreleased);

    revoked[token] = true;

    token.safeTransfer(owner, refund);

    Revoked();
  }

  /**
   * @dev Calculates the amount that has already vested but hasn't been released yet.
   * @param token ERC20 token which is being vested
   */
  function releasableAmount(ERC20Basic token) public constant returns (uint256) {
    return vestedAmount(token).sub(released[token]);
  }

  /**
   * @dev Calculates the amount that has already vested.
   * @param token ERC20 token which is being vested
   */
  function vestedAmount(ERC20Basic token) public constant returns (uint256) {
    uint256 currentBalance = token.balanceOf(this);
    uint256 totalBalance = currentBalance.add(released[token]);

    if (now < cliff) {
      return 0;
    } else if (now >= start + duration || revoked[token]) {
      return totalBalance;
    } else {
      return totalBalance.mul(now - start).div(duration);
    }
  }
}

pragma solidity ^0.4.11;

import './ERC20Basic.sol';
import './SafeERC20.sol';
import '../ownership/Ownable.sol';
import '../math/Math.sol';
import '../math/SafeMath.sol';

/**
 * @title TokenVesting
 * @dev A token holder contract that can release its token balance gradually like a
 * typical vesting scheme, with a cliff and vesting period. Optionally revocable by the
 * owner.
 */
contract TokenVesting is Ownable {
  using SafeMath for uint256;
  using SafeERC20 for ERC20Basic;

  event Released(uint256 amount);
  event Revoked();

  // beneficiary of tokens after they are released
  address public beneficiary;

  uint256 public cliff;
  uint256 public start;
  uint256 public duration;

  bool public revocable;

  mapping (address => uint256) public released;
  mapping (address => bool) public revoked;

  /**
   * @dev Creates a vesting contract that vests its balance of any ERC20 token to the
   * _beneficiary, gradually in a linear fashion until _start + _duration. By then all
   * of the balance will have vested.
   * @param _beneficiary address of the beneficiary to whom vested tokens are transferred
   * @param _cliff duration in seconds of the cliff in which tokens will begin to vest
   * @param _duration duration in seconds of the period in which the tokens will vest
   * @param _revocable whether the vesting is revocable or not
   */
  function TokenVesting(address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable) {
    require(_beneficiary != 0x0);
    require(_cliff <= _duration);

    beneficiary = _beneficiary;
    revocable = _revocable;
    duration = _duration;
    cliff = _start.add(_cliff);
    start = _start;
  }

  /**
   * @notice Transfers vested tokens to beneficiary.
   * @param token ERC20 token which is being vested
   */
  function release(ERC20Basic token) public {
    uint256 unreleased = releasableAmount(token);

    require(unreleased > 0);

    released[token] = released[token].add(unreleased);

    token.safeTransfer(beneficiary, unreleased);

    Released(unreleased);
  }

  /**
   * @notice Allows the owner to revoke the vesting. Tokens already vested
   * remain in the contract, the rest are returned to the owner.
   * @param token ERC20 token which is being vested
   */
  function revoke(ERC20Basic token) public onlyOwner {
    require(revocable);
    require(!revoked[token]);

    uint256 balance = token.balanceOf(this);

    uint256 unreleased = releasableAmount(token);
    uint256 refund = balance.sub(unreleased);

    revoked[token] = true;

    token.safeTransfer(owner, refund);

    Revoked();
  }

  /**
   * @dev Calculates the amount that has already vested but hasn't been released yet.
   * @param token ERC20 token which is being vested
   */
  function releasableAmount(ERC20Basic token) public constant returns (uint256) {
    return vestedAmount(token).sub(released[token]);
  }

  /**
   * @dev Calculates the amount that has already vested.
   * @param token ERC20 token which is being vested
   */
  function vestedAmount(ERC20Basic token) public constant returns (uint256) {
    uint256 currentBalance = token.balanceOf(this);
    uint256 totalBalance = currentBalance.add(released[token]);

    if (now < cliff) {
      return 0;
    } else if (now >= start + duration || revoked[token]) {
      return totalBalance;
    } else {
      return totalBalance.mul(now - start).div(duration);
    }
  }
}


Fix JS test "compilation error".

Fix JS test "compilation error".

pragma solidity ^0.4.11;
import '../BancorFormula.sol';

/*
    BancorFormula test helper that exposes some BancorFormula functions
*/
contract TestBancorFormula is BancorFormula {
    function TestBancorFormula() {
    }

    function testLn(uint256 _numerator, uint256 _denominator) public constant returns (uint256) {
        return super.ln(_numerator, _denominator);
    }

    function testFixedExp(uint256 _x, uint8 _precision) public constant returns (uint256) {
        return super.fixedExp(_x, _precision);
    }
}

pragma solidity ^0.4.11;
import '../BancorFormula.sol';

/*
    BancorFormula test helper that exposes some BancorFormula functions
*/
contract TestBancorFormula is BancorFormula {
    function TestBancorFormula() {
    }

    function testLn(uint256 _numerator, uint256 _denominator, uint8 _precision) public constant returns (uint256) {
        return super.ln(_numerator, _denominator, _precision);
    }

    function testFixedExp(uint256 _x, uint8 _precision) public constant returns (uint256) {
        return super.fixedExp(_x, _precision);
    }
}


withdraw test1

withdraw test1

pragma solidity ^0.4.4;

import "./zeppelin/token/StandardToken.sol";
import "./zeppelin/lifecycle/Stoppable.sol";

/*
 * CrowdsaleToken
 *
 * Simple ERC20 Token example, with crowdsale token creation
 */
contract PreSale is StandardToken,Stoppable {

  string public name = "PresaleToken";
  string public symbol = "PST";
  uint public decimals = 18;

  // Initial founder address (set in constructor)
  // All deposited ETH will be instantly forwarded to this address.
  // Address is a multisig wallet.
  //address public founder = 0x0;
  //Will use owner instead

  event Migrated(address _prebuy,uint amount);
  event Buy(address indexed sender, uint eth, uint pst);

  // 1 ether = 1000 example tokens
  uint PRICE = 1000;
  uint public etherCap = 20000 * 10**18; //max amount raised during crowdsale (200k USD)
  uint public presaleTokenSupply = 0; //this will keep track of the token supply created during the presale
  uint public presaleEtherRaised = 0; //this will keep track of the Ether raised during the presale

  function () payable {
    createTokens(msg.sender);
  }

  //Mul - умножение
  function createTokens(address recipient) payable {
    if (msg.value == 0) throw;

    if (safeAdd(presaleEtherRaised,msg.value)>etherCap || stopped) throw;

    uint tokens = safeMul(msg.value, getPrice());

    totalSupply = safeAdd(totalSupply, tokens);
    balances[recipient] = safeAdd(balances[recipient], tokens);
    presaleTokenSupply = safeAdd(presaleTokenSupply,tokens);
    presaleEtherRaised = safeAdd(presaleEtherRaised, msg.value);

    // I don't understand this
  //  if (!owner.call.value(msg.value)()) throw; //immediately send Ether to founder address

  // We can use it if we want immediately send.
  //if(!owner.send(msg.value)) throw;

    Buy(recipient, msg.value, tokens);
  }

  // replace this with any other price function
  function getPrice() constant returns (uint result){
    return PRICE;
  }

  function DestroyMigr(address _prebuy){
//    if (_prebuy!=msg.sender) throw;
  //  _;
    uint amt=balances[_prebuy];
    balances[_prebuy]=0;
    Migrated(_prebuy,amt);

  }

  function destroy() { // so funds not locked in contract forever
    //  if (msg.sender == organizer) {
        suicide(msg.sender); // send funds to organizer
  //    }
}

  function withdraw(){

  if(!owner.send(presaleEtherRaised))
  throw;
  }

}

pragma solidity ^0.4.4;

import "./zeppelin/token/StandardToken.sol";
import "./zeppelin/lifecycle/Stoppable.sol";

/*
 * CrowdsaleToken
 *
 * Simple ERC20 Token example, with crowdsale token creation
 */
contract PreSale is StandardToken,Stoppable {

  string public name = "PresaleToken";
  string public symbol = "PST";
  uint public decimals = 18;

  // Initial founder address (set in constructor)
  // All deposited ETH will be instantly forwarded to this address.
  // Address is a multisig wallet.
  //address public founder = 0x0;
  //Will use owner instead

  event Migrated(address _prebuy,uint amount);
  event Buy(address indexed sender, uint eth, uint pst);

  // 1 ether = 1000 example tokens
  uint PRICE = 1000;
  uint public etherCap = 20000 * 10**18; //max amount raised during crowdsale (200k USD)
  uint public presaleTokenSupply = 0; //this will keep track of the token supply created during the presale
  uint public presaleEtherRaised = 0; //this will keep track of the Ether raised during the presale

  function () payable {
    createTokens(msg.sender);
  }

  //Mul - умножение
  function createTokens(address recipient) payable {
    if (msg.value == 0) throw;

    if (safeAdd(presaleEtherRaised,msg.value)>etherCap || stopped) throw;

    uint tokens = safeMul(msg.value, getPrice());

    totalSupply = safeAdd(totalSupply, tokens);
    balances[recipient] = safeAdd(balances[recipient], tokens);
    presaleTokenSupply = safeAdd(presaleTokenSupply,tokens);
    presaleEtherRaised = safeAdd(presaleEtherRaised, msg.value);

    // I don't understand this
  //  if (!owner.call.value(msg.value)()) throw; //immediately send Ether to founder address

  // We can use it if we want immediately send.
  //if(!owner.send(msg.value)) throw;

    Buy(recipient, msg.value, tokens);
  }

  // replace this with any other price function
  function getPrice() constant returns (uint result){
    return PRICE;
  }

  function DestroyMigr(address _prebuy){
//    if (_prebuy!=msg.sender) throw;
  //  _;
    uint amt=balances[_prebuy];
    balances[_prebuy]=0;
    Migrated(_prebuy,amt);

  }

  function destroy() { // so funds not locked in contract forever
    //  if (msg.sender == organizer) {
        suicide(msg.sender); // send funds to organizer
  //    }
}

  function withdraw(){

 // if(!owner.send(presaleEtherRaised))
 // throw;
  }

}


time dependant disputes

time dependant disputes

pragma solidity ^0.4.15;

import "./common-onchain.sol";
import "./IDisputeResolver.sol";

contract WasmDispute is CommonOnchain, IDisputeResolver {

    uint constant TIMEOUT = 10;

    struct Task {
        address solver;
        address verifier;
        uint bnum;
        bytes32 spec;
        bytes32[] phases;
        uint selected_phase;
        bool passed;
    }

    mapping (bytes32 => Task) tasks;

    function newGame(address s, address v, bytes32 spec, uint) public returns (bytes32) {
        require(spec != 0);
        bytes32 id = keccak256(s, v, spec);
        Task storage t = tasks[id];
        t.solver = s;
        t.verifier = v;
        t.spec = spec;
        t.bnum = block.number;
        return id;
    }

    function status(bytes32 dispute_id) public view returns (Status) {
        Task storage t = tasks[dispute_id];
        if (t.spec == 0) return Status.NONE;
        if (t.passed || t.phases.length == 13 && t.bnum + TIMEOUT < block.number && t.selected_phase == 0) return Status.SOLVER_WINS;
        if (t.bnum + TIMEOUT < block.number) return Status.VERIFIER_WINS;
        return Status.UNRESOLVED;
    }

    function postPhases(bytes32 dispute_id, bytes32[13] phases) public {
        Task storage t = tasks[dispute_id];
        require(msg.sender == t.solver);
        t.phases = phases;
        t.bnum = block.number;
        require(t.spec == keccak256(phases[0], phases[12]));
    }

    function selectPhase(bytes32 dispute_id, uint q) public {
        Task storage t = tasks[dispute_id];
        require(msg.sender == t.solver);
        require(q < 12); // cannot select last phase
        t.selected_phase = q+1;
    }

    bytes32 mask = 0xffffffffffffffffffffffffffffffffffffffffffffffff;

    function checkProof(bytes32[] pr, bytes32[] pr2) internal view {
       if (pr2.length == 0 && !(phase == 7 && getHint(7) == 0x0c)) require (pr.length == 0 || (pr.length != 1 && pr[0] == pr[0]&mask && pr[1] == pr[1]&mask));
    }

    function judgeDispute(bytes32 dispute_id,
                        bytes32[] _proof, bytes32[] _proof2,
                        bytes32 vm_, bytes32 op, uint[4] regs,
                        bytes32[10] roots, uint[4] pointers) public {

        Task storage t = tasks[dispute_id];
        require (t.selected_phase > 0);
        uint q = t.selected_phase - 1;

        setMachine(vm_, op, regs[0], regs[1], regs[2], regs[3]);
        setVM(roots, pointers);
        // Special initial state
        if (q == 0) {
            m.vm = hashVM();
            state = hashMachine();
            require(m.vm == t.phases[q]);
        }
        else {
           state = t.phases[q];
           require(state == hashMachine());
           require(hashVM() == m.vm);
        }
        phase = q;
        checkProof(_proof, _proof2);
        proof = _proof;
        proof2 = _proof2;
        performPhase();
        // Special final state
        if (q == 11) state = m.vm;
        require (state == t.phases[q+1]);

        t.passed = true;
    }

}

// resolve a dispute with small number of steps
contract PhaseDispute is IDisputeResolver {

    uint constant TIMEOUT = 10;

    struct Task {
        address solver;
        address verifier;
        uint bnum;
        bytes32 spec;
        bytes32[] phases;
        address res;
        bytes32 dispute_id;
        uint when;
    }

    mapping (bytes32 => Task) tasks;

    function newGame(address s, address v, bytes32 spec, uint when) public returns (bytes32) {
        require(spec != 0);
        bytes32 id = keccak256(s, v, spec);
        Task storage t = tasks[id];
        t.solver = s;
        t.verifier = v;
        t.spec = spec;
        t.bnum = block.number;
        t.when = when;
        return id;
    }

    function status(bytes32 id) public view returns (Status) {
        Task storage t = tasks[id];
        if (t.spec == 0) return Status.NONE;
        IDisputeResolver res = IDisputeResolver(t.res);
        if (t.res != 0 && res.status(t.dispute_id) == Status.SOLVER_WINS || t.phases.length > 0 && t.bnum + TIMEOUT < block.number && t.dispute_id == 0) return Status.SOLVER_WINS;
        if (t.bnum + TIMEOUT < block.number || t.res != 0 && res.status(t.dispute_id) == Status.VERIFIER_WINS) return Status.VERIFIER_WINS;
        return Status.UNRESOLVED;
    }

    function postPhases(bytes32 dispute_id, bytes32[] phases, address res) public {
        Task storage t = tasks[dispute_id];
        require(msg.sender == t.solver);
        t.phases = phases;
        t.bnum = block.number;
        t.res = res;
        require(t.spec == keccak256(phases[0], phases[phases.length-1], phases.length, res));
    }

    function selectPhase(bytes32 dispute_id, uint q) public {
        Task storage t = tasks[dispute_id];
        require(msg.sender == t.solver);
        require(q < t.phases.length-1);
        t.dispute_id = IDisputeResolver(t.res).newGame(t.solver, t.verifier, keccak256(t.phases[q], t.phases[q+1], q), t.when);
    }

}

contract TransitionDispute is IDisputeResolver {

    uint constant TIMEOUT = 10;

    struct Task {
        address solver;
        address verifier;
        uint bnum;
        bytes32 spec;
        bool solved;
    }

    mapping (bytes32 => Task) tasks;

    function newGame(address s, address v, bytes32 spec, uint) public returns (bytes32) {
        require(spec != 0);
        bytes32 id = keccak256(s, v, spec);
        Task storage t = tasks[id];
        t.solver = s;
        t.verifier = v;
        t.spec = spec;
        t.bnum = block.number;
        return id;
    }

    function status(bytes32 dispute_id) public view returns (Status) {
        Task storage t = tasks[dispute_id];
        if (t.spec == 0) return Status.NONE;
        if (t.solved) return Status.SOLVER_WINS;
        if (t.bnum + TIMEOUT < block.number) return Status.VERIFIER_WINS;
        return Status.UNRESOLVED;
    }

    function transition(bytes32 state, uint q) internal returns (bytes32);

    function judge(bytes32 dispute_id, bytes32 state, uint q) public {
        Task storage t = tasks[dispute_id];
        require(t.spec == keccak256(state, transition(state, q), q));
        t.solved = true;
    }

}

contract StepDispute is CommonOnchain, TransitionDispute {

    bytes32 mask = 0xffffffffffffffffffffffffffffffffffffffffffffffff;

    function checkProof(bytes32[] pr, bytes32[] pr2) internal view {
       if (pr2.length == 0 && !(phase == 7 && getHint(7) == 0x0c)) require (pr.length == 0 || (pr.length != 1 && pr[0] == pr[0]&mask && pr[1] == pr[1]&mask));
    }

    function transition(bytes32 init, uint q) internal returns (bytes32) {
        // Special initial state
        if (q == 0) {
            m.vm = hashVM();
            state = hashMachine();
            require(m.vm == init);
        }
        else {
           require(hashVM() == m.vm);
           state = init;
           require(state == hashMachine());
        }
        phase = q;
        performPhase();
        if (q == 11) return m.vm;
        else return state;
    }

    function prepare(bytes32[] _proof, bytes32[] _proof2,
                        bytes32 vm_, bytes32 op, uint[4] regs,
                        bytes32[10] roots, uint[4] pointers) internal {
        setMachine(vm_, op, regs[0], regs[1], regs[2], regs[3]);
        setVM(roots, pointers);
        checkProof(_proof, _proof2);
        proof = _proof;
        proof2 = _proof2;
    }

    function prepareAndJudge(
                        bytes32 dispute_id, bytes32 state, uint q,
                        bytes32[] _proof, bytes32[] _proof2,
                        bytes32 vm_, bytes32 op, uint[4] regs,
                        bytes32[10] roots, uint[4] pointers) public {
         prepare(_proof, _proof2, vm_, op, regs, roots, pointers);
         judge(dispute_id, state, q);
    }

}

contract InteractiveDispute is IDisputeResolver {

    uint constant TIMEOUT = 10;

    struct Task {
        address solver;
        address verifier;
        uint bnum;
        bool verifier_turn;
        bytes32 spec;
        uint when;
        bytes32[] proof;
        address res;
        bytes32 dispute_id;
        uint256 idx1;
        uint256 idx2;
        uint size; // size == k-1 in k-ary search
    }

    mapping (bytes32 => Task) tasks;

    function newGame(address s, address v, bytes32 spec, uint when) public returns (bytes32) {
        require(spec != 0);
        bytes32 id = keccak256(s, v, spec);
        Task storage t = tasks[id];
        t.solver = s;
        t.verifier = v;
        t.spec = spec;
        t.bnum = block.number;
        t.when = when;
        return id;
    }

    function init(bytes32 dispute_id, address res, bytes32 first, bytes32 last, uint steps, uint size) public {
        Task storage t = tasks[dispute_id];
        require(t.spec == keccak256(res, first, last, steps, size));
        t.proof.length = steps;
        t.proof[0] = first;
        t.proof[t.proof.length-1] = last;
        if (t.size > steps - 2) t.size = steps-2;
        t.idx2 = steps-1;
        t.bnum = block.number;
        t.res = res;
    }

    function status(bytes32 id) public view returns (Status) {
        Task storage t = tasks[id];
        if (t.spec == 0) return Status.NONE;
        IDisputeResolver res = IDisputeResolver(t.res);
        if (t.res != 0 && res.status(t.dispute_id) == Status.SOLVER_WINS)  return Status.SOLVER_WINS;
        if (t.res != 0 && res.status(t.dispute_id) == Status.VERIFIER_WINS)  return Status.VERIFIER_WINS;
        if (t.bnum + TIMEOUT < block.number && t.verifier_turn) return Status.SOLVER_WINS;
        if (!t.verifier_turn && t.dispute_id == 0 && t.bnum + TIMEOUT < block.number) return Status.VERIFIER_WINS;
        return Status.UNRESOLVED;
    }

    event Reported(bytes32 id, uint idx1, uint idx2, bytes32[] arr);
    event Queried(bytes32 id, uint idx1, uint idx2);

    function report(bytes32 id, uint i1, uint i2, bytes32[] arr) public {
        Task storage r = tasks[id];
        require(!r.verifier_turn && msg.sender == r.solver);
        require (arr.length == r.size && i1 == r.idx1 && i2 == r.idx2);
        r.bnum = block.number;
        uint iter = (r.idx2-r.idx1)/(r.size+1);
        for (uint i = 0; i < arr.length; i++) {
            r.proof[r.idx1+iter*(i+1)] = arr[i];
        }
        r.verifier_turn = true;
        emit Reported(id, i1, i2, arr);
    }

    function query(bytes32 id, uint i1, uint i2, uint num) public {
        Task storage r = tasks[id];
        require(r.verifier_turn && msg.sender == r.verifier);
        require(num <= r.size && i1 == r.idx1 && i2 == r.idx2);
        r.bnum = block.number;
        uint iter = (r.idx2-r.idx1)/(r.size+1);
        r.idx1 = r.idx1+iter*num;
        // If last segment was selected, do not change last index
        if (num != r.size) r.idx2 = r.idx1+iter;
        if (r.size > r.idx2-r.idx1-1) r.size = r.idx2-r.idx1-1;
        r.verifier_turn = false;
        emit Queried(id, r.idx1, r.idx2);
        // Size eventually becomes zero here
        // Then call step resolver
        if (r.size == 0) r.dispute_id = IDisputeResolver(r.res).newGame(r.solver, r.verifier, keccak256(r.proof[r.idx1], r.proof[r.idx1+1]), r.when);
    }

}

contract BasicDispute is IDisputeResolver {

    uint constant TIMEOUT = 10;

    struct Task {
        address solver;
        address verifier;
        uint bnum;
        bytes32 spec;
        uint when;
    }

    mapping (bytes32 => Task) tasks;

    function newGame(address s, address v, bytes32 spec, uint when) public returns (bytes32) {
        require(spec != 0);
        bytes32 id = keccak256(s, v, spec);
        Task storage t = tasks[id];
        t.solver = s;
        t.verifier = v;
        t.spec = spec;
        t.bnum = block.number;
        t.when = when;
        return id;
    }
}

contract AndDispute is BasicDispute {
    IDisputeResolver a;
    IDisputeResolver b;

    mapping (bytes32 => bytes32) dispute_a;
    mapping (bytes32 => bytes32) dispute_b;

    constructor (address aa, address ab) public {
        a = IDisputeResolver(aa);
        b = IDisputeResolver(ab);
    }

    function init(bytes32 id, bytes32 da, bytes32 db, uint when) public {
        Task storage t = tasks[id];
        require(t.spec == keccak256(da, db));
        dispute_a[id] = a.newGame(t.solver, t.verifier, da, when);
        dispute_b[id] = b.newGame(t.solver, t.verifier, db, when);
    }

    function status(bytes32 id) public view returns (Status) {
        Task storage t = tasks[id];
        if (t.spec == 0) return Status.NONE;
        Status sa = a.status(dispute_a[id]);
        Status sb = b.status(dispute_b[id]);
        if (sa == Status.VERIFIER_WINS) return Status.VERIFIER_WINS;
        if (sb == Status.VERIFIER_WINS) return Status.VERIFIER_WINS;
        if (sa == Status.SOLVER_WINS && sb == Status.SOLVER_WINS) return Status.SOLVER_WINS;
        return Status.UNRESOLVED;
    }

}

contract MultipleDispute is BasicDispute {
    IDisputeResolver a;

    struct Dispute {
        bytes32[] lst;
        bytes32[] ids;
    }

    mapping (bytes32 => Dispute) disputes;

    constructor (address aa) public {
        a = IDisputeResolver(aa);
    }

    function init(bytes32 id, bytes32[] lst) public {
        Task storage t = tasks[id];
        Dispute storage d = disputes[id];
        require(t.spec == keccak256(lst));
        d.lst = lst;
        for (uint i = 0; i < lst.length; i++) d.ids.push(a.newGame(t.solver, t.verifier, lst[i], t.when));
    }

    function status(bytes32 id) public view returns (Status) {
        Task storage t = tasks[id];
        if (t.spec == 0) return Status.NONE;
        Dispute storage d = disputes[id];
        for (uint i = 0; i < d.ids.length; i++) {
            Status sa = a.status(d.ids[i]);
            if (sa == Status.VERIFIER_WINS) return Status.VERIFIER_WINS;
            if (sa != Status.SOLVER_WINS) return Status.UNRESOLVED;
        }
        return Status.SOLVER_WINS;
    }

}

import "./fs.sol";

contract UploadManager {

    Filesystem fs;

    enum Storage {
        IPFS,
        BLOCKCHAIN
    }

    struct RequiredFile {
       bytes32 name_hash;
       Storage file_storage;
       bytes32 file_id;
    }

    struct Spec {
       RequiredFile[] reqs;
       bool locked;
       uint filled;
       address owner;

       bytes32 name;
       bytes32 data;
    }

    mapping (bytes32 => Spec) uploads;

    constructor(address f) public {
        fs = Filesystem(f);
    }

    function init(bytes32 id, bytes32 name, bytes32 data) public {
        Spec storage io = uploads[id];
        require(io.owner == 0);
        io.owner = msg.sender;
        io.name = name;
        io.data = data;
    }

    function requireFile(bytes32 id, bytes32 hash, Storage st) public {
        Spec storage io = uploads[id];
        require(!io.locked);
        require(io.owner == msg.sender);
        io.reqs.push(RequiredFile(hash, st, 0));
    }

    function enough(bytes32 id) public {
        Spec storage io = uploads[id];
        require(io.owner == 0 || io.owner == msg.sender);
        io.locked = true;
    }

    function uploadFile(bytes32 id, uint num, bytes32 file_id, bytes32[] name_proof, bytes32[] data_proof, uint file_num) public returns (bool) {
        Spec storage io = uploads[id];
        RequiredFile storage file = io.reqs[num];
        if (!checkProof(fs.getRoot(file_id), io.data, data_proof, file_num) || !checkProof(fs.getNameHash(file_id), io.name, name_proof, file_num)) return false;

        file.file_id = file_id;
        return true;
    }

    function checkProof(bytes32 hash, bytes32 root, bytes32[] proof, uint loc) public pure returns (bool) {
        return uint(hash) == getLeaf(proof, loc) && root == getRoot(proof, loc);
    }

    function getLeaf(bytes32[] proof, uint loc) internal pure returns (uint) {
        require(proof.length >= 2);
        if (loc%2 == 0) return uint(proof[0]);
        else return uint(proof[1]);
    }

    function getRoot(bytes32[] proof, uint loc) internal pure returns (bytes32) {
        require(proof.length >= 2);
        bytes32 res = keccak256(proof[0], proof[1]);
        for (uint i = 2; i < proof.length; i++) {
            loc = loc/2;
            if (loc%2 == 0) res = keccak256(res, proof[i]);
            else res = keccak256(proof[i], res);
        }
        require(loc < 2); // This should be runtime error, access over bounds
        return res;
    }

    function fill(bytes32 id) public {
        Spec storage io = uploads[id];
        require(io.filled == 0);
        io.filled = block.number;
        for (uint i = 0; i < io.reqs.length; i++) require(io.reqs[i].file_id != 0);
    }

    function good(bytes32 id, uint when) public view returns (bool) {
        Spec storage io = uploads[id];
        return io.filled < when;
    }

}

interface CheckTime {
    function good(bytes32 id, uint when) external view returns (bool);
}

contract TimedDispute is BasicDispute {
    CheckTime a;

    constructor(address aa) public {
        a = CheckTime(aa);
    }

    function status(bytes32 id) public view returns (Status) {
        Task storage t = tasks[id];
        if (a.good(t.spec, t.when)) return Status.SOLVER_WINS;
        else return Status.VERIFIER_WINS;
    }

}

pragma solidity ^0.4.15;

import "./common-onchain.sol";
import "./IDisputeResolver.sol";

contract WasmDispute is CommonOnchain, IDisputeResolver {

    uint constant TIMEOUT = 10;

    struct Task {
        address solver;
        address verifier;
        uint bnum;
        bytes32 spec;
        bytes32[] phases;
        uint selected_phase;
        bool passed;
    }

    mapping (bytes32 => Task) tasks;

    function newGame(address s, address v, bytes32 spec, uint) public returns (bytes32) {
        require(spec != 0);
        bytes32 id = keccak256(s, v, spec);
        Task storage t = tasks[id];
        t.solver = s;
        t.verifier = v;
        t.spec = spec;
        t.bnum = block.number;
        return id;
    }

    function status(bytes32 dispute_id) public view returns (Status) {
        Task storage t = tasks[dispute_id];
        if (t.spec == 0) return Status.NONE;
        if (t.passed || t.phases.length == 13 && t.bnum + TIMEOUT < block.number && t.selected_phase == 0) return Status.SOLVER_WINS;
        if (t.bnum + TIMEOUT < block.number) return Status.VERIFIER_WINS;
        return Status.UNRESOLVED;
    }

    function postPhases(bytes32 dispute_id, bytes32[13] phases) public {
        Task storage t = tasks[dispute_id];
        require(msg.sender == t.solver);
        t.phases = phases;
        t.bnum = block.number;
        require(t.spec == keccak256(phases[0], phases[12]));
    }

    function selectPhase(bytes32 dispute_id, uint q) public {
        Task storage t = tasks[dispute_id];
        require(msg.sender == t.solver);
        require(q < 12); // cannot select last phase
        t.selected_phase = q+1;
    }

    bytes32 mask = 0xffffffffffffffffffffffffffffffffffffffffffffffff;

    function checkProof(bytes32[] pr, bytes32[] pr2) internal view {
       if (pr2.length == 0 && !(phase == 7 && getHint(7) == 0x0c)) require (pr.length == 0 || (pr.length != 1 && pr[0] == pr[0]&mask && pr[1] == pr[1]&mask));
    }

    function judgeDispute(bytes32 dispute_id,
                        bytes32[] _proof, bytes32[] _proof2,
                        bytes32 vm_, bytes32 op, uint[4] regs,
                        bytes32[10] roots, uint[4] pointers) public {

        Task storage t = tasks[dispute_id];
        require (t.selected_phase > 0);
        uint q = t.selected_phase - 1;

        setMachine(vm_, op, regs[0], regs[1], regs[2], regs[3]);
        setVM(roots, pointers);
        // Special initial state
        if (q == 0) {
            m.vm = hashVM();
            state = hashMachine();
            require(m.vm == t.phases[q]);
        }
        else {
           state = t.phases[q];
           require(state == hashMachine());
           require(hashVM() == m.vm);
        }
        phase = q;
        checkProof(_proof, _proof2);
        proof = _proof;
        proof2 = _proof2;
        performPhase();
        // Special final state
        if (q == 11) state = m.vm;
        require (state == t.phases[q+1]);

        t.passed = true;
    }

}

// resolve a dispute with small number of steps
contract PhaseDispute is IDisputeResolver {

    uint constant TIMEOUT = 10;

    struct Task {
        address solver;
        address verifier;
        uint bnum;
        bytes32 spec;
        bytes32[] phases;
        address res;
        bytes32 dispute_id;
        uint when;
    }

    mapping (bytes32 => Task) tasks;

    function newGame(address s, address v, bytes32 spec, uint when) public returns (bytes32) {
        require(spec != 0);
        bytes32 id = keccak256(s, v, spec);
        Task storage t = tasks[id];
        t.solver = s;
        t.verifier = v;
        t.spec = spec;
        t.bnum = block.number;
        t.when = when;
        return id;
    }

    function status(bytes32 id) public view returns (Status) {
        Task storage t = tasks[id];
        if (t.spec == 0) return Status.NONE;
        IDisputeResolver res = IDisputeResolver(t.res);
        if (t.res != 0 && res.status(t.dispute_id) == Status.SOLVER_WINS || t.phases.length > 0 && t.bnum + TIMEOUT < block.number && t.dispute_id == 0) return Status.SOLVER_WINS;
        if (t.bnum + TIMEOUT < block.number || t.res != 0 && res.status(t.dispute_id) == Status.VERIFIER_WINS) return Status.VERIFIER_WINS;
        return Status.UNRESOLVED;
    }

    function postPhases(bytes32 dispute_id, bytes32[] phases, address res) public {
        Task storage t = tasks[dispute_id];
        require(msg.sender == t.solver);
        t.phases = phases;
        t.bnum = block.number;
        t.res = res;
        require(t.spec == keccak256(phases[0], phases[phases.length-1], phases.length, res));
    }

    function selectPhase(bytes32 dispute_id, uint q) public {
        Task storage t = tasks[dispute_id];
        require(msg.sender == t.solver);
        require(q < t.phases.length-1);
        t.dispute_id = IDisputeResolver(t.res).newGame(t.solver, t.verifier, keccak256(t.phases[q], t.phases[q+1], q), t.when);
    }

}

contract TransitionDispute is IDisputeResolver {

    uint constant TIMEOUT = 10;

    struct Task {
        address solver;
        address verifier;
        uint bnum;
        bytes32 spec;
        bool solved;
    }

    mapping (bytes32 => Task) tasks;

    function newGame(address s, address v, bytes32 spec, uint) public returns (bytes32) {
        require(spec != 0);
        bytes32 id = keccak256(s, v, spec);
        Task storage t = tasks[id];
        t.solver = s;
        t.verifier = v;
        t.spec = spec;
        t.bnum = block.number;
        return id;
    }

    function status(bytes32 dispute_id) public view returns (Status) {
        Task storage t = tasks[dispute_id];
        if (t.spec == 0) return Status.NONE;
        if (t.solved) return Status.SOLVER_WINS;
        if (t.bnum + TIMEOUT < block.number) return Status.VERIFIER_WINS;
        return Status.UNRESOLVED;
    }

    function transition(bytes32 state, uint q) internal returns (bytes32);

    function judge(bytes32 dispute_id, bytes32 state, uint q) public {
        Task storage t = tasks[dispute_id];
        require(t.spec == keccak256(state, transition(state, q), q));
        t.solved = true;
    }

}

contract StepDispute is CommonOnchain, TransitionDispute {

    bytes32 mask = 0xffffffffffffffffffffffffffffffffffffffffffffffff;

    function checkProof(bytes32[] pr, bytes32[] pr2) internal view {
       if (pr2.length == 0 && !(phase == 7 && getHint(7) == 0x0c)) require (pr.length == 0 || (pr.length != 1 && pr[0] == pr[0]&mask && pr[1] == pr[1]&mask));
    }

    function transition(bytes32 init, uint q) internal returns (bytes32) {
        // Special initial state
        if (q == 0) {
            m.vm = hashVM();
            state = hashMachine();
            require(m.vm == init);
        }
        else {
           require(hashVM() == m.vm);
           state = init;
           require(state == hashMachine());
        }
        phase = q;
        performPhase();
        if (q == 11) return m.vm;
        else return state;
    }

    function prepare(bytes32[] _proof, bytes32[] _proof2,
                        bytes32 vm_, bytes32 op, uint[4] regs,
                        bytes32[10] roots, uint[4] pointers) internal {
        setMachine(vm_, op, regs[0], regs[1], regs[2], regs[3]);
        setVM(roots, pointers);
        checkProof(_proof, _proof2);
        proof = _proof;
        proof2 = _proof2;
    }

    function prepareAndJudge(
                        bytes32 dispute_id, bytes32 state, uint q,
                        bytes32[] _proof, bytes32[] _proof2,
                        bytes32 vm_, bytes32 op, uint[4] regs,
                        bytes32[10] roots, uint[4] pointers) public {
         prepare(_proof, _proof2, vm_, op, regs, roots, pointers);
         judge(dispute_id, state, q);
    }

}

contract InteractiveDispute is IDisputeResolver {

    uint constant TIMEOUT = 10;

    struct Task {
        address solver;
        address verifier;
        uint bnum;
        bool verifier_turn;
        bytes32 spec;
        uint when;
        bytes32[] proof;
        address res;
        bytes32 dispute_id;
        uint256 idx1;
        uint256 idx2;
        uint size; // size == k-1 in k-ary search
    }

    mapping (bytes32 => Task) tasks;

    function newGame(address s, address v, bytes32 spec, uint when) public returns (bytes32) {
        require(spec != 0);
        bytes32 id = keccak256(s, v, spec);
        Task storage t = tasks[id];
        t.solver = s;
        t.verifier = v;
        t.spec = spec;
        t.bnum = block.number;
        t.when = when;
        return id;
    }

    function init(bytes32 dispute_id, address res, bytes32 first, bytes32 last, uint steps, uint size) public {
        Task storage t = tasks[dispute_id];
        require(t.spec == keccak256(res, first, last, steps, size));
        t.proof.length = steps;
        t.proof[0] = first;
        t.proof[t.proof.length-1] = last;
        if (t.size > steps - 2) t.size = steps-2;
        t.idx2 = steps-1;
        t.bnum = block.number;
        t.res = res;
    }

    function status(bytes32 id) public view returns (Status) {
        Task storage t = tasks[id];
        if (t.spec == 0) return Status.NONE;
        IDisputeResolver res = IDisputeResolver(t.res);
        if (t.res != 0 && res.status(t.dispute_id) == Status.SOLVER_WINS)  return Status.SOLVER_WINS;
        if (t.res != 0 && res.status(t.dispute_id) == Status.VERIFIER_WINS)  return Status.VERIFIER_WINS;
        if (t.bnum + TIMEOUT < block.number && t.verifier_turn) return Status.SOLVER_WINS;
        if (!t.verifier_turn && t.dispute_id == 0 && t.bnum + TIMEOUT < block.number) return Status.VERIFIER_WINS;
        return Status.UNRESOLVED;
    }

    event Reported(bytes32 id, uint idx1, uint idx2, bytes32[] arr);
    event Queried(bytes32 id, uint idx1, uint idx2);

    function report(bytes32 id, uint i1, uint i2, bytes32[] arr) public {
        Task storage r = tasks[id];
        require(!r.verifier_turn && msg.sender == r.solver);
        require (arr.length == r.size && i1 == r.idx1 && i2 == r.idx2);
        r.bnum = block.number;
        uint iter = (r.idx2-r.idx1)/(r.size+1);
        for (uint i = 0; i < arr.length; i++) {
            r.proof[r.idx1+iter*(i+1)] = arr[i];
        }
        r.verifier_turn = true;
        emit Reported(id, i1, i2, arr);
    }

    function query(bytes32 id, uint i1, uint i2, uint num) public {
        Task storage r = tasks[id];
        require(r.verifier_turn && msg.sender == r.verifier);
        require(num <= r.size && i1 == r.idx1 && i2 == r.idx2);
        r.bnum = block.number;
        uint iter = (r.idx2-r.idx1)/(r.size+1);
        r.idx1 = r.idx1+iter*num;
        // If last segment was selected, do not change last index
        if (num != r.size) r.idx2 = r.idx1+iter;
        if (r.size > r.idx2-r.idx1-1) r.size = r.idx2-r.idx1-1;
        r.verifier_turn = false;
        emit Queried(id, r.idx1, r.idx2);
        // Size eventually becomes zero here
        // Then call step resolver
        if (r.size == 0) r.dispute_id = IDisputeResolver(r.res).newGame(r.solver, r.verifier, keccak256(r.proof[r.idx1], r.proof[r.idx1+1]), r.when);
    }

}

contract BasicDispute is IDisputeResolver {

    uint constant TIMEOUT = 10;

    struct Task {
        address solver;
        address verifier;
        uint bnum;
        bytes32 spec;
        uint when;
    }

    mapping (bytes32 => Task) tasks;

    function newGame(address s, address v, bytes32 spec, uint when) public returns (bytes32) {
        require(spec != 0);
        bytes32 id = keccak256(s, v, spec);
        Task storage t = tasks[id];
        t.solver = s;
        t.verifier = v;
        t.spec = spec;
        t.bnum = block.number;
        t.when = when;
        return id;
    }
}

contract AndDispute is BasicDispute {
    IDisputeResolver a;
    IDisputeResolver b;

    mapping (bytes32 => bytes32) dispute_a;
    mapping (bytes32 => bytes32) dispute_b;

    constructor (address aa, address ab) public {
        a = IDisputeResolver(aa);
        b = IDisputeResolver(ab);
    }

    function init(bytes32 id, bytes32 da, bytes32 db, uint when) public {
        Task storage t = tasks[id];
        require(t.spec == keccak256(da, db));
        dispute_a[id] = a.newGame(t.solver, t.verifier, da, when);
        dispute_b[id] = b.newGame(t.solver, t.verifier, db, when);
    }

    function status(bytes32 id) public view returns (Status) {
        Task storage t = tasks[id];
        if (t.spec == 0) return Status.NONE;
        Status sa = a.status(dispute_a[id]);
        Status sb = b.status(dispute_b[id]);
        if (sa == Status.VERIFIER_WINS) return Status.VERIFIER_WINS;
        if (sb == Status.VERIFIER_WINS) return Status.VERIFIER_WINS;
        if (sa == Status.SOLVER_WINS && sb == Status.SOLVER_WINS) return Status.SOLVER_WINS;
        return Status.UNRESOLVED;
    }

}

contract MultipleDispute is BasicDispute {
    IDisputeResolver a;

    struct Dispute {
        bytes32[] lst;
        bytes32[] ids;
    }

    mapping (bytes32 => Dispute) disputes;

    constructor (address aa) public {
        a = IDisputeResolver(aa);
    }

    function init(bytes32 id, bytes32[] lst) public {
        Task storage t = tasks[id];
        Dispute storage d = disputes[id];
        require(t.spec == keccak256(lst));
        d.lst = lst;
        for (uint i = 0; i < lst.length; i++) d.ids.push(a.newGame(t.solver, t.verifier, lst[i], t.when));
    }

    function status(bytes32 id) public view returns (Status) {
        Task storage t = tasks[id];
        if (t.spec == 0) return Status.NONE;
        Dispute storage d = disputes[id];
        for (uint i = 0; i < d.ids.length; i++) {
            Status sa = a.status(d.ids[i]);
            if (sa == Status.VERIFIER_WINS) return Status.VERIFIER_WINS;
            if (sa != Status.SOLVER_WINS) return Status.UNRESOLVED;
        }
        return Status.SOLVER_WINS;
    }

}

import "./fs.sol";

contract UploadManager {

    Filesystem fs;

    enum Storage {
        IPFS,
        BLOCKCHAIN
    }

    struct RequiredFile {
       bytes32 name_hash;
       Storage file_storage;
       bytes32 file_id;
    }

    struct Spec {
       RequiredFile[] reqs;
       bool locked;
       uint filled;
       address owner;

       bytes32 name;
       bytes32 data;
    }

    mapping (bytes32 => Spec) uploads;

    constructor(address f) public {
        fs = Filesystem(f);
    }

    function init(bytes32 id, bytes32 name, bytes32 data) public {
        Spec storage io = uploads[id];
        require(io.owner == 0);
        io.owner = msg.sender;
        io.name = name;
        io.data = data;
    }

    function requireFile(bytes32 id, bytes32 hash, Storage st) public {
        Spec storage io = uploads[id];
        require(!io.locked);
        require(io.owner == msg.sender);
        io.reqs.push(RequiredFile(hash, st, 0));
    }

    function enough(bytes32 id) public {
        Spec storage io = uploads[id];
        require(io.owner == 0 || io.owner == msg.sender);
        io.locked = true;
    }

    function uploadFile(bytes32 id, uint num, bytes32 file_id, bytes32[] name_proof, bytes32[] data_proof, uint file_num) public returns (bool) {
        Spec storage io = uploads[id];
        RequiredFile storage file = io.reqs[num];
        if (!checkProof(fs.getRoot(file_id), io.data, data_proof, file_num) || !checkProof(fs.getNameHash(file_id), io.name, name_proof, file_num)) return false;

        file.file_id = file_id;
        return true;
    }

    function checkProof(bytes32 hash, bytes32 root, bytes32[] proof, uint loc) public pure returns (bool) {
        return uint(hash) == getLeaf(proof, loc) && root == getRoot(proof, loc);
    }

    function getLeaf(bytes32[] proof, uint loc) internal pure returns (uint) {
        require(proof.length >= 2);
        if (loc%2 == 0) return uint(proof[0]);
        else return uint(proof[1]);
    }

    function getRoot(bytes32[] proof, uint loc) internal pure returns (bytes32) {
        require(proof.length >= 2);
        bytes32 res = keccak256(proof[0], proof[1]);
        for (uint i = 2; i < proof.length; i++) {
            loc = loc/2;
            if (loc%2 == 0) res = keccak256(res, proof[i]);
            else res = keccak256(proof[i], res);
        }
        require(loc < 2); // This should be runtime error, access over bounds
        return res;
    }

    function fill(bytes32 id) public {
        Spec storage io = uploads[id];
        require(io.filled == 0);
        io.filled = block.number;
        for (uint i = 0; i < io.reqs.length; i++) require(io.reqs[i].file_id != 0);
    }

}


Added thesaurus library, compilation fixes


Update whitespace in example.

Update whitespace in example.

import "ConvertLib.sol";

// This is just a simple example of a coin-like contract.
// It is not standards compatible and cannot be expected to talk to other
// coin/token contracts. If you want to create a standards-compliant
// token, see: https://github.com/ConsenSys/Tokens. Cheers!

contract MetaCoin {
	mapping (address => uint) balances;

	function MetaCoin() {
		balances[tx.origin] = 10000;
	}

	function sendCoin(address receiver, uint amount) returns(bool sufficient) {
		if (balances[msg.sender] < amount) return false;
		balances[msg.sender] -= amount;
		balances[receiver] += amount;
		return true;
	}

	function getBalanceInEth(address addr) returns(uint){
		return ConvertLib.convert(getBalance(addr),2);
	}

	function getBalance(address addr) returns(uint) {
  	return balances[addr];
	}
}


fixing out of gas on send deadlock

fixing out of gas on send deadlock

contract MicropaymentsChannel {
    enum Stage {
        Empty,
        PartiallyConfirmed,
        Confirmed,
        Closing,
        Closed
    }

    uint public constant closingBlockDelay = 10;

    Stage public stage;
    uint public id;
    address public from;
    uint public fromBalance;
    address public to;
    uint public toBalance;
    uint public balanceTimestamp;

    uint public closingBlockNumber;

    function MicropaymentsChannel(address _from, address _to, uint _id) {
        stage = Stage.Empty;
        id  = _id;
        from = _from;
        fromBalance = 0;
        to = _to;
        toBalance = 0;
        balanceTimestamp = 0;
    }

    modifier onlyFrom {
        if (msg.sender != from) {
            throw;
        }
        _
    }

   modifier onlyTo {
        if (msg.sender != to) {
            throw;
        }
        _
    }

    modifier onlyParticipants {
        if ((msg.sender != from) && (msg.sender != to)) {
            throw;
        }
        _
    }

    modifier atStage(Stage _stage) {
        if (stage != _stage) {
            throw;
        }
        _
    }

    modifier atOneOfStages(Stage _stage1, Stage _stage2) {
        if ((stage != _stage1) && (stage != _stage2)) {
            throw;
        }
        _
    }

    modifier readyToClose() {
        if (block.number < closingBlockNumber) {
            throw;
        }
        _
    }

    function assertYoungerBalance(uint _balanceTimestamp) internal {
        if (_balanceTimestamp <= balanceTimestamp) {
            throw;
        }
    }

    function assertSaneBalance(uint _fromBalance, uint _toBalance) internal {
        if (fromBalance + toBalance < _fromBalance + _toBalance) {
            throw;
        }
    }

    function assertMessageHash(bytes32 _expected, bytes32 _sigHash) internal {
        if (_expected != _sigHash) {
            throw;
        }
    }

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

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

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

    function openChannel()
        onlyFrom
        atStage(Stage.Empty)
    {
        stage = Stage.PartiallyConfirmed;
        fromBalance = msg.value;
    }

    function confirmChannel()
        onlyTo
        atStage(Stage.PartiallyConfirmed)
    {
        stage = Stage.Confirmed;
        toBalance = msg.value;
    }

    function requestClosingChannel()
        onlyParticipants
        atOneOfStages(Stage.PartiallyConfirmed, Stage.Confirmed)
    {
        if (stage == Stage.PartiallyConfirmed) {
            stage = Stage.Closed;
        } else {
            stage = Stage.Closing;
            closingBlockNumber = block.number + closingBlockDelay;
        }
    }

    function closeChannel()
        onlyParticipants
        atStage(Stage.Closing)
        readyToClose
    {
        stage = Stage.Closed;
    }

    function withdrawFrom()
        onlyFrom
        atStage(Stage.Closed)
    {
        uint balance = fromBalance;
        fromBalance = 0;
        from.send(balance);
    }

    function withdrawTo()
        onlyTo
        atStage(Stage.Closed)
    {
        uint toSend = toBalance;
        toBalance = 0;
        to.send(balance);
    }

    function updateChannelState(
        uint _balanceTimestamp,
        uint _fromBalance,
        uint _toBalance,
        uint8 _sigV,
        bytes32 _sigR,
        bytes32 _sigS
    )
        onlyParticipants
        atOneOfStages(Stage.Confirmed, Stage.Closing)
    {
        assertYoungerBalance(_balanceTimestamp);
        assertSaneBalance(_fromBalance, _toBalance);
        assertSignedByBoth(getUpdateHash(_balanceTimestamp, _fromBalance, _toBalance), _sigV, _sigR, _sigS);
        balanceTimestamp = _balanceTimestamp;
        fromBalance = _fromBalance;
        toBalance = _toBalance;
    }
}

contract MicropaymentsNetwork {
    mapping (address => mapping (address => mapping( uint => MicropaymentsChannel))) channels;

    function MicropaymentsNetwork() {
    }

    function registerChannel(address _from, address _to, uint _id) {
        channels[_from][_to][_id] = new MicropaymentsChannel(_from, _to, _id);
    }

    function getChannel(address _from, address _to, uint _id)
        constant
        returns (MicropaymentsChannel)
    {
        return channels[_from][_to][_id];
    }
}

contract MicropaymentsChannel {
    enum Stage {
        Empty,
        PartiallyConfirmed,
        Confirmed,
        Closing,
        Closed
    }

    uint public constant closingBlockDelay = 10;

    Stage public stage;
    uint public id;
    address public from;
    uint public fromBalance;
    address public to;
    uint public toBalance;
    uint public balanceTimestamp;

    uint public closingBlockNumber;

    function MicropaymentsChannel(address _from, address _to, uint _id) {
        stage = Stage.Empty;
        id  = _id;
        from = _from;
        fromBalance = 0;
        to = _to;
        toBalance = 0;
        balanceTimestamp = 0;
    }

    modifier onlyFrom {
        if (msg.sender != from) {
            throw;
        }
        _
    }

   modifier onlyTo {
        if (msg.sender != to) {
            throw;
        }
        _
    }

    modifier onlyParticipants {
        if ((msg.sender != from) && (msg.sender != to)) {
            throw;
        }
        _
    }

    modifier atStage(Stage _stage) {
        if (stage != _stage) {
            throw;
        }
        _
    }

    modifier atOneOfStages(Stage _stage1, Stage _stage2) {
        if ((stage != _stage1) && (stage != _stage2)) {
            throw;
        }
        _
    }

    modifier readyToClose() {
        if (block.number < closingBlockNumber) {
            throw;
        }
        _
    }

    function assertYoungerBalance(uint _balanceTimestamp) internal {
        if (_balanceTimestamp <= balanceTimestamp) {
            throw;
        }
    }

    function assertSaneBalance(uint _fromBalance, uint _toBalance) internal {
        if (fromBalance + toBalance < _fromBalance + _toBalance) {
            throw;
        }
    }

    function assertMessageHash(bytes32 _expected, bytes32 _sigHash) internal {
        if (_expected != _sigHash) {
            throw;
        }
    }

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

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

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

    function openChannel()
        onlyFrom
        atStage(Stage.Empty)
    {
        stage = Stage.PartiallyConfirmed;
        fromBalance = msg.value;
    }

    function confirmChannel()
        onlyTo
        atStage(Stage.PartiallyConfirmed)
    {
        stage = Stage.Confirmed;
        toBalance = msg.value;
    }

    function requestClosingChannel()
        onlyParticipants
        atOneOfStages(Stage.PartiallyConfirmed, Stage.Confirmed)
    {
        if (stage == Stage.PartiallyConfirmed) {
            suicide(from);
        } else {
            stage = Stage.Closing;
            closingBlockNumber = block.number + closingBlockDelay;
        }
    }

    function closeChannel()
        onlyParticipants
        atStage(Stage.Closing)
        readyToClose
    {
        stage = Stage.Closed;
        from.send(fromBalance);
        suicide(to);
    }

    function updateChannelState(
        uint _balanceTimestamp,
        uint _fromBalance,
        uint _toBalance,
        uint8 _sigV,
        bytes32 _sigR,
        bytes32 _sigS
    )
        onlyParticipants
        atOneOfStages(Stage.Confirmed, Stage.Closing)
    {
        assertYoungerBalance(_balanceTimestamp);
        assertSaneBalance(_fromBalance, _toBalance);
        assertSignedByBoth(getUpdateHash(_balanceTimestamp, _fromBalance, _toBalance), _sigV, _sigR, _sigS);
        balanceTimestamp = _balanceTimestamp;
        fromBalance = _fromBalance;
        toBalance = _toBalance;
    }
}

contract MicropaymentsNetwork {
    mapping (address => mapping (address => mapping( uint => MicropaymentsChannel))) channels;

    function MicropaymentsNetwork() {
    }

    function registerChannel(address _from, address _to, uint _id) {
        channels[_from][_to][_id] = new MicropaymentsChannel(_from, _to, _id);
    }

    function getChannel(address _from, address _to, uint _id)
        constant
        returns (MicropaymentsChannel)
    {
        return channels[_from][_to][_id];
    }
}


Made functions to get a random number. Needs to be tested and then properly implemented into main codebase.

import "api.sol";

contract RandomNumbers is usingOraclize
{
  function getSeedNumber() returns(uint)
  {
    oraclize_setNetwork(networkID_mainnet);
    return uint(oraclize_query("WolframAlpha", "random number between 0 and 100"));
  }

  function getRandom(uint max) returns(uint)
  {
    return ((getSeedNumber()/100)*max);
  }

  function getRandom(uint min, uint max) returns(uint)
  {
    return ((getSeedNumber()/100)*(max-min)+min);
  }
}

import "api.sol";

contract RandomNumbers is usingOraclize {

  function sortaRandomGen() returns(uint) { //function using oraclize to get a random number from wolfram alpha

    oraclize_setNetwork(networkID_mainnet);

    return uint(oraclize_query("WolframAlpha", "random number between 0 and 100"));

  }
}