// File: FactRegistry.sol



pragma solidity ^0.5.2;

import "./IQueryableFactRegistry.sol";

contract FactRegistry is IQueryableFactRegistry {
    // Mapping: fact hash -> true.
    mapping (bytes32 => bool) private verifiedFact;

    // Indicates whether the Fact Registry has at least one fact registered.
    bool anyFactRegistered;

    /*
      Checks if a fact has been verified.
    */
    function isValid(bytes32 fact)
        external view
        returns(bool)
    {
        return verifiedFact[fact];
    }

    function registerFact(
        bytes32 factHash
        )
        internal
    {
        // This function stores the testiment hash in the mapping.
        verifiedFact[factHash] = true;

        // Mark first time off.
        if (!anyFactRegistered) {
            anyFactRegistered = true;
        }
    }

    /*
      Indicates whether at least one fact was registered.
    */
    function hasRegisteredFact()
        external view
        returns(bool)
    {
        return anyFactRegistered;
    }

}

// File: Fri.sol



pragma solidity ^0.5.2;

import "./MemoryMap.sol";
import "./MemoryAccessUtils.sol";
import "./FriLayer.sol";
import "./HornerEvaluator.sol";

/*
  This contract computes and verifies all the FRI layer, one by one. The final layer is verified
  by evaluating the fully committed polynomial, and requires specific handling.
*/
contract Fri is MemoryMap, MemoryAccessUtils, HornerEvaluator, FriLayer {
    event LogGas(string name, uint256 val);

    function verifyLastLayer(uint256[] memory ctx, uint256 nPoints)
        internal {
        uint256 friLastLayerDegBound = ctx[MM_FRI_LAST_LAYER_DEG_BOUND];
        uint256 groupOrderMinusOne = friLastLayerDegBound * ctx[MM_BLOW_UP_FACTOR] - 1;
        uint256 coefsStart = ctx[MM_FRI_LAST_LAYER_PTR];

        for (uint256 i = 0; i < nPoints; i++) {
            uint256 point = ctx[MM_FRI_QUEUE + 3*i + 2];
            // Invert point using inverse(point) == fpow(point, ord(point) - 1).

            point = fpow(point, groupOrderMinusOne);
            require(
                hornerEval(coefsStart, point, friLastLayerDegBound) == ctx[MM_FRI_QUEUE + 3*i + 1],
                "Bad Last layer value.");
        }
    }

    /*
      Verifies FRI layers.

      Upon entry and every time we pass through the "if (index < layerSize)" condition,
      ctx[mmFriQueue:] holds an array of triplets (query index, FRI value, FRI inversed point), i.e.
          ctx[mmFriQueue::3] holds query indices.
          ctx[mmFriQueue + 1::3] holds the input for the next layer.
          ctx[mmFriQueue + 2::3] holds the inverses of the evaluation points:
            ctx[mmFriQueue + 3*i + 2] = inverse(
                fpow(layerGenerator,  bitReverse(ctx[mmFriQueue + 3*i], logLayerSize)).
    */
    function friVerifyLayers(
        uint256[] memory ctx)
        internal
    {

        uint256 friCtx = getPtr(ctx, MM_FRI_CTX);
        require(
            MAX_SUPPORTED_MAX_FRI_STEP == FRI_MAX_FRI_STEP,
            "Incosistent MAX_FRI_STEP between MemoryMap.sol and FriLayer.sol");
        initFriGroups(friCtx);
        // emit LogGas("FRI offset precomputation", gasleft());
        uint256 channelPtr = getChannelPtr(ctx);
        uint256 merkleQueuePtr = getMerkleQueuePtr(ctx);

        uint256 friStep = 1;
        uint256 nLiveQueries = ctx[MM_N_UNIQUE_QUERIES];

        // Add 0 at the end of the queries array to avoid empty array check in readNextElment.
        ctx[MM_FRI_QUERIES_DELIMITER] = 0;

        // Rather than converting all the values from Montgomery to standard form,
        // we can just pretend that the values are in standard form but all
        // the committed polynomials are multiplied by MontgomeryR.
        //
        // The values in the proof are already multiplied by MontgomeryR,
        // but the inputs from the OODS oracle need to be fixed.
        for (uint256 i = 0; i < nLiveQueries; i++ ) {
            ctx[MM_FRI_QUEUE + 3*i + 1] = fmul(ctx[MM_FRI_QUEUE + 3*i + 1], K_MONTGOMERY_R);
        }

        uint256 friQueue = getPtr(ctx, MM_FRI_QUEUE);

        uint256[] memory friSteps = getFriSteps(ctx);
        uint256 nFriSteps = friSteps.length;
        while (friStep < nFriSteps) {
            uint256 friCosetSize = 2**friSteps[friStep];

            nLiveQueries = computeNextLayer(
                channelPtr, friQueue, merkleQueuePtr, nLiveQueries,
                ctx[MM_FRI_EVAL_POINTS + friStep], friCosetSize, friCtx);

            // emit LogGas(
            //     string(abi.encodePacked("FRI layer ", bytes1(uint8(48 + friStep)))), gasleft());

            // Layer is done, verify the current layer and move to next layer.
            // ctx[mmMerkleQueue: merkleQueueIdx) holds the indices
            // and values of the merkle leaves that need verification.
            verify(
                channelPtr, merkleQueuePtr, bytes32(ctx[MM_FRI_COMMITMENTS + friStep - 1]),
                nLiveQueries);

            // emit LogGas(
            //     string(abi.encodePacked("Merkle of FRI layer ", bytes1(uint8(48 + friStep)))),
            //     gasleft());
            friStep++;
        }

        verifyLastLayer(ctx, nLiveQueries);
        // emit LogGas("last FRI layer", gasleft());
    }
}

// File: FriLayer.sol



pragma solidity ^0.5.2;

import "./MerkleVerifier.sol";
import "./PrimeFieldElement6.sol";

/*
  The main component of FRI is the FRI step which takes
  the i-th layer evaluations on a coset c*<g> and produces a single evaluation in layer i+1.

  To this end we have a friCtx that holds the following data:
  evaluations:    holds the evaluations on the coset we are currently working on.
  group:          holds the group <g> in bit reversed order.
  halfInvGroup:   holds the group <g^-1>/<-1> in bit reversed order.
                  (We only need half of the inverse group)

  Note that due to the bit reversed order, a prefix of size 2^k of either group
  or halfInvGroup has the same structure (but for a smaller group).
*/
contract FriLayer is MerkleVerifier, PrimeFieldElement6 {
    event LogGas(string name, uint256 val);

    uint256 constant internal FRI_MAX_FRI_STEP = 4;
    uint256 constant internal MAX_COSET_SIZE = 2**FRI_MAX_FRI_STEP;
    // Generator of the group of size MAX_COSET_SIZE: GENERATOR_VAL**((PRIME - 1)/MAX_COSET_SIZE).
    uint256 constant internal FRI_GROUP_GEN =
    0x1388a7fd3b4b9599dc4b0691d6a5fcba;

    uint256 constant internal FRI_GROUP_SIZE = 0x20 * MAX_COSET_SIZE;
    uint256 constant internal FRI_CTX_TO_COSET_EVALUATIONS_OFFSET = 0;
    uint256 constant internal FRI_CTX_TO_FRI_GROUP_OFFSET = FRI_GROUP_SIZE;
    uint256 constant internal FRI_CTX_TO_FRI_HALF_INV_GROUP_OFFSET =
    FRI_CTX_TO_FRI_GROUP_OFFSET + FRI_GROUP_SIZE;

    uint256 constant internal FRI_CTX_SIZE =
    FRI_CTX_TO_FRI_HALF_INV_GROUP_OFFSET + (FRI_GROUP_SIZE / 2);

    function nextLayerElementFromTwoPreviousLayerElements(
        uint256 fX, uint256 fMinusX, uint256 evalPoint, uint256 xInv)
        internal pure
        returns (uint256 res)
    {
        // Folding formula:
        // f(x)  = g(x^2) + xh(x^2)
        // f(-x) = g((-x)^2) - xh((-x)^2) = g(x^2) - xh(x^2)
        // =>
        // 2g(x^2) = f(x) + f(-x)
        // 2h(x^2) = (f(x) - f(-x))/x
        // => The 2*interpolation at evalPoint is:
        // 2*(g(x^2) + evalPoint*h(x^2)) = f(x) + f(-x) + evalPoint*(f(x) - f(-x))*xInv.
        //
        // Note that multiplying by 2 doesn't affect the degree,
        // so we can just agree to do that on both the prover and verifier.
        assembly {
            // PRIME is PrimeFieldElement6.K_MODULUS.
            let PRIME := 0x30000003000000010000000000000001
            // Note that whenever we call add(), the result is always less than 2*PRIME,
            // so there are no overflows.
            res := addmod(add(fX, fMinusX),
                   mulmod(mulmod(evalPoint, xInv, PRIME),
                   add(fX, /*-fMinusX*/sub(PRIME, fMinusX)), PRIME), PRIME)
        }
    }

    /*
      Reads 4 elements, and applies 2 + 1 FRI transformations to obtain a single element.

      FRI layer n:                              f0 f1  f2 f3
      -----------------------------------------  \ / -- \ / -----------
      FRI layer n+1:                              f0    f2
      -------------------------------------------- \ ---/ -------------
      FRI layer n+2:                                 f0

      The basic FRI transformation is described in nextLayerElementFromTwoPreviousLayerElements().
    */
    function do2FriSteps(
        uint256 friHalfInvGroupPtr, uint256 evaluationsOnCosetPtr, uint256 cosetOffset_,
        uint256 friEvalPoint)
    internal pure returns (uint256 nextLayerValue, uint256 nextXInv) {
        assembly {
            let PRIME := 0x30000003000000010000000000000001
            let friEvalPointDivByX := mulmod(friEvalPoint, cosetOffset_, PRIME)

            let f0 := mload(evaluationsOnCosetPtr)
            {
                let f1 := mload(add(evaluationsOnCosetPtr, 0x20))

                // f0 < 3P ( = 1 + 1 + 1).
                f0 := add(add(f0, f1),
                             mulmod(friEvalPointDivByX,
                                    add(f0, /*-fMinusX*/sub(PRIME, f1)),
                                    PRIME))
            }

            let f2 := mload(add(evaluationsOnCosetPtr, 0x40))
            {
                let f3 := mload(add(evaluationsOnCosetPtr, 0x60))
                f2 := addmod(add(f2, f3),
                             mulmod(add(f2, /*-fMinusX*/sub(PRIME, f3)),
                                    mulmod(mload(add(friHalfInvGroupPtr, 0x20)),
                                           friEvalPointDivByX,
                                           PRIME),
                                    PRIME),
                             PRIME)
            }

            {
                let newXInv := mulmod(cosetOffset_, cosetOffset_, PRIME)
                nextXInv := mulmod(newXInv, newXInv, PRIME)
            }

            // f0 + f2 < 4P ( = 3 + 1).
            nextLayerValue := addmod(add(f0, f2),
                          mulmod(mulmod(friEvalPointDivByX, friEvalPointDivByX, PRIME),
                                 add(f0, /*-fMinusX*/sub(PRIME, f2)),
                                 PRIME),
                          PRIME)
        }
    }

    /*
      Reads 8 elements, and applies 4 + 2 + 1 FRI transformation to obtain a single element.

      See do2FriSteps for more detailed explanation.
    */
    function do3FriSteps(
        uint256 friHalfInvGroupPtr, uint256 evaluationsOnCosetPtr, uint256 cosetOffset_,
        uint256 friEvalPoint)
    internal pure returns (uint256 nextLayerValue, uint256 nextXInv) {
        assembly {
            let PRIME := 0x30000003000000010000000000000001
            let MPRIME := 0x300000030000000100000000000000010
            let f0 := mload(evaluationsOnCosetPtr)

            let friEvalPointDivByX := mulmod(friEvalPoint, cosetOffset_, PRIME)
            let friEvalPointDivByXSquared := mulmod(friEvalPointDivByX, friEvalPointDivByX, PRIME)
            let imaginaryUnit := mload(add(friHalfInvGroupPtr, 0x20))

            {
                let f1 := mload(add(evaluationsOnCosetPtr, 0x20))

                // f0 < 3P ( = 1 + 1 + 1).
                f0 := add(add(f0, f1),
                          mulmod(friEvalPointDivByX,
                                 add(f0, /*-fMinusX*/sub(PRIME, f1)),
                                 PRIME))
            }
            {
                let f2 := mload(add(evaluationsOnCosetPtr, 0x40))
                {
                    let f3 := mload(add(evaluationsOnCosetPtr, 0x60))

                    // f2 < 3P ( = 1 + 1 + 1).
                    f2 := add(add(f2, f3),
                              mulmod(add(f2, /*-fMinusX*/sub(PRIME, f3)),
                                     mulmod(friEvalPointDivByX, imaginaryUnit, PRIME),
                                     PRIME))
                }

                // f0 < 7P ( = 3 + 3 + 1).
                f0 := add(add(f0, f2),
                          mulmod(friEvalPointDivByXSquared,
                                 add(f0, /*-fMinusX*/sub(MPRIME, f2)),
                                 PRIME))
            }
            {
                let f4 := mload(add(evaluationsOnCosetPtr, 0x80))
                {
                    let friEvalPointDivByX2 := mulmod(friEvalPointDivByX,
                                                    mload(add(friHalfInvGroupPtr, 0x40)), PRIME)
                    {
                        let f5 := mload(add(evaluationsOnCosetPtr, 0xa0))

                        // f4 < 3P ( = 1 + 1 + 1).
                        f4 := add(add(f4, f5),
                                  mulmod(friEvalPointDivByX2,
                                         add(f4, /*-fMinusX*/sub(PRIME, f5)),
                                         PRIME))
                    }

                    let f6 := mload(add(evaluationsOnCosetPtr, 0xc0))
                    {
                        let f7 := mload(add(evaluationsOnCosetPtr, 0xe0))

                        // f6 < 3P ( = 1 + 1 + 1).
                        f6 := add(add(f6, f7),
                                  mulmod(add(f6, /*-fMinusX*/sub(PRIME, f7)),
                                         // friEvalPointDivByX2 * imaginaryUnit ==
                                         // friEvalPointDivByX * mload(add(friHalfInvGroupPtr, 0x60)).
                                         mulmod(friEvalPointDivByX2, imaginaryUnit, PRIME),
                                         PRIME))
                    }

                    // f4 < 7P ( = 3 + 3 + 1).
                    f4 := add(add(f4, f6),
                              mulmod(mulmod(friEvalPointDivByX2, friEvalPointDivByX2, PRIME),
                                     add(f4, /*-fMinusX*/sub(MPRIME, f6)),
                                     PRIME))
                }

                // f0, f4 < 7P -> f0 + f4 < 14P && 9P < f0 + (MPRIME - f4) < 23P.
                nextLayerValue :=
                   addmod(add(f0, f4),
                          mulmod(mulmod(friEvalPointDivByXSquared, friEvalPointDivByXSquared, PRIME),
                                 add(f0, /*-fMinusX*/sub(MPRIME, f4)),
                                 PRIME),
                          PRIME)
            }

            {
                let xInv2 := mulmod(cosetOffset_, cosetOffset_, PRIME)
                let xInv4 := mulmod(xInv2, xInv2, PRIME)
                nextXInv := mulmod(xInv4, xInv4, PRIME)
            }


        }
    }

    /*
      This function reads 16 elements, and applies 8 + 4 + 2 + 1 fri transformation
      to obtain a single element.

      See do2FriSteps for more detailed explanation.
    */
    function do4FriSteps(
        uint256 friHalfInvGroupPtr, uint256 evaluationsOnCosetPtr, uint256 cosetOffset_,
        uint256 friEvalPoint)
    internal pure returns (uint256 nextLayerValue, uint256 nextXInv) {
        assembly {
            let friEvalPointDivByXTessed
            let PRIME := 0x30000003000000010000000000000001
            let MPRIME := 0x300000030000000100000000000000010
            let f0 := mload(evaluationsOnCosetPtr)

            let friEvalPointDivByX := mulmod(friEvalPoint, cosetOffset_, PRIME)
            let imaginaryUnit := mload(add(friHalfInvGroupPtr, 0x20))

            {
                let f1 := mload(add(evaluationsOnCosetPtr, 0x20))

                // f0 < 3P ( = 1 + 1 + 1).
                f0 := add(add(f0, f1),
                          mulmod(friEvalPointDivByX,
                                 add(f0, /*-fMinusX*/sub(PRIME, f1)),
                                 PRIME))
            }
            {
                let f2 := mload(add(evaluationsOnCosetPtr, 0x40))
                {
                    let f3 := mload(add(evaluationsOnCosetPtr, 0x60))

                    // f2 < 3P ( = 1 + 1 + 1).
                    f2 := add(add(f2, f3),
                                mulmod(add(f2, /*-fMinusX*/sub(PRIME, f3)),
                                       mulmod(friEvalPointDivByX, imaginaryUnit, PRIME),
                                       PRIME))
                }
                {
                    let friEvalPointDivByXSquared := mulmod(friEvalPointDivByX, friEvalPointDivByX, PRIME)
                    friEvalPointDivByXTessed := mulmod(friEvalPointDivByXSquared, friEvalPointDivByXSquared, PRIME)

                    // f0 < 7P ( = 3 + 3 + 1).
                    f0 := add(add(f0, f2),
                              mulmod(friEvalPointDivByXSquared,
                                     add(f0, /*-fMinusX*/sub(MPRIME, f2)),
                                     PRIME))
                }
            }
            {
                let f4 := mload(add(evaluationsOnCosetPtr, 0x80))
                {
                    let friEvalPointDivByX2 := mulmod(friEvalPointDivByX,
                                                      mload(add(friHalfInvGroupPtr, 0x40)), PRIME)
                    {
                        let f5 := mload(add(evaluationsOnCosetPtr, 0xa0))

                        // f4 < 3P ( = 1 + 1 + 1).
                        f4 := add(add(f4, f5),
                                  mulmod(friEvalPointDivByX2,
                                         add(f4, /*-fMinusX*/sub(PRIME, f5)),
                                         PRIME))
                    }

                    let f6 := mload(add(evaluationsOnCosetPtr, 0xc0))
                    {
                        let f7 := mload(add(evaluationsOnCosetPtr, 0xe0))

                        // f6 < 3P ( = 1 + 1 + 1).
                        f6 := add(add(f6, f7),
                                  mulmod(add(f6, /*-fMinusX*/sub(PRIME, f7)),
                                         // friEvalPointDivByX2 * imaginaryUnit ==
                                         // friEvalPointDivByX * mload(add(friHalfInvGroupPtr, 0x60)).
                                         mulmod(friEvalPointDivByX2, imaginaryUnit, PRIME),
                                         PRIME))
                    }

                    // f4 < 7P ( = 3 + 3 + 1).
                    f4 := add(add(f4, f6),
                              mulmod(mulmod(friEvalPointDivByX2, friEvalPointDivByX2, PRIME),
                                     add(f4, /*-fMinusX*/sub(MPRIME, f6)),
                                     PRIME))
                }

                // f0 < 15P ( = 7 + 7 + 1).
                f0 := add(add(f0, f4),
                          mulmod(friEvalPointDivByXTessed,
                                 add(f0, /*-fMinusX*/sub(MPRIME, f4)),
                                 PRIME))
            }
            {
                let f8 := mload(add(evaluationsOnCosetPtr, 0x100))
                {
                    let friEvalPointDivByX4 := mulmod(friEvalPointDivByX,
                                                      mload(add(friHalfInvGroupPtr, 0x80)), PRIME)
                    {
                        let f9 := mload(add(evaluationsOnCosetPtr, 0x120))

                        // f8 < 3P ( = 1 + 1 + 1).
                        f8 := add(add(f8, f9),
                                  mulmod(friEvalPointDivByX4,
                                         add(f8, /*-fMinusX*/sub(PRIME, f9)),
                                         PRIME))
                    }

                    let f10 := mload(add(evaluationsOnCosetPtr, 0x140))
                    {
                        let f11 := mload(add(evaluationsOnCosetPtr, 0x160))
                        // f10 < 3P ( = 1 + 1 + 1).
                        f10 := add(add(f10, f11),
                                   mulmod(add(f10, /*-fMinusX*/sub(PRIME, f11)),
                                          // friEvalPointDivByX4 * imaginaryUnit ==
                                          // friEvalPointDivByX * mload(add(friHalfInvGroupPtr, 0xa0)).
                                          mulmod(friEvalPointDivByX4, imaginaryUnit, PRIME),
                                          PRIME))
                    }

                    // f8 < 7P ( = 3 + 3 + 1).
                    f8 := add(add(f8, f10),
                              mulmod(mulmod(friEvalPointDivByX4, friEvalPointDivByX4, PRIME),
                                     add(f8, /*-fMinusX*/sub(MPRIME, f10)),
                                     PRIME))
                }
                {
                    let f12 := mload(add(evaluationsOnCosetPtr, 0x180))
                    {
                        let friEvalPointDivByX6 := mulmod(friEvalPointDivByX,
                                                          mload(add(friHalfInvGroupPtr, 0xc0)), PRIME)
                        {
                            let f13 := mload(add(evaluationsOnCosetPtr, 0x1a0))

                            // f12 < 3P ( = 1 + 1 + 1).
                            f12 := add(add(f12, f13),
                                       mulmod(friEvalPointDivByX6,
                                              add(f12, /*-fMinusX*/sub(PRIME, f13)),
                                              PRIME))
                        }

                        let f14 := mload(add(evaluationsOnCosetPtr, 0x1c0))
                        {
                            let f15 := mload(add(evaluationsOnCosetPtr, 0x1e0))

                            // f14 < 3P ( = 1 + 1 + 1).
                            f14 := add(add(f14, f15),
                                       mulmod(add(f14, /*-fMinusX*/sub(PRIME, f15)),
                                              // friEvalPointDivByX6 * imaginaryUnit ==
                                              // friEvalPointDivByX * mload(add(friHalfInvGroupPtr, 0xe0)).
                                              mulmod(friEvalPointDivByX6, imaginaryUnit, PRIME),
                                              PRIME))
                        }

                        // f12 < 7P ( = 3 + 3 + 1).
                        f12 := add(add(f12, f14),
                                   mulmod(mulmod(friEvalPointDivByX6, friEvalPointDivByX6, PRIME),
                                          add(f12, /*-fMinusX*/sub(MPRIME, f14)),
                                          PRIME))
                    }

                    // f8 < 15P ( = 7 + 7 + 1).
                    f8 := add(add(f8, f12),
                              mulmod(mulmod(friEvalPointDivByXTessed, imaginaryUnit, PRIME),
                                     add(f8, /*-fMinusX*/sub(MPRIME, f12)),
                                     PRIME))
                }

                // f0, f8 < 15P -> f0 + f8 < 30P && 16P < f0 + (MPRIME - f8) < 31P.
                nextLayerValue :=
                    addmod(add(f0, f8),
                           mulmod(mulmod(friEvalPointDivByXTessed, friEvalPointDivByXTessed, PRIME),
                                  add(f0, /*-fMinusX*/sub(MPRIME, f8)),
                                  PRIME),
                           PRIME)
            }

            {
                let xInv2 := mulmod(cosetOffset_, cosetOffset_, PRIME)
                let xInv4 := mulmod(xInv2, xInv2, PRIME)
                let xInv8 := mulmod(xInv4, xInv4, PRIME)
                nextXInv := mulmod(xInv8, xInv8, PRIME)
            }
        }
    }

    /*
      Gathers the "cosetSize" elements that belong to the same coset
      as the item at the top of the FRI queue and stores them in ctx[MM_FRI_STEP_VALUES:].

      Returns
        friQueueHead - friQueueHead_ + 0x60  * (# elements that were taken from the queue).
        cosetIdx - the start index of the coset that was gathered.
        cosetOffset_ - the xInv field element that corresponds to cosetIdx.
    */
    function gatherCosetInputs(
        uint256 channelPtr, uint256 friCtx, uint256 friQueueHead_, uint256 cosetSize)
        internal pure returns (uint256 friQueueHead, uint256 cosetIdx, uint256 cosetOffset_) {

        uint256 evaluationsOnCosetPtr = friCtx + FRI_CTX_TO_COSET_EVALUATIONS_OFFSET;
        uint256 friGroupPtr = friCtx + FRI_CTX_TO_FRI_GROUP_OFFSET;

        friQueueHead = friQueueHead_;
        assembly {
            let queueItemIdx := mload(friQueueHead)
            // The coset index is represented by the most significant bits of the queue item index.
            cosetIdx := and(queueItemIdx, not(sub(cosetSize, 1)))
            let nextCosetIdx := add(cosetIdx, cosetSize)
            let PRIME := 0x30000003000000010000000000000001

            // Get the algebraic coset offset:
            // I.e. given c*g^(-k) compute c, where
            //      g is the generator of the coset group.
            //      k is bitReverse(offsetWithinCoset, log2(cosetSize)).
            //
            // To do this we multiply the algebraic coset offset at the top of the queue (c*g^(-k))
            // by the group element that corresponds to the index inside the coset (g^k).
            cosetOffset_ := mulmod(
                /*(c*g^(-k)*/ mload(add(friQueueHead, 0x40)),
                /*(g^k)*/     mload(add(friGroupPtr,
                                        mul(/*offsetWithinCoset*/sub(queueItemIdx, cosetIdx),
                                            0x20))),
                PRIME)

            let proofPtr := mload(channelPtr)

            for { let index := cosetIdx } lt(index, nextCosetIdx) { index := add(index, 1) } {
                // Inline channel operation:
                // Assume we are going to read the next element from the proof.
                // If this is not the case add(proofPtr, 0x20) will be reverted.
                let fieldElementPtr := proofPtr
                proofPtr := add(proofPtr, 0x20)

                // Load the next index from the queue and check if it is our sibling.
                if eq(index, queueItemIdx) {
                    // Take element from the queue rather than from the proof
                    // and convert it back to Montgomery form for Merkle verification.
                    fieldElementPtr := add(friQueueHead, 0x20)

                    // Revert the read from proof.
                    proofPtr := sub(proofPtr, 0x20)

                    // Reading the next index here is safe due to the
                    // delimiter after the queries.
                    friQueueHead := add(friQueueHead, 0x60)
                    queueItemIdx := mload(friQueueHead)
                }

                // Note that we apply the modulo operation to convert the field elements we read
                // from the proof to canonical representation (in the range [0, PRIME - 1]).
                mstore(evaluationsOnCosetPtr, mod(mload(fieldElementPtr), PRIME))
                evaluationsOnCosetPtr := add(evaluationsOnCosetPtr, 0x20)
            }

            mstore(channelPtr, proofPtr)
        }
    }

    /*
      Returns the bit reversal of num assuming it has the given number of bits.
      For example, if we have numberOfBits = 6 and num = (0b)1101 == (0b)001101,
      the function will return (0b)101100.
    */
    function bitReverse(uint256 num, uint256 numberOfBits)
    internal pure
        returns(uint256 numReversed)
    {
        assert((numberOfBits == 256) || (num < 2 ** numberOfBits));
        uint256 n = num;
        uint256 r = 0;
        for (uint256 k = 0; k < numberOfBits; k++) {
            r = (r * 2) | (n % 2);
            n = n / 2;
        }
        return r;
    }

    /*
      Initializes the FRI group and half inv group in the FRI context.
    */
    function initFriGroups(uint256 friCtx) internal {
        uint256 friGroupPtr = friCtx + FRI_CTX_TO_FRI_GROUP_OFFSET;
        uint256 friHalfInvGroupPtr = friCtx + FRI_CTX_TO_FRI_HALF_INV_GROUP_OFFSET;

        // FRI_GROUP_GEN is the coset generator.
        // Raising it to the (MAX_COSET_SIZE - 1) power gives us the inverse.
        uint256 genFriGroup = FRI_GROUP_GEN;

        uint256 genFriGroupInv = fpow(genFriGroup, (MAX_COSET_SIZE - 1));

        uint256 lastVal = ONE_VAL;
        uint256 lastValInv = ONE_VAL;
        uint256 prime = PrimeFieldElement6.K_MODULUS;
        assembly {
            // ctx[mmHalfFriInvGroup + 0] = ONE_VAL;
            mstore(friHalfInvGroupPtr, lastValInv)
            // ctx[mmFriGroup + 0] = ONE_VAL;
            mstore(friGroupPtr, lastVal)
            // ctx[mmFriGroup + 1] = fsub(0, ONE_VAL);
            mstore(add(friGroupPtr, 0x20), sub(prime, lastVal))
        }

        // To compute [1, -1 (== g^n/2), g^n/4, -g^n/4, ...]
        // we compute half the elements and derive the rest using negation.
        uint256 halfCosetSize = MAX_COSET_SIZE / 2;
        for (uint256 i = 1; i < halfCosetSize; i++) {
            lastVal = fmul(lastVal, genFriGroup);
            lastValInv = fmul(lastValInv, genFriGroupInv);
            uint256 idx = bitReverse(i, FRI_MAX_FRI_STEP-1);

            assembly {
                // ctx[mmHalfFriInvGroup + idx] = lastValInv;
                mstore(add(friHalfInvGroupPtr, mul(idx, 0x20)), lastValInv)
                // ctx[mmFriGroup + 2*idx] = lastVal;
                mstore(add(friGroupPtr, mul(idx, 0x40)), lastVal)
                // ctx[mmFriGroup + 2*idx + 1] = fsub(0, lastVal);
                mstore(add(friGroupPtr, add(mul(idx, 0x40), 0x20)), sub(prime, lastVal))
            }
        }
    }

    /*
      Operates on the coset of size friFoldedCosetSize that start at index.

      It produces 3 outputs:
        1. The field elements that result from doing FRI reductions on the coset.
        2. The pointInv elements for the location that corresponds to the first output.
        3. The root of a Merkle tree for the input layer.

      The input is read either from the queue or from the proof depending on data availability.
      Since the function reads from the queue it returns an updated head pointer.
    */
    function doFriSteps(
        uint256 friCtx, uint256 friQueueTail, uint256 cosetOffset_, uint256 friEvalPoint,
        uint256 friCosetSize, uint256 index, uint256 merkleQueuePtr)
        internal pure {
        uint256 friValue;

        uint256 evaluationsOnCosetPtr = friCtx + FRI_CTX_TO_COSET_EVALUATIONS_OFFSET;
        uint256 friHalfInvGroupPtr = friCtx + FRI_CTX_TO_FRI_HALF_INV_GROUP_OFFSET;

        // Compare to expected FRI step sizes in order of likelihood, step size 3 being most common.
        if (friCosetSize == 8) {
            (friValue, cosetOffset_) = do3FriSteps(
                friHalfInvGroupPtr, evaluationsOnCosetPtr, cosetOffset_, friEvalPoint);
        } else if (friCosetSize == 4) {
            (friValue, cosetOffset_) = do2FriSteps(
                friHalfInvGroupPtr, evaluationsOnCosetPtr, cosetOffset_, friEvalPoint);
        } else if (friCosetSize == 16) {
            (friValue, cosetOffset_) = do4FriSteps(
                friHalfInvGroupPtr, evaluationsOnCosetPtr, cosetOffset_, friEvalPoint);
        } else {
            require(false, "Only step sizes of 2, 3 or 4 are supported.");
        }

        uint256 lhashMask = getHashMask();
        assembly {
            let indexInNextStep := div(index, friCosetSize)
            mstore(merkleQueuePtr, indexInNextStep)
            mstore(add(merkleQueuePtr, 0x20), and(lhashMask, keccak256(evaluationsOnCosetPtr,
                                                                          mul(0x20,friCosetSize))))

            mstore(friQueueTail, indexInNextStep)
            mstore(add(friQueueTail, 0x20), friValue)
            mstore(add(friQueueTail, 0x40), cosetOffset_)
        }
    }

    /*
      Computes the FRI step with eta = log2(friCosetSize) for all the live queries.
      The input and output data is given in array of triplets:
          (query index, FRI value, FRI inversed point)
      in the address friQueuePtr (which is &ctx[mmFriQueue:]).

      The function returns the number of live queries remaining after computing the FRI step.

      The number of live queries decreases whenever multiple query points in the same
      coset are reduced to a single query in the next FRI layer.

      As the function computes the next layer it also collects that data from
      the previous layer for Merkle verification.
    */
    function computeNextLayer(
        uint256 channelPtr, uint256 friQueuePtr, uint256 merkleQueuePtr, uint256 nQueries,
        uint256 friEvalPoint, uint256 friCosetSize, uint256 friCtx)
        internal pure returns (uint256 nLiveQueries) {
        uint256 merkleQueueTail = merkleQueuePtr;
        uint256 friQueueHead = friQueuePtr;
        uint256 friQueueTail = friQueuePtr;
        uint256 friQueueEnd = friQueueHead + (0x60 * nQueries);

        do {
            uint256 cosetOffset;
            uint256 index;
            (friQueueHead, index, cosetOffset) = gatherCosetInputs(
                channelPtr, friCtx, friQueueHead, friCosetSize);

            doFriSteps(
                friCtx, friQueueTail, cosetOffset, friEvalPoint, friCosetSize, index,
                merkleQueueTail);

            merkleQueueTail += 0x40;
            friQueueTail += 0x60;
        } while (friQueueHead < friQueueEnd);
        return (friQueueTail - friQueuePtr) / 0x60;
    }

}

// File: HornerEvaluator.sol



pragma solidity ^0.5.2;

import "./PrimeFieldElement6.sol";

contract HornerEvaluator is PrimeFieldElement6 {
    /*
      Computes the evaluation of a polynomial f(x) = sum(a_i * x^i) on the given point.
      The coefficients of the polynomial are given in
        a_0 = coefsStart[0], ..., a_{n-1} = coefsStart[n - 1]
      where n = nCoefs = friLastLayerDegBound. Note that coefsStart is not actually an array but
      a direct pointer.
      The function requires that n is divisible by 8.
    */
    function hornerEval(uint256 coefsStart, uint256 point, uint256 nCoefs)
        internal pure
        returns (uint256) {
        uint256 result = 0;
        uint256 prime = PrimeFieldElement6.K_MODULUS;

        require(nCoefs % 8 == 0, "Number of polynomial coefficients must be divisible by 8");
        require(nCoefs < 4096, "No more than 4096 coefficients are supported");

        assembly {
            let coefsPtr := add(coefsStart, mul(nCoefs, 0x20))
            for { } gt(coefsPtr, coefsStart) { } {
                // Reduce coefsPtr by 8 field elements.
                coefsPtr := sub(coefsPtr, 0x100)

                // Apply 4 Horner steps (result := result * point + coef).
                result :=
                    add(mload(add(coefsPtr, 0x80)), mulmod(
                    add(mload(add(coefsPtr, 0xa0)), mulmod(
                    add(mload(add(coefsPtr, 0xc0)), mulmod(
                    add(mload(add(coefsPtr, 0xe0)), mulmod(
                        result,
                    point, prime)),
                    point, prime)),
                    point, prime)),
                    point, prime))

                // Apply 4 additional Horner steps.
                result :=
                    add(mload(coefsPtr), mulmod(
                    add(mload(add(coefsPtr, 0x20)), mulmod(
                    add(mload(add(coefsPtr, 0x40)), mulmod(
                    add(mload(add(coefsPtr, 0x60)), mulmod(
                        result,
                    point, prime)),
                    point, prime)),
                    point, prime)),
                    point, prime))
            }
        }

        // Since the last operation was "add" (instead of "addmod"), we need to take result % prime.
        return result % prime;
    }
}

// File: IFactRegistry.sol



pragma solidity ^0.5.2;

/*
  The Fact Registry design pattern is a way to separate cryptographic verification from the
  business logic of the contract flow.

  A fact registry holds a hash table of verified "facts" which are represented by a hash of claims
  that the registry hash check and found valid. This table may be queried by accessing the
  isValid() function of the registry with a given hash.

  In addition, each fact registry exposes a registry specific function for submitting new claims
  together with their proofs. The information submitted varies from one registry to the other
  depending of the type of fact requiring verification.

  For further reading on the Fact Registry design pattern see this
  `StarkWare blog post <https://medium.com/starkware/the-fact-registry-a64aafb598b6>`_.
*/
contract IFactRegistry {
    /*
      Returns true if the given fact was previously registered in the contract.
    */
    function isValid(bytes32 fact)
        external view
        returns(bool);
}

// File: IMerkleVerifier.sol



pragma solidity ^0.5.2;

contract IMerkleVerifier {
    uint256 constant internal MAX_N_MERKLE_VERIFIER_QUERIES =  128;

    function verify(
        uint256 channelPtr,
        uint256 queuePtr,
        bytes32 root,
        uint256 n)
        internal view
        returns (bytes32 hash);
}

// File: IQueryableFactRegistry.sol



pragma solidity ^0.5.2;

import "./IFactRegistry.sol";

/*
  Extends the IFactRegistry interface with a query method that indicates
  whether the fact registry has successfully registered any fact or is still empty of such facts.
*/
contract IQueryableFactRegistry is IFactRegistry {

    /*
      Returns true if at least one fact has been registered.
    */
    function hasRegisteredFact()
        external view
        returns(bool);

}

// File: IStarkVerifier.sol



pragma solidity ^0.5.2;

contract IStarkVerifier {

    function verifyProof(
        uint256[] memory proofParams,
        uint256[] memory proof,
        uint256[] memory publicInput
    )
        internal;
}

// File: MemoryAccessUtils.sol



pragma solidity ^0.5.2;

import "./MemoryMap.sol";

contract MemoryAccessUtils is MemoryMap {
    function getPtr(uint256[] memory ctx, uint256 offset)
        internal pure
        returns (uint256) {
        uint256 ctxPtr;
        require(offset < MM_CONTEXT_SIZE, "Overflow protection failed");
        assembly {
            ctxPtr := add(ctx, 0x20)
        }
        return ctxPtr + offset * 0x20;
    }

    function getProofPtr(uint256[] memory proof)
        internal pure
        returns (uint256)
    {
        uint256 proofPtr;
        assembly {
            proofPtr := proof
        }
        return proofPtr;
    }

    function getChannelPtr(uint256[] memory ctx)
        internal pure
        returns (uint256) {
        uint256 ctxPtr;
        assembly {
            ctxPtr := add(ctx, 0x20)
        }
        return ctxPtr + MM_CHANNEL * 0x20;
    }

    function getQueries(uint256[] memory ctx)
        internal pure
        returns (uint256[] memory)
    {
        uint256[] memory queries;
        // Dynamic array holds length followed by values.
        uint256 offset = 0x20 + 0x20*MM_N_UNIQUE_QUERIES;
        assembly {
            queries := add(ctx, offset)
        }
        return queries;
    }

    function getMerkleQueuePtr(uint256[] memory ctx)
        internal pure
        returns (uint256)
    {
        return getPtr(ctx, MM_MERKLE_QUEUE);
    }

    function getFriSteps(uint256[] memory ctx)
        internal pure
        returns (uint256[] memory friSteps)
    {
        uint256 friStepsPtr = getPtr(ctx, MM_FRI_STEPS_PTR);
        assembly {
            friSteps := mload(friStepsPtr)
        }
    }
}

// File: MemoryMap.sol



pragma solidity ^0.5.2;

contract MemoryMap {
    /*
      We store the state of the verifer in a contiguous chunk of memory.
      The offsets of the different fields are listed below.
      E.g. The offset of the i'th hash is [mm_hashes + i].
    */
    uint256 constant internal CHANNEL_STATE_SIZE = 3;
    uint256 constant internal MAX_N_QUERIES =  48;
    uint256 constant internal FRI_QUEUE_SIZE = MAX_N_QUERIES;

    uint256 constant internal MAX_SUPPORTED_MAX_FRI_STEP = 4;

    uint256 constant internal MM_EVAL_DOMAIN_SIZE =                          0x0;
    uint256 constant internal MM_BLOW_UP_FACTOR =                            0x1;
    uint256 constant internal MM_LOG_EVAL_DOMAIN_SIZE =                      0x2;
    uint256 constant internal MM_PROOF_OF_WORK_BITS =                        0x3;
    uint256 constant internal MM_EVAL_DOMAIN_GENERATOR =                     0x4;
    uint256 constant internal MM_PUBLIC_INPUT_PTR =                          0x5;
    uint256 constant internal MM_TRACE_COMMITMENT =                          0x6;
    uint256 constant internal MM_OODS_COMMITMENT =                           0x7;
    uint256 constant internal MM_N_UNIQUE_QUERIES =                          0x8;
    uint256 constant internal MM_CHANNEL =                                   0x9; // uint256[3]
    uint256 constant internal MM_MERKLE_QUEUE =                              0xc; // uint256[96]
    uint256 constant internal MM_FRI_QUEUE =                                0x6c; // uint256[144]
    uint256 constant internal MM_FRI_QUERIES_DELIMITER =                    0xfc;
    uint256 constant internal MM_FRI_CTX =                                  0xfd; // uint256[40]
    uint256 constant internal MM_FRI_STEPS_PTR =                           0x125;
    uint256 constant internal MM_FRI_EVAL_POINTS =                         0x126; // uint256[10]
    uint256 constant internal MM_FRI_COMMITMENTS =                         0x130; // uint256[10]
    uint256 constant internal MM_FRI_LAST_LAYER_DEG_BOUND =                0x13a;
    uint256 constant internal MM_FRI_LAST_LAYER_PTR =                      0x13b;
    uint256 constant internal MM_CONSTRAINT_POLY_ARGS_START =              0x13c;
    uint256 constant internal MM_PERIODIC_COLUMN__CONSTS0_A =              0x13c;
    uint256 constant internal MM_PERIODIC_COLUMN__CONSTS1_A =              0x13d;
    uint256 constant internal MM_PERIODIC_COLUMN__CONSTS2_A =              0x13e;
    uint256 constant internal MM_PERIODIC_COLUMN__CONSTS3_A =              0x13f;
    uint256 constant internal MM_PERIODIC_COLUMN__CONSTS4_A =              0x140;
    uint256 constant internal MM_PERIODIC_COLUMN__CONSTS5_A =              0x141;
    uint256 constant internal MM_PERIODIC_COLUMN__CONSTS6_A =              0x142;
    uint256 constant internal MM_PERIODIC_COLUMN__CONSTS7_A =              0x143;
    uint256 constant internal MM_PERIODIC_COLUMN__CONSTS8_A =              0x144;
    uint256 constant internal MM_PERIODIC_COLUMN__CONSTS9_A =              0x145;
    uint256 constant internal MM_PERIODIC_COLUMN__CONSTS0_B =              0x146;
    uint256 constant internal MM_PERIODIC_COLUMN__CONSTS1_B =              0x147;
    uint256 constant internal MM_PERIODIC_COLUMN__CONSTS2_B =              0x148;
    uint256 constant internal MM_PERIODIC_COLUMN__CONSTS3_B =              0x149;
    uint256 constant internal MM_PERIODIC_COLUMN__CONSTS4_B =              0x14a;
    uint256 constant internal MM_PERIODIC_COLUMN__CONSTS5_B =              0x14b;
    uint256 constant internal MM_PERIODIC_COLUMN__CONSTS6_B =              0x14c;
    uint256 constant internal MM_PERIODIC_COLUMN__CONSTS7_B =              0x14d;
    uint256 constant internal MM_PERIODIC_COLUMN__CONSTS8_B =              0x14e;
    uint256 constant internal MM_PERIODIC_COLUMN__CONSTS9_B =              0x14f;
    uint256 constant internal MM_MAT00 =                                   0x150;
    uint256 constant internal MM_MAT01 =                                   0x151;
    uint256 constant internal MM_TRACE_LENGTH =                            0x152;
    uint256 constant internal MM_MAT10 =                                   0x153;
    uint256 constant internal MM_MAT11 =                                   0x154;
    uint256 constant internal MM_INPUT_VALUE_A =                           0x155;
    uint256 constant internal MM_OUTPUT_VALUE_A =                          0x156;
    uint256 constant internal MM_INPUT_VALUE_B =                           0x157;
    uint256 constant internal MM_OUTPUT_VALUE_B =                          0x158;
    uint256 constant internal MM_TRACE_GENERATOR =                         0x159;
    uint256 constant internal MM_OODS_POINT =                              0x15a;
    uint256 constant internal MM_COEFFICIENTS =                            0x15b; // uint256[48]
    uint256 constant internal MM_OODS_VALUES =                             0x18b; // uint256[22]
    uint256 constant internal MM_CONSTRAINT_POLY_ARGS_END =                0x1a1;
    uint256 constant internal MM_COMPOSITION_OODS_VALUES =                 0x1a1; // uint256[2]
    uint256 constant internal MM_OODS_EVAL_POINTS =                        0x1a3; // uint256[48]
    uint256 constant internal MM_OODS_COEFFICIENTS =                       0x1d3; // uint256[24]
    uint256 constant internal MM_TRACE_QUERY_RESPONSES =                   0x1eb; // uint256[960]
    uint256 constant internal MM_COMPOSITION_QUERY_RESPONSES =             0x5ab; // uint256[96]
    uint256 constant internal MM_CONTEXT_SIZE =                            0x60b;
}

// File: MerkleVerifier.sol



pragma solidity ^0.5.2;

import "./IMerkleVerifier.sol";

contract MerkleVerifier is IMerkleVerifier {

    function getHashMask() internal pure returns(uint256) {
        // Default implementation.
        return 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000000;
    }

    /*
      Verifies a Merkle tree decommitment for n leaves in a Merkle tree with N leaves.

      The inputs data sits in the queue at queuePtr.
      Each slot in the queue contains a 32 bytes leaf index and a 32 byte leaf value.
      The indices need to be in the range [N..2*N-1] and strictly incrementing.
      Decommitments are read from the channel in the ctx.

      The input data is destroyed during verification.
    */
    function verify(
        uint256 channelPtr,
        uint256 queuePtr,
        bytes32 root,
        uint256 n)
        internal view
        returns (bytes32 hash)
    {
        uint256 lhashMask = getHashMask();
        require(n <= MAX_N_MERKLE_VERIFIER_QUERIES, "TOO_MANY_MERKLE_QUERIES");

        assembly {
            // queuePtr + i * 0x40 gives the i'th index in the queue.
            // hashesPtr + i * 0x40 gives the i'th hash in the queue.
            let hashesPtr := add(queuePtr, 0x20)
            let queueSize := mul(n, 0x40)
            let slotSize := 0x40

            // The items are in slots [0, n-1].
            let rdIdx := 0
            let wrIdx := 0 // = n % n.

            // Iterate the queue until we hit the root.
            let index := mload(add(rdIdx, queuePtr))
            let proofPtr := mload(channelPtr)

            // while(index > 1).
            for { } gt(index, 1) { } {
                let siblingIndex := xor(index, 1)
                // sibblingOffset := 0x20 * lsb(siblingIndex).
                let sibblingOffset := mulmod(siblingIndex, 0x20, 0x40)

                // Store the hash corresponding to index in the correct slot.
                // 0 if index is even and 0x20 if index is odd.
                // The hash of the sibling will be written to the other slot.
                mstore(xor(0x20, sibblingOffset), mload(add(rdIdx, hashesPtr)))
                rdIdx := addmod(rdIdx, slotSize, queueSize)

                // Inline channel operation:
                // Assume we are going to read a new hash from the proof.
                // If this is not the case add(proofPtr, 0x20) will be reverted.
                let newHashPtr := proofPtr
                proofPtr := add(proofPtr, 0x20)

                // Push index/2 into the queue, before reading the next index.
                // The order is important, as otherwise we may try to read from an empty queue (in
                // the case where we are working on one item).
                // wrIdx will be updated after writing the relevant hash to the queue.
                mstore(add(wrIdx, queuePtr), div(index, 2))

                // Load the next index from the queue and check if it is our sibling.
                index := mload(add(rdIdx, queuePtr))
                if eq(index, siblingIndex) {
                    // Take sibling from queue rather than from proof.
                    newHashPtr := add(rdIdx, hashesPtr)
                    // Revert reading from proof.
                    proofPtr := sub(proofPtr, 0x20)
                    rdIdx := addmod(rdIdx, slotSize, queueSize)

                    // Index was consumed, read the next one.
                    // Note that the queue can't be empty at this point.
                    // The index of the parent of the current node was already pushed into the
                    // queue, and the parent is never the sibling.
                    index := mload(add(rdIdx, queuePtr))
                }

                mstore(sibblingOffset, mload(newHashPtr))

                // Push the new hash to the end of the queue.
                mstore(add(wrIdx, hashesPtr), and(lhashMask, keccak256(0x00, 0x40)))
                wrIdx := addmod(wrIdx, slotSize, queueSize)
            }
            hash := mload(add(rdIdx, hashesPtr))

            // Update the proof pointer in the context.
            mstore(channelPtr, proofPtr)
        }
        // emit LogBool(hash == root);
        require(hash == root, "INVALID_MERKLE_PROOF");
    }
}

// File: MimcConstraintPoly.sol



// ---------- The following code was auto-generated. PLEASE DO NOT EDIT. ----------
pragma solidity ^0.5.2;

contract MimcConstraintPoly {
    // The Memory map during the execution of this contract is as follows:
    // [0x0, 0x20) - periodic_column/consts0_a.
    // [0x20, 0x40) - periodic_column/consts1_a.
    // [0x40, 0x60) - periodic_column/consts2_a.
    // [0x60, 0x80) - periodic_column/consts3_a.
    // [0x80, 0xa0) - periodic_column/consts4_a.
    // [0xa0, 0xc0) - periodic_column/consts5_a.
    // [0xc0, 0xe0) - periodic_column/consts6_a.
    // [0xe0, 0x100) - periodic_column/consts7_a.
    // [0x100, 0x120) - periodic_column/consts8_a.
    // [0x120, 0x140) - periodic_column/consts9_a.
    // [0x140, 0x160) - periodic_column/consts0_b.
    // [0x160, 0x180) - periodic_column/consts1_b.
    // [0x180, 0x1a0) - periodic_column/consts2_b.
    // [0x1a0, 0x1c0) - periodic_column/consts3_b.
    // [0x1c0, 0x1e0) - periodic_column/consts4_b.
    // [0x1e0, 0x200) - periodic_column/consts5_b.
    // [0x200, 0x220) - periodic_column/consts6_b.
    // [0x220, 0x240) - periodic_column/consts7_b.
    // [0x240, 0x260) - periodic_column/consts8_b.
    // [0x260, 0x280) - periodic_column/consts9_b.
    // [0x280, 0x2a0) - mat00.
    // [0x2a0, 0x2c0) - mat01.
    // [0x2c0, 0x2e0) - trace_length.
    // [0x2e0, 0x300) - mat10.
    // [0x300, 0x320) - mat11.
    // [0x320, 0x340) - input_value_a.
    // [0x340, 0x360) - output_value_a.
    // [0x360, 0x380) - input_value_b.
    // [0x380, 0x3a0) - output_value_b.
    // [0x3a0, 0x3c0) - trace_generator.
    // [0x3c0, 0x3e0) - oods_point.
    // [0x3e0, 0x9e0) - coefficients.
    // [0x9e0, 0xca0) - oods_values.
    // ----------------------- end of input data - -------------------------
    // [0xca0, 0xcc0) - composition_degree_bound.
    // [0xcc0, 0xce0) - intermediate_value/after_lin_transform0_a_0.
    // [0xce0, 0xd00) - intermediate_value/after_lin_transform0_b_0.
    // [0xd00, 0xd20) - intermediate_value/after_lin_transform1_a_0.
    // [0xd20, 0xd40) - intermediate_value/after_lin_transform1_b_0.
    // [0xd40, 0xd60) - intermediate_value/after_lin_transform2_a_0.
    // [0xd60, 0xd80) - intermediate_value/after_lin_transform2_b_0.
    // [0xd80, 0xda0) - intermediate_value/after_lin_transform3_a_0.
    // [0xda0, 0xdc0) - intermediate_value/after_lin_transform3_b_0.
    // [0xdc0, 0xde0) - intermediate_value/after_lin_transform4_a_0.
    // [0xde0, 0xe00) - intermediate_value/after_lin_transform4_b_0.
    // [0xe00, 0xe20) - intermediate_value/after_lin_transform5_a_0.
    // [0xe20, 0xe40) - intermediate_value/after_lin_transform5_b_0.
    // [0xe40, 0xe60) - intermediate_value/after_lin_transform6_a_0.
    // [0xe60, 0xe80) - intermediate_value/after_lin_transform6_b_0.
    // [0xe80, 0xea0) - intermediate_value/after_lin_transform7_a_0.
    // [0xea0, 0xec0) - intermediate_value/after_lin_transform7_b_0.
    // [0xec0, 0xee0) - intermediate_value/after_lin_transform8_a_0.
    // [0xee0, 0xf00) - intermediate_value/after_lin_transform8_b_0.
    // [0xf00, 0xf20) - intermediate_value/after_lin_transform9_a_0.
    // [0xf20, 0xf40) - intermediate_value/after_lin_transform9_b_0.
    // [0xf40, 0xf80) - expmods.
    // [0xf80, 0xfe0) - denominator_invs.
    // [0xfe0, 0x1040) - denominators.
    // [0x1040, 0x1060) - numerators.
    // [0x1060, 0x10c0) - adjustments.
    // [0x10c0, 0x1180) - expmod_context.

    function() external {
        uint256 res;
        assembly {
            let PRIME := 0x30000003000000010000000000000001
            // Copy input from calldata to memory.
            calldatacopy(0x0, 0x0, /*Input data size*/ 0xca0)
            let point := /*oods_point*/ mload(0x3c0)
            // Initialize composition_degree_bound to 2 * trace_length.
            mstore(0xca0, mul(2, /*trace_length*/ mload(0x2c0)))
            function expmod(base, exponent, modulus) -> res {
              let p := /*expmod_context*/ 0x10c0
              mstore(p, 0x20)                 // Length of Base.
              mstore(add(p, 0x20), 0x20)      // Length of Exponent.
              mstore(add(p, 0x40), 0x20)      // Length of Modulus.
              mstore(add(p, 0x60), base)      // Base.
              mstore(add(p, 0x80), exponent)  // Exponent.
              mstore(add(p, 0xa0), modulus)   // Modulus.
              // Call modexp precompile.
              if iszero(staticcall(not(0), 0x05, p, 0xc0, p, 0x20)) {
                revert(0, 0)
              }
              res := mload(p)
            }

            function degreeAdjustment(compositionPolynomialDegreeBound, constraintDegree, numeratorDegree,
                                       denominatorDegree) -> res {
              res := sub(sub(compositionPolynomialDegreeBound, 1),
                         sub(add(constraintDegree, numeratorDegree), denominatorDegree))
            }

            {
              // Prepare expmods for denominators and numerators.

              // expmods[0] = point^trace_length.
              mstore(0xf40, expmod(point, /*trace_length*/ mload(0x2c0), PRIME))

              // expmods[1] = trace_generator^(trace_length - 1).
              mstore(0xf60, expmod(/*trace_generator*/ mload(0x3a0), sub(/*trace_length*/ mload(0x2c0), 1), PRIME))

            }

            {
              // Prepare denominators for batch inverse.

              // Denominator for constraints: 'step0_a', 'step0_b', 'step1_a', 'step1_b', 'step2_a', 'step2_b', 'step3_a', 'step3_b', 'step4_a', 'step4_b', 'step5_a', 'step5_b', 'step6_a', 'step6_b', 'step7_a', 'step7_b', 'step8_a', 'step8_b', 'step9_a', 'step9_b'.
              // denominators[0] = point^trace_length - 1.
              mstore(0xfe0,
                     addmod(/*point^trace_length*/ mload(0xf40), sub(PRIME, 1), PRIME))

              // Denominator for constraints: 'input_a', 'input_b'.
              // denominators[1] = point - 1.
              mstore(0x1000,
                     addmod(point, sub(PRIME, 1), PRIME))

              // Denominator for constraints: 'output_a', 'output_b'.
              // denominators[2] = point - trace_generator^(trace_length - 1).
              mstore(0x1020,
                     addmod(point, sub(PRIME, /*trace_generator^(trace_length - 1)*/ mload(0xf60)), PRIME))

            }

            {
              // Compute the inverses of the denominators into denominatorInvs using batch inverse.

              // Start by computing the cumulative product.
              // Let (d_0, d_1, d_2, ..., d_{n-1}) be the values in denominators. After this loop
              // denominatorInvs will be (1, d_0, d_0 * d_1, ...) and prod will contain the value of
              // d_0 * ... * d_{n-1}.
              // Compute the offset between the partialProducts array and the input values array.
              let productsToValuesOffset := 0x60
              let prod := 1
              let partialProductEndPtr := 0xfe0
              for { let partialProductPtr := 0xf80 }
                  lt(partialProductPtr, partialProductEndPtr)
                  { partialProductPtr := add(partialProductPtr, 0x20) } {
                  mstore(partialProductPtr, prod)
                  // prod *= d_{i}.
                  prod := mulmod(prod,
                                 mload(add(partialProductPtr, productsToValuesOffset)),
                                 PRIME)
              }

              let firstPartialProductPtr := 0xf80
              // Compute the inverse of the product.
              let prodInv := expmod(prod, sub(PRIME, 2), PRIME)

              if eq(prodInv, 0) {
                  // Solidity generates reverts with reason that look as follows:
                  // 1. 4 bytes with the constant 0x08c379a0 (== Keccak256(b'Error(string)')[:4]).
                  // 2. 32 bytes offset bytes (always 0x20 as far as i can tell).
                  // 3. 32 bytes with the length of the revert reason.
                  // 4. Revert reason string.

                  mstore(0, 0x08c379a000000000000000000000000000000000000000000000000000000000)
                  mstore(0x4, 0x20)
                  mstore(0x24, 0x1e)
                  mstore(0x44, "Batch inverse product is zero.")
                  revert(0, 0x62)
              }

              // Compute the inverses.
              // Loop over denominator_invs in reverse order.
              // currentPartialProductPtr is initialized to one past the end.
              let currentPartialProductPtr := 0xfe0
              for { } gt(currentPartialProductPtr, firstPartialProductPtr) { } {
                  currentPartialProductPtr := sub(currentPartialProductPtr, 0x20)
                  // Store 1/d_{i} = (d_0 * ... * d_{i-1}) * 1/(d_0 * ... * d_{i}).
                  mstore(currentPartialProductPtr,
                         mulmod(mload(currentPartialProductPtr), prodInv, PRIME))
                  // Update prodInv to be 1/(d_0 * ... * d_{i-1}) by multiplying by d_i.
                  prodInv := mulmod(prodInv,
                                     mload(add(currentPartialProductPtr, productsToValuesOffset)),
                                     PRIME)
              }
            }

            {
              // Compute numerators and adjustment polynomials.

              // Numerator for constraints 'step9_a', 'step9_b'.
              // numerators[0] = point - trace_generator^(trace_length - 1).
              mstore(0x1040,
                     addmod(point, sub(PRIME, /*trace_generator^(trace_length - 1)*/ mload(0xf60)), PRIME))

              // Adjustment polynomial for constraints 'step0_a', 'step0_b', 'step1_a', 'step1_b', 'step2_a', 'step2_b', 'step3_a', 'step3_b', 'step4_a', 'step4_b', 'step5_a', 'step5_b', 'step6_a', 'step6_b', 'step7_a', 'step7_b', 'step8_a', 'step8_b'.
              // adjustments[0] = point^degreeAdjustment(composition_degree_bound, 3 * (trace_length - 1), 0, trace_length).
              mstore(0x1060,
                     expmod(point, degreeAdjustment(/*composition_degree_bound*/ mload(0xca0), mul(3, sub(/*trace_length*/ mload(0x2c0), 1)), 0, /*trace_length*/ mload(0x2c0)), PRIME))

              // Adjustment polynomial for constraints 'step9_a', 'step9_b'.
              // adjustments[1] = point^degreeAdjustment(composition_degree_bound, 3 * (trace_length - 1), 1, trace_length).
              mstore(0x1080,
                     expmod(point, degreeAdjustment(/*composition_degree_bound*/ mload(0xca0), mul(3, sub(/*trace_length*/ mload(0x2c0), 1)), 1, /*trace_length*/ mload(0x2c0)), PRIME))

              // Adjustment polynomial for constraints 'input_a', 'output_a', 'input_b', 'output_b'.
              // adjustments[2] = point^degreeAdjustment(composition_degree_bound, trace_length - 1, 0, 1).
              mstore(0x10a0,
                     expmod(point, degreeAdjustment(/*composition_degree_bound*/ mload(0xca0), sub(/*trace_length*/ mload(0x2c0), 1), 0, 1), PRIME))

            }

            {
              // Compute the result of the composition polynomial.

              {
              // after_lin_transform0_a_0 = mat00 * (column0_row0 - consts0_a) + mat01 * (column10_row0 - consts0_b).
              let val := addmod(
                mulmod(
                  /*mat00*/ mload(0x280),
                  addmod(
                    /*column0_row0*/ mload(0x9e0),
                    sub(PRIME, /*periodic_column/consts0_a*/ mload(0x0)),
                    PRIME),
                  PRIME),
                mulmod(
                  /*mat01*/ mload(0x2a0),
                  addmod(
                    /*column10_row0*/ mload(0xb40),
                    sub(PRIME, /*periodic_column/consts0_b*/ mload(0x140)),
                    PRIME),
                  PRIME),
                PRIME)
              mstore(0xcc0, val)
              }


              {
              // after_lin_transform0_b_0 = mat10 * (column0_row0 - consts0_a) + mat11 * (column10_row0 - consts0_b).
              let val := addmod(
                mulmod(
                  /*mat10*/ mload(0x2e0),
                  addmod(
                    /*column0_row0*/ mload(0x9e0),
                    sub(PRIME, /*periodic_column/consts0_a*/ mload(0x0)),
                    PRIME),
                  PRIME),
                mulmod(
                  /*mat11*/ mload(0x300),
                  addmod(
                    /*column10_row0*/ mload(0xb40),
                    sub(PRIME, /*periodic_column/consts0_b*/ mload(0x140)),
                    PRIME),
                  PRIME),
                PRIME)
              mstore(0xce0, val)
              }


              {
              // after_lin_transform1_a_0 = mat00 * (column1_row0 - consts1_a) + mat01 * (column11_row0 - consts1_b).
              let val := addmod(
                mulmod(
                  /*mat00*/ mload(0x280),
                  addmod(
                    /*column1_row0*/ mload(0xa20),
                    sub(PRIME, /*periodic_column/consts1_a*/ mload(0x20)),
                    PRIME),
                  PRIME),
                mulmod(
                  /*mat01*/ mload(0x2a0),
                  addmod(
                    /*column11_row0*/ mload(0xb80),
                    sub(PRIME, /*periodic_column/consts1_b*/ mload(0x160)),
                    PRIME),
                  PRIME),
                PRIME)
              mstore(0xd00, val)
              }


              {
              // after_lin_transform1_b_0 = mat10 * (column1_row0 - consts1_a) + mat11 * (column11_row0 - consts1_b).
              let val := addmod(
                mulmod(
                  /*mat10*/ mload(0x2e0),
                  addmod(
                    /*column1_row0*/ mload(0xa20),
                    sub(PRIME, /*periodic_column/consts1_a*/ mload(0x20)),
                    PRIME),
                  PRIME),
                mulmod(
                  /*mat11*/ mload(0x300),
                  addmod(
                    /*column11_row0*/ mload(0xb80),
                    sub(PRIME, /*periodic_column/consts1_b*/ mload(0x160)),
                    PRIME),
                  PRIME),
                PRIME)
              mstore(0xd20, val)
              }


              {
              // after_lin_transform2_a_0 = mat00 * (column2_row0 - consts2_a) + mat01 * (column12_row0 - consts2_b).
              let val := addmod(
                mulmod(
                  /*mat00*/ mload(0x280),
                  addmod(
                    /*column2_row0*/ mload(0xa40),
                    sub(PRIME, /*periodic_column/consts2_a*/ mload(0x40)),
                    PRIME),
                  PRIME),
                mulmod(
                  /*mat01*/ mload(0x2a0),
                  addmod(
                    /*column12_row0*/ mload(0xba0),
                    sub(PRIME, /*periodic_column/consts2_b*/ mload(0x180)),
                    PRIME),
                  PRIME),
                PRIME)
              mstore(0xd40, val)
              }


              {
              // after_lin_transform2_b_0 = mat10 * (column2_row0 - consts2_a) + mat11 * (column12_row0 - consts2_b).
              let val := addmod(
                mulmod(
                  /*mat10*/ mload(0x2e0),
                  addmod(
                    /*column2_row0*/ mload(0xa40),
                    sub(PRIME, /*periodic_column/consts2_a*/ mload(0x40)),
                    PRIME),
                  PRIME),
                mulmod(
                  /*mat11*/ mload(0x300),
                  addmod(
                    /*column12_row0*/ mload(0xba0),
                    sub(PRIME, /*periodic_column/consts2_b*/ mload(0x180)),
                    PRIME),
                  PRIME),
                PRIME)
              mstore(0xd60, val)
              }


              {
              // after_lin_transform3_a_0 = mat00 * (column3_row0 - consts3_a) + mat01 * (column13_row0 - consts3_b).
              let val := addmod(
                mulmod(
                  /*mat00*/ mload(0x280),
                  addmod(
                    /*column3_row0*/ mload(0xa60),
                    sub(PRIME, /*periodic_column/consts3_a*/ mload(0x60)),
                    PRIME),
                  PRIME),
                mulmod(
                  /*mat01*/ mload(0x2a0),
                  addmod(
                    /*column13_row0*/ mload(0xbc0),
                    sub(PRIME, /*periodic_column/consts3_b*/ mload(0x1a0)),
                    PRIME),
                  PRIME),
                PRIME)
              mstore(0xd80, val)
              }


              {
              // after_lin_transform3_b_0 = mat10 * (column3_row0 - consts3_a) + mat11 * (column13_row0 - consts3_b).
              let val := addmod(
                mulmod(
                  /*mat10*/ mload(0x2e0),
                  addmod(
                    /*column3_row0*/ mload(0xa60),
                    sub(PRIME, /*periodic_column/consts3_a*/ mload(0x60)),
                    PRIME),
                  PRIME),
                mulmod(
                  /*mat11*/ mload(0x300),
                  addmod(
                    /*column13_row0*/ mload(0xbc0),
                    sub(PRIME, /*periodic_column/consts3_b*/ mload(0x1a0)),
                    PRIME),
                  PRIME),
                PRIME)
              mstore(0xda0, val)
              }


              {
              // after_lin_transform4_a_0 = mat00 * (column4_row0 - consts4_a) + mat01 * (column14_row0 - consts4_b).
              let val := addmod(
                mulmod(
                  /*mat00*/ mload(0x280),
                  addmod(
                    /*column4_row0*/ mload(0xa80),
                    sub(PRIME, /*periodic_column/consts4_a*/ mload(0x80)),
                    PRIME),
                  PRIME),
                mulmod(
                  /*mat01*/ mload(0x2a0),
                  addmod(
                    /*column14_row0*/ mload(0xbe0),
                    sub(PRIME, /*periodic_column/consts4_b*/ mload(0x1c0)),
                    PRIME),
                  PRIME),
                PRIME)
              mstore(0xdc0, val)
              }


              {
              // after_lin_transform4_b_0 = mat10 * (column4_row0 - consts4_a) + mat11 * (column14_row0 - consts4_b).
              let val := addmod(
                mulmod(
                  /*mat10*/ mload(0x2e0),
                  addmod(
                    /*column4_row0*/ mload(0xa80),
                    sub(PRIME, /*periodic_column/consts4_a*/ mload(0x80)),
                    PRIME),
                  PRIME),
                mulmod(
                  /*mat11*/ mload(0x300),
                  addmod(
                    /*column14_row0*/ mload(0xbe0),
                    sub(PRIME, /*periodic_column/consts4_b*/ mload(0x1c0)),
                    PRIME),
                  PRIME),
                PRIME)
              mstore(0xde0, val)
              }


              {
              // after_lin_transform5_a_0 = mat00 * (column5_row0 - consts5_a) + mat01 * (column15_row0 - consts5_b).
              let val := addmod(
                mulmod(
                  /*mat00*/ mload(0x280),
                  addmod(
                    /*column5_row0*/ mload(0xaa0),
                    sub(PRIME, /*periodic_column/consts5_a*/ mload(0xa0)),
                    PRIME),
                  PRIME),
                mulmod(
                  /*mat01*/ mload(0x2a0),
                  addmod(
                    /*column15_row0*/ mload(0xc00),
                    sub(PRIME, /*periodic_column/consts5_b*/ mload(0x1e0)),
                    PRIME),
                  PRIME),
                PRIME)
              mstore(0xe00, val)
              }


              {
              // after_lin_transform5_b_0 = mat10 * (column5_row0 - consts5_a) + mat11 * (column15_row0 - consts5_b).
              let val := addmod(
                mulmod(
                  /*mat10*/ mload(0x2e0),
                  addmod(
                    /*column5_row0*/ mload(0xaa0),
                    sub(PRIME, /*periodic_column/consts5_a*/ mload(0xa0)),
                    PRIME),
                  PRIME),
                mulmod(
                  /*mat11*/ mload(0x300),
                  addmod(
                    /*column15_row0*/ mload(0xc00),
                    sub(PRIME, /*periodic_column/consts5_b*/ mload(0x1e0)),
                    PRIME),
                  PRIME),
                PRIME)
              mstore(0xe20, val)
              }


              {
              // after_lin_transform6_a_0 = mat00 * (column6_row0 - consts6_a) + mat01 * (column16_row0 - consts6_b).
              let val := addmod(
                mulmod(
                  /*mat00*/ mload(0x280),
                  addmod(
                    /*column6_row0*/ mload(0xac0),
                    sub(PRIME, /*periodic_column/consts6_a*/ mload(0xc0)),
                    PRIME),
                  PRIME),
                mulmod(
                  /*mat01*/ mload(0x2a0),
                  addmod(
                    /*column16_row0*/ mload(0xc20),
                    sub(PRIME, /*periodic_column/consts6_b*/ mload(0x200)),
                    PRIME),
                  PRIME),
                PRIME)
              mstore(0xe40, val)
              }


              {
              // after_lin_transform6_b_0 = mat10 * (column6_row0 - consts6_a) + mat11 * (column16_row0 - consts6_b).
              let val := addmod(
                mulmod(
                  /*mat10*/ mload(0x2e0),
                  addmod(
                    /*column6_row0*/ mload(0xac0),
                    sub(PRIME, /*periodic_column/consts6_a*/ mload(0xc0)),
                    PRIME),
                  PRIME),
                mulmod(
                  /*mat11*/ mload(0x300),
                  addmod(
                    /*column16_row0*/ mload(0xc20),
                    sub(PRIME, /*periodic_column/consts6_b*/ mload(0x200)),
                    PRIME),
                  PRIME),
                PRIME)
              mstore(0xe60, val)
              }


              {
              // after_lin_transform7_a_0 = mat00 * (column7_row0 - consts7_a) + mat01 * (column17_row0 - consts7_b).
              let val := addmod(
                mulmod(
                  /*mat00*/ mload(0x280),
                  addmod(
                    /*column7_row0*/ mload(0xae0),
                    sub(PRIME, /*periodic_column/consts7_a*/ mload(0xe0)),
                    PRIME),
                  PRIME),
                mulmod(
                  /*mat01*/ mload(0x2a0),
                  addmod(
                    /*column17_row0*/ mload(0xc40),
                    sub(PRIME, /*periodic_column/consts7_b*/ mload(0x220)),
                    PRIME),
                  PRIME),
                PRIME)
              mstore(0xe80, val)
              }


              {
              // after_lin_transform7_b_0 = mat10 * (column7_row0 - consts7_a) + mat11 * (column17_row0 - consts7_b).
              let val := addmod(
                mulmod(
                  /*mat10*/ mload(0x2e0),
                  addmod(
                    /*column7_row0*/ mload(0xae0),
                    sub(PRIME, /*periodic_column/consts7_a*/ mload(0xe0)),
                    PRIME),
                  PRIME),
                mulmod(
                  /*mat11*/ mload(0x300),
                  addmod(
                    /*column17_row0*/ mload(0xc40),
                    sub(PRIME, /*periodic_column/consts7_b*/ mload(0x220)),
                    PRIME),
                  PRIME),
                PRIME)
              mstore(0xea0, val)
              }


              {
              // after_lin_transform8_a_0 = mat00 * (column8_row0 - consts8_a) + mat01 * (column18_row0 - consts8_b).
              let val := addmod(
                mulmod(
                  /*mat00*/ mload(0x280),
                  addmod(
                    /*column8_row0*/ mload(0xb00),
                    sub(PRIME, /*periodic_column/consts8_a*/ mload(0x100)),
                    PRIME),
                  PRIME),
                mulmod(
                  /*mat01*/ mload(0x2a0),
                  addmod(
                    /*column18_row0*/ mload(0xc60),
                    sub(PRIME, /*periodic_column/consts8_b*/ mload(0x240)),
                    PRIME),
                  PRIME),
                PRIME)
              mstore(0xec0, val)
              }


              {
              // after_lin_transform8_b_0 = mat10 * (column8_row0 - consts8_a) + mat11 * (column18_row0 - consts8_b).
              let val := addmod(
                mulmod(
                  /*mat10*/ mload(0x2e0),
                  addmod(
                    /*column8_row0*/ mload(0xb00),
                    sub(PRIME, /*periodic_column/consts8_a*/ mload(0x100)),
                    PRIME),
                  PRIME),
                mulmod(
                  /*mat11*/ mload(0x300),
                  addmod(
                    /*column18_row0*/ mload(0xc60),
                    sub(PRIME, /*periodic_column/consts8_b*/ mload(0x240)),
                    PRIME),
                  PRIME),
                PRIME)
              mstore(0xee0, val)
              }


              {
              // after_lin_transform9_a_0 = mat00 * (column9_row0 - consts9_a) + mat01 * (column19_row0 - consts9_b).
              let val := addmod(
                mulmod(
                  /*mat00*/ mload(0x280),
                  addmod(
                    /*column9_row0*/ mload(0xb20),
                    sub(PRIME, /*periodic_column/consts9_a*/ mload(0x120)),
                    PRIME),
                  PRIME),
                mulmod(
                  /*mat01*/ mload(0x2a0),
                  addmod(
                    /*column19_row0*/ mload(0xc80),
                    sub(PRIME, /*periodic_column/consts9_b*/ mload(0x260)),
                    PRIME),
                  PRIME),
                PRIME)
              mstore(0xf00, val)
              }


              {
              // after_lin_transform9_b_0 = mat10 * (column9_row0 - consts9_a) + mat11 * (column19_row0 - consts9_b).
              let val := addmod(
                mulmod(
                  /*mat10*/ mload(0x2e0),
                  addmod(
                    /*column9_row0*/ mload(0xb20),
                    sub(PRIME, /*periodic_column/consts9_a*/ mload(0x120)),
                    PRIME),
                  PRIME),
                mulmod(
                  /*mat11*/ mload(0x300),
                  addmod(
                    /*column19_row0*/ mload(0xc80),
                    sub(PRIME, /*periodic_column/consts9_b*/ mload(0x260)),
                    PRIME),
                  PRIME),
                PRIME)
              mstore(0xf20, val)
              }


              {
              // Constraint expression for step0_a: column1_row0 - after_lin_transform0_a_0 * after_lin_transform0_a_0 * after_lin_transform0_a_0.
              let val := addmod(
                /*column1_row0*/ mload(0xa20),
                sub(
                  PRIME,
                  mulmod(
                    mulmod(
                      /*intermediate_value/after_lin_transform0_a_0*/ mload(0xcc0),
                      /*intermediate_value/after_lin_transform0_a_0*/ mload(0xcc0),
                      PRIME),
                    /*intermediate_value/after_lin_transform0_a_0*/ mload(0xcc0),
                    PRIME)),
                PRIME)

              // Numerator: 1.
              // val *= 1.
              // val := mulmod(val, 1, PRIME).
              // Denominator: point^trace_length - 1.
              // val *= denominator_invs[0].
              val := mulmod(val, mload(0xf80), PRIME)

              // res += val * (coefficients[0] + coefficients[1] * adjustments[0]).
              res := addmod(res,
                            mulmod(val,
                                   add(/*coefficients[0]*/ mload(0x3e0),
                                       mulmod(/*coefficients[1]*/ mload(0x400),
                                              /*adjustments[0]*/mload(0x1060),
                      PRIME)),
                      PRIME),
                      PRIME)
              }

              {
              // Constraint expression for step0_b: column11_row0 - after_lin_transform0_b_0 * after_lin_transform0_b_0 * after_lin_transform0_b_0.
              let val := addmod(
                /*column11_row0*/ mload(0xb80),
                sub(
                  PRIME,
                  mulmod(
                    mulmod(
                      /*intermediate_value/after_lin_transform0_b_0*/ mload(0xce0),
                      /*intermediate_value/after_lin_transform0_b_0*/ mload(0xce0),
                      PRIME),
                    /*intermediate_value/after_lin_transform0_b_0*/ mload(0xce0),
                    PRIME)),
                PRIME)

              // Numerator: 1.
              // val *= 1.
              // val := mulmod(val, 1, PRIME).
              // Denominator: point^trace_length - 1.
              // val *= denominator_invs[0].
              val := mulmod(val, mload(0xf80), PRIME)

              // res += val * (coefficients[2] + coefficients[3] * adjustments[0]).
              res := addmod(res,
                            mulmod(val,
                                   add(/*coefficients[2]*/ mload(0x420),
                                       mulmod(/*coefficients[3]*/ mload(0x440),
                                              /*adjustments[0]*/mload(0x1060),
                      PRIME)),
                      PRIME),
                      PRIME)
              }

              {
              // Constraint expression for step1_a: column2_row0 - after_lin_transform1_a_0 * after_lin_transform1_a_0 * after_lin_transform1_a_0.
              let val := addmod(
                /*column2_row0*/ mload(0xa40),
                sub(
                  PRIME,
                  mulmod(
                    mulmod(
                      /*intermediate_value/after_lin_transform1_a_0*/ mload(0xd00),
                      /*intermediate_value/after_lin_transform1_a_0*/ mload(0xd00),
                      PRIME),
                    /*intermediate_value/after_lin_transform1_a_0*/ mload(0xd00),
                    PRIME)),
                PRIME)

              // Numerator: 1.
              // val *= 1.
              // val := mulmod(val, 1, PRIME).
              // Denominator: point^trace_length - 1.
              // val *= denominator_invs[0].
              val := mulmod(val, mload(0xf80), PRIME)

              // res += val * (coefficients[4] + coefficients[5] * adjustments[0]).
              res := addmod(res,
                            mulmod(val,
                                   add(/*coefficients[4]*/ mload(0x460),
                                       mulmod(/*coefficients[5]*/ mload(0x480),
                                              /*adjustments[0]*/mload(0x1060),
                      PRIME)),
                      PRIME),
                      PRIME)
              }

              {
              // Constraint expression for step1_b: column12_row0 - after_lin_transform1_b_0 * after_lin_transform1_b_0 * after_lin_transform1_b_0.
              let val := addmod(
                /*column12_row0*/ mload(0xba0),
                sub(
                  PRIME,
                  mulmod(
                    mulmod(
                      /*intermediate_value/after_lin_transform1_b_0*/ mload(0xd20),
                      /*intermediate_value/after_lin_transform1_b_0*/ mload(0xd20),
                      PRIME),
                    /*intermediate_value/after_lin_transform1_b_0*/ mload(0xd20),
                    PRIME)),
                PRIME)

              // Numerator: 1.
              // val *= 1.
              // val := mulmod(val, 1, PRIME).
              // Denominator: point^trace_length - 1.
              // val *= denominator_invs[0].
              val := mulmod(val, mload(0xf80), PRIME)

              // res += val * (coefficients[6] + coefficients[7] * adjustments[0]).
              res := addmod(res,
                            mulmod(val,
                                   add(/*coefficients[6]*/ mload(0x4a0),
                                       mulmod(/*coefficients[7]*/ mload(0x4c0),
                                              /*adjustments[0]*/mload(0x1060),
                      PRIME)),
                      PRIME),
                      PRIME)
              }

              {
              // Constraint expression for step2_a: column3_row0 - after_lin_transform2_a_0 * after_lin_transform2_a_0 * after_lin_transform2_a_0.
              let val := addmod(
                /*column3_row0*/ mload(0xa60),
                sub(
                  PRIME,
                  mulmod(
                    mulmod(
                      /*intermediate_value/after_lin_transform2_a_0*/ mload(0xd40),
                      /*intermediate_value/after_lin_transform2_a_0*/ mload(0xd40),
                      PRIME),
                    /*intermediate_value/after_lin_transform2_a_0*/ mload(0xd40),
                    PRIME)),
                PRIME)

              // Numerator: 1.
              // val *= 1.
              // val := mulmod(val, 1, PRIME).
              // Denominator: point^trace_length - 1.
              // val *= denominator_invs[0].
              val := mulmod(val, mload(0xf80), PRIME)

              // res += val * (coefficients[8] + coefficients[9] * adjustments[0]).
              res := addmod(res,
                            mulmod(val,
                                   add(/*coefficients[8]*/ mload(0x4e0),
                                       mulmod(/*coefficients[9]*/ mload(0x500),
                                              /*adjustments[0]*/mload(0x1060),
                      PRIME)),
                      PRIME),
                      PRIME)
              }

              {
              // Constraint expression for step2_b: column13_row0 - after_lin_transform2_b_0 * after_lin_transform2_b_0 * after_lin_transform2_b_0.
              let val := addmod(
                /*column13_row0*/ mload(0xbc0),
                sub(
                  PRIME,
                  mulmod(
                    mulmod(
                      /*intermediate_value/after_lin_transform2_b_0*/ mload(0xd60),
                      /*intermediate_value/after_lin_transform2_b_0*/ mload(0xd60),
                      PRIME),
                    /*intermediate_value/after_lin_transform2_b_0*/ mload(0xd60),
                    PRIME)),
                PRIME)

              // Numerator: 1.
              // val *= 1.
              // val := mulmod(val, 1, PRIME).
              // Denominator: point^trace_length - 1.
              // val *= denominator_invs[0].
              val := mulmod(val, mload(0xf80), PRIME)

              // res += val * (coefficients[10] + coefficients[11] * adjustments[0]).
              res := addmod(res,
                            mulmod(val,
                                   add(/*coefficients[10]*/ mload(0x520),
                                       mulmod(/*coefficients[11]*/ mload(0x540),
                                              /*adjustments[0]*/mload(0x1060),
                      PRIME)),
                      PRIME),
                      PRIME)
              }

              {
              // Constraint expression for step3_a: column4_row0 - after_lin_transform3_a_0 * after_lin_transform3_a_0 * after_lin_transform3_a_0.
              let val := addmod(
                /*column4_row0*/ mload(0xa80),
                sub(
                  PRIME,
                  mulmod(
                    mulmod(
                      /*intermediate_value/after_lin_transform3_a_0*/ mload(0xd80),
                      /*intermediate_value/after_lin_transform3_a_0*/ mload(0xd80),
                      PRIME),
                    /*intermediate_value/after_lin_transform3_a_0*/ mload(0xd80),
                    PRIME)),
                PRIME)

              // Numerator: 1.
              // val *= 1.
              // val := mulmod(val, 1, PRIME).
              // Denominator: point^trace_length - 1.
              // val *= denominator_invs[0].
              val := mulmod(val, mload(0xf80), PRIME)

              // res += val * (coefficients[12] + coefficients[13] * adjustments[0]).
              res := addmod(res,
                            mulmod(val,
                                   add(/*coefficients[12]*/ mload(0x560),
                                       mulmod(/*coefficients[13]*/ mload(0x580),
                                              /*adjustments[0]*/mload(0x1060),
                      PRIME)),
                      PRIME),
                      PRIME)
              }

              {
              // Constraint expression for step3_b: column14_row0 - after_lin_transform3_b_0 * after_lin_transform3_b_0 * after_lin_transform3_b_0.
              let val := addmod(
                /*column14_row0*/ mload(0xbe0),
                sub(
                  PRIME,
                  mulmod(
                    mulmod(
                      /*intermediate_value/after_lin_transform3_b_0*/ mload(0xda0),
                      /*intermediate_value/after_lin_transform3_b_0*/ mload(0xda0),
                      PRIME),
                    /*intermediate_value/after_lin_transform3_b_0*/ mload(0xda0),
                    PRIME)),
                PRIME)

              // Numerator: 1.
              // val *= 1.
              // val := mulmod(val, 1, PRIME).
              // Denominator: point^trace_length - 1.
              // val *= denominator_invs[0].
              val := mulmod(val, mload(0xf80), PRIME)

              // res += val * (coefficients[14] + coefficients[15] * adjustments[0]).
              res := addmod(res,
                            mulmod(val,
                                   add(/*coefficients[14]*/ mload(0x5a0),
                                       mulmod(/*coefficients[15]*/ mload(0x5c0),
                                              /*adjustments[0]*/mload(0x1060),
                      PRIME)),
                      PRIME),
                      PRIME)
              }

              {
              // Constraint expression for step4_a: column5_row0 - after_lin_transform4_a_0 * after_lin_transform4_a_0 * after_lin_transform4_a_0.
              let val := addmod(
                /*column5_row0*/ mload(0xaa0),
                sub(
                  PRIME,
                  mulmod(
                    mulmod(
                      /*intermediate_value/after_lin_transform4_a_0*/ mload(0xdc0),
                      /*intermediate_value/after_lin_transform4_a_0*/ mload(0xdc0),
                      PRIME),
                    /*intermediate_value/after_lin_transform4_a_0*/ mload(0xdc0),
                    PRIME)),
                PRIME)

              // Numerator: 1.
              // val *= 1.
              // val := mulmod(val, 1, PRIME).
              // Denominator: point^trace_length - 1.
              // val *= denominator_invs[0].
              val := mulmod(val, mload(0xf80), PRIME)

              // res += val * (coefficients[16] + coefficients[17] * adjustments[0]).
              res := addmod(res,
                            mulmod(val,
                                   add(/*coefficients[16]*/ mload(0x5e0),
                                       mulmod(/*coefficients[17]*/ mload(0x600),
                                              /*adjustments[0]*/mload(0x1060),
                      PRIME)),
                      PRIME),
                      PRIME)
              }

              {
              // Constraint expression for step4_b: column15_row0 - after_lin_transform4_b_0 * after_lin_transform4_b_0 * after_lin_transform4_b_0.
              let val := addmod(
                /*column15_row0*/ mload(0xc00),
                sub(
                  PRIME,
                  mulmod(
                    mulmod(
                      /*intermediate_value/after_lin_transform4_b_0*/ mload(0xde0),
                      /*intermediate_value/after_lin_transform4_b_0*/ mload(0xde0),
                      PRIME),
                    /*intermediate_value/after_lin_transform4_b_0*/ mload(0xde0),
                    PRIME)),
                PRIME)

              // Numerator: 1.
              // val *= 1.
              // val := mulmod(val, 1, PRIME).
              // Denominator: point^trace_length - 1.
              // val *= denominator_invs[0].
              val := mulmod(val, mload(0xf80), PRIME)

              // res += val * (coefficients[18] + coefficients[19] * adjustments[0]).
              res := addmod(res,
                            mulmod(val,
                                   add(/*coefficients[18]*/ mload(0x620),
                                       mulmod(/*coefficients[19]*/ mload(0x640),
                                              /*adjustments[0]*/mload(0x1060),
                      PRIME)),
                      PRIME),
                      PRIME)
              }

              {
              // Constraint expression for step5_a: column6_row0 - after_lin_transform5_a_0 * after_lin_transform5_a_0 * after_lin_transform5_a_0.
              let val := addmod(
                /*column6_row0*/ mload(0xac0),
                sub(
                  PRIME,
                  mulmod(
                    mulmod(
                      /*intermediate_value/after_lin_transform5_a_0*/ mload(0xe00),
                      /*intermediate_value/after_lin_transform5_a_0*/ mload(0xe00),
                      PRIME),
                    /*intermediate_value/after_lin_transform5_a_0*/ mload(0xe00),
                    PRIME)),
                PRIME)

              // Numerator: 1.
              // val *= 1.
              // val := mulmod(val, 1, PRIME).
              // Denominator: point^trace_length - 1.
              // val *= denominator_invs[0].
              val := mulmod(val, mload(0xf80), PRIME)

              // res += val * (coefficients[20] + coefficients[21] * adjustments[0]).
              res := addmod(res,
                            mulmod(val,
                                   add(/*coefficients[20]*/ mload(0x660),
                                       mulmod(/*coefficients[21]*/ mload(0x680),
                                              /*adjustments[0]*/mload(0x1060),
                      PRIME)),
                      PRIME),
                      PRIME)
              }

              {
              // Constraint expression for step5_b: column16_row0 - after_lin_transform5_b_0 * after_lin_transform5_b_0 * after_lin_transform5_b_0.
              let val := addmod(
                /*column16_row0*/ mload(0xc20),
                sub(
                  PRIME,
                  mulmod(
                    mulmod(
                      /*intermediate_value/after_lin_transform5_b_0*/ mload(0xe20),
                      /*intermediate_value/after_lin_transform5_b_0*/ mload(0xe20),
                      PRIME),
                    /*intermediate_value/after_lin_transform5_b_0*/ mload(0xe20),
                    PRIME)),
                PRIME)

              // Numerator: 1.
              // val *= 1.
              // val := mulmod(val, 1, PRIME).
              // Denominator: point^trace_length - 1.
              // val *= denominator_invs[0].
              val := mulmod(val, mload(0xf80), PRIME)

              // res += val * (coefficients[22] + coefficients[23] * adjustments[0]).
              res := addmod(res,
                            mulmod(val,
                                   add(/*coefficients[22]*/ mload(0x6a0),
                                       mulmod(/*coefficients[23]*/ mload(0x6c0),
                                              /*adjustments[0]*/mload(0x1060),
                      PRIME)),
                      PRIME),
                      PRIME)
              }

              {
              // Constraint expression for step6_a: column7_row0 - after_lin_transform6_a_0 * after_lin_transform6_a_0 * after_lin_transform6_a_0.
              let val := addmod(
                /*column7_row0*/ mload(0xae0),
                sub(
                  PRIME,
                  mulmod(
                    mulmod(
                      /*intermediate_value/after_lin_transform6_a_0*/ mload(0xe40),
                      /*intermediate_value/after_lin_transform6_a_0*/ mload(0xe40),
                      PRIME),
                    /*intermediate_value/after_lin_transform6_a_0*/ mload(0xe40),
                    PRIME)),
                PRIME)

              // Numerator: 1.
              // val *= 1.
              // val := mulmod(val, 1, PRIME).
              // Denominator: point^trace_length - 1.
              // val *= denominator_invs[0].
              val := mulmod(val, mload(0xf80), PRIME)

              // res += val * (coefficients[24] + coefficients[25] * adjustments[0]).
              res := addmod(res,
                            mulmod(val,
                                   add(/*coefficients[24]*/ mload(0x6e0),
                                       mulmod(/*coefficients[25]*/ mload(0x700),
                                              /*adjustments[0]*/mload(0x1060),
                      PRIME)),
                      PRIME),
                      PRIME)
              }

              {
              // Constraint expression for step6_b: column17_row0 - after_lin_transform6_b_0 * after_lin_transform6_b_0 * after_lin_transform6_b_0.
              let val := addmod(
                /*column17_row0*/ mload(0xc40),
                sub(
                  PRIME,
                  mulmod(
                    mulmod(
                      /*intermediate_value/after_lin_transform6_b_0*/ mload(0xe60),
                      /*intermediate_value/after_lin_transform6_b_0*/ mload(0xe60),
                      PRIME),
                    /*intermediate_value/after_lin_transform6_b_0*/ mload(0xe60),
                    PRIME)),
                PRIME)

              // Numerator: 1.
              // val *= 1.
              // val := mulmod(val, 1, PRIME).
              // Denominator: point^trace_length - 1.
              // val *= denominator_invs[0].
              val := mulmod(val, mload(0xf80), PRIME)

              // res += val * (coefficients[26] + coefficients[27] * adjustments[0]).
              res := addmod(res,
                            mulmod(val,
                                   add(/*coefficients[26]*/ mload(0x720),
                                       mulmod(/*coefficients[27]*/ mload(0x740),
                                              /*adjustments[0]*/mload(0x1060),
                      PRIME)),
                      PRIME),
                      PRIME)
              }

              {
              // Constraint expression for step7_a: column8_row0 - after_lin_transform7_a_0 * after_lin_transform7_a_0 * after_lin_transform7_a_0.
              let val := addmod(
                /*column8_row0*/ mload(0xb00),
                sub(
                  PRIME,
                  mulmod(
                    mulmod(
                      /*intermediate_value/after_lin_transform7_a_0*/ mload(0xe80),
                      /*intermediate_value/after_lin_transform7_a_0*/ mload(0xe80),
                      PRIME),
                    /*intermediate_value/after_lin_transform7_a_0*/ mload(0xe80),
                    PRIME)),
                PRIME)

              // Numerator: 1.
              // val *= 1.
              // val := mulmod(val, 1, PRIME).
              // Denominator: point^trace_length - 1.
              // val *= denominator_invs[0].
              val := mulmod(val, mload(0xf80), PRIME)

              // res += val * (coefficients[28] + coefficients[29] * adjustments[0]).
              res := addmod(res,
                            mulmod(val,
                                   add(/*coefficients[28]*/ mload(0x760),
                                       mulmod(/*coefficients[29]*/ mload(0x780),
                                              /*adjustments[0]*/mload(0x1060),
                      PRIME)),
                      PRIME),
                      PRIME)
              }

              {
              // Constraint expression for step7_b: column18_row0 - after_lin_transform7_b_0 * after_lin_transform7_b_0 * after_lin_transform7_b_0.
              let val := addmod(
                /*column18_row0*/ mload(0xc60),
                sub(
                  PRIME,
                  mulmod(
                    mulmod(
                      /*intermediate_value/after_lin_transform7_b_0*/ mload(0xea0),
                      /*intermediate_value/after_lin_transform7_b_0*/ mload(0xea0),
                      PRIME),
                    /*intermediate_value/after_lin_transform7_b_0*/ mload(0xea0),
                    PRIME)),
                PRIME)

              // Numerator: 1.
              // val *= 1.
              // val := mulmod(val, 1, PRIME).
              // Denominator: point^trace_length - 1.
              // val *= denominator_invs[0].
              val := mulmod(val, mload(0xf80), PRIME)

              // res += val * (coefficients[30] + coefficients[31] * adjustments[0]).
              res := addmod(res,
                            mulmod(val,
                                   add(/*coefficients[30]*/ mload(0x7a0),
                                       mulmod(/*coefficients[31]*/ mload(0x7c0),
                                              /*adjustments[0]*/mload(0x1060),
                      PRIME)),
                      PRIME),
                      PRIME)
              }

              {
              // Constraint expression for step8_a: column9_row0 - after_lin_transform8_a_0 * after_lin_transform8_a_0 * after_lin_transform8_a_0.
              let val := addmod(
                /*column9_row0*/ mload(0xb20),
                sub(
                  PRIME,
                  mulmod(
                    mulmod(
                      /*intermediate_value/after_lin_transform8_a_0*/ mload(0xec0),
                      /*intermediate_value/after_lin_transform8_a_0*/ mload(0xec0),
                      PRIME),
                    /*intermediate_value/after_lin_transform8_a_0*/ mload(0xec0),
                    PRIME)),
                PRIME)

              // Numerator: 1.
              // val *= 1.
              // val := mulmod(val, 1, PRIME).
              // Denominator: point^trace_length - 1.
              // val *= denominator_invs[0].
              val := mulmod(val, mload(0xf80), PRIME)

              // res += val * (coefficients[32] + coefficients[33] * adjustments[0]).
              res := addmod(res,
                            mulmod(val,
                                   add(/*coefficients[32]*/ mload(0x7e0),
                                       mulmod(/*coefficients[33]*/ mload(0x800),
                                              /*adjustments[0]*/mload(0x1060),
                      PRIME)),
                      PRIME),
                      PRIME)
              }

              {
              // Constraint expression for step8_b: column19_row0 - after_lin_transform8_b_0 * after_lin_transform8_b_0 * after_lin_transform8_b_0.
              let val := addmod(
                /*column19_row0*/ mload(0xc80),
                sub(
                  PRIME,
                  mulmod(
                    mulmod(
                      /*intermediate_value/after_lin_transform8_b_0*/ mload(0xee0),
                      /*intermediate_value/after_lin_transform8_b_0*/ mload(0xee0),
                      PRIME),
                    /*intermediate_value/after_lin_transform8_b_0*/ mload(0xee0),
                    PRIME)),
                PRIME)

              // Numerator: 1.
              // val *= 1.
              // val := mulmod(val, 1, PRIME).
              // Denominator: point^trace_length - 1.
              // val *= denominator_invs[0].
              val := mulmod(val, mload(0xf80), PRIME)

              // res += val * (coefficients[34] + coefficients[35] * adjustments[0]).
              res := addmod(res,
                            mulmod(val,
                                   add(/*coefficients[34]*/ mload(0x820),
                                       mulmod(/*coefficients[35]*/ mload(0x840),
                                              /*adjustments[0]*/mload(0x1060),
                      PRIME)),
                      PRIME),
                      PRIME)
              }

              {
              // Constraint expression for step9_a: column0_row1 - after_lin_transform9_a_0 * after_lin_transform9_a_0 * after_lin_transform9_a_0.
              let val := addmod(
                /*column0_row1*/ mload(0xa00),
                sub(
                  PRIME,
                  mulmod(
                    mulmod(
                      /*intermediate_value/after_lin_transform9_a_0*/ mload(0xf00),
                      /*intermediate_value/after_lin_transform9_a_0*/ mload(0xf00),
                      PRIME),
                    /*intermediate_value/after_lin_transform9_a_0*/ mload(0xf00),
                    PRIME)),
                PRIME)

              // Numerator: point - trace_generator^(trace_length - 1).
              // val *= numerators[0].
              val := mulmod(val, mload(0x1040), PRIME)
              // Denominator: point^trace_length - 1.
              // val *= denominator_invs[0].
              val := mulmod(val, mload(0xf80), PRIME)

              // res += val * (coefficients[36] + coefficients[37] * adjustments[1]).
              res := addmod(res,
                            mulmod(val,
                                   add(/*coefficients[36]*/ mload(0x860),
                                       mulmod(/*coefficients[37]*/ mload(0x880),
                                              /*adjustments[1]*/mload(0x1080),
                      PRIME)),
                      PRIME),
                      PRIME)
              }

              {
              // Constraint expression for step9_b: column10_row1 - after_lin_transform9_b_0 * after_lin_transform9_b_0 * after_lin_transform9_b_0.
              let val := addmod(
                /*column10_row1*/ mload(0xb60),
                sub(
                  PRIME,
                  mulmod(
                    mulmod(
                      /*intermediate_value/after_lin_transform9_b_0*/ mload(0xf20),
                      /*intermediate_value/after_lin_transform9_b_0*/ mload(0xf20),
                      PRIME),
                    /*intermediate_value/after_lin_transform9_b_0*/ mload(0xf20),
                    PRIME)),
                PRIME)

              // Numerator: point - trace_generator^(trace_length - 1).
              // val *= numerators[0].
              val := mulmod(val, mload(0x1040), PRIME)
              // Denominator: point^trace_length - 1.
              // val *= denominator_invs[0].
              val := mulmod(val, mload(0xf80), PRIME)

              // res += val * (coefficients[38] + coefficients[39] * adjustments[1]).
              res := addmod(res,
                            mulmod(val,
                                   add(/*coefficients[38]*/ mload(0x8a0),
                                       mulmod(/*coefficients[39]*/ mload(0x8c0),
                                              /*adjustments[1]*/mload(0x1080),
                      PRIME)),
                      PRIME),
                      PRIME)
              }

              {
              // Constraint expression for input_a: column0_row0 - input_value_a.
              let val := addmod(/*column0_row0*/ mload(0x9e0), sub(PRIME, /*input_value_a*/ mload(0x320)), PRIME)

              // Numerator: 1.
              // val *= 1.
              // val := mulmod(val, 1, PRIME).
              // Denominator: point - 1.
              // val *= denominator_invs[1].
              val := mulmod(val, mload(0xfa0), PRIME)

              // res += val * (coefficients[40] + coefficients[41] * adjustments[2]).
              res := addmod(res,
                            mulmod(val,
                                   add(/*coefficients[40]*/ mload(0x8e0),
                                       mulmod(/*coefficients[41]*/ mload(0x900),
                                              /*adjustments[2]*/mload(0x10a0),
                      PRIME)),
                      PRIME),
                      PRIME)
              }

              {
              // Constraint expression for output_a: column9_row0 - output_value_a.
              let val := addmod(/*column9_row0*/ mload(0xb20), sub(PRIME, /*output_value_a*/ mload(0x340)), PRIME)

              // Numerator: 1.
              // val *= 1.
              // val := mulmod(val, 1, PRIME).
              // Denominator: point - trace_generator^(trace_length - 1).
              // val *= denominator_invs[2].
              val := mulmod(val, mload(0xfc0), PRIME)

              // res += val * (coefficients[42] + coefficients[43] * adjustments[2]).
              res := addmod(res,
                            mulmod(val,
                                   add(/*coefficients[42]*/ mload(0x920),
                                       mulmod(/*coefficients[43]*/ mload(0x940),
                                              /*adjustments[2]*/mload(0x10a0),
                      PRIME)),
                      PRIME),
                      PRIME)
              }

              {
              // Constraint expression for input_b: column10_row0 - input_value_b.
              let val := addmod(/*column10_row0*/ mload(0xb40), sub(PRIME, /*input_value_b*/ mload(0x360)), PRIME)

              // Numerator: 1.
              // val *= 1.
              // val := mulmod(val, 1, PRIME).
              // Denominator: point - 1.
              // val *= denominator_invs[1].
              val := mulmod(val, mload(0xfa0), PRIME)

              // res += val * (coefficients[44] + coefficients[45] * adjustments[2]).
              res := addmod(res,
                            mulmod(val,
                                   add(/*coefficients[44]*/ mload(0x960),
                                       mulmod(/*coefficients[45]*/ mload(0x980),
                                              /*adjustments[2]*/mload(0x10a0),
                      PRIME)),
                      PRIME),
                      PRIME)
              }

              {
              // Constraint expression for output_b: column19_row0 - output_value_b.
              let val := addmod(/*column19_row0*/ mload(0xc80), sub(PRIME, /*output_value_b*/ mload(0x380)), PRIME)

              // Numerator: 1.
              // val *= 1.
              // val := mulmod(val, 1, PRIME).
              // Denominator: point - trace_generator^(trace_length - 1).
              // val *= denominator_invs[2].
              val := mulmod(val, mload(0xfc0), PRIME)

              // res += val * (coefficients[46] + coefficients[47] * adjustments[2]).
              res := addmod(res,
                            mulmod(val,
                                   add(/*coefficients[46]*/ mload(0x9a0),
                                       mulmod(/*coefficients[47]*/ mload(0x9c0),
                                              /*adjustments[2]*/mload(0x10a0),
                      PRIME)),
                      PRIME),
                      PRIME)
              }

            mstore(0, res)
            return(0, 0x20)
            }
        }
    }
}
// ---------- End of auto-generated code. ----------

// File: MimcOods.sol



// ---------- The following code was auto-generated. PLEASE DO NOT EDIT. ----------
pragma solidity ^0.5.2;

import "./MemoryMap.sol";
import "./StarkParameters.sol";

contract MimcOods is MemoryMap, StarkParameters {
    // For each query point we want to invert (2 + N_ROWS_IN_MASK) items:
    //  The query point itself (x).
    //  The denominator for the constraint polynomial (x-z^constraintDegree)
    //  [(x-(g^rowNumber)z) for rowNumber in mask].
    uint256 constant internal BATCH_INVERSE_CHUNK = (2 + N_ROWS_IN_MASK);
    uint256 constant internal BATCH_INVERSE_SIZE = MAX_N_QUERIES * BATCH_INVERSE_CHUNK;

    /*
      Builds and sums boundary constraints that check that the prover provided the proper evaluations
      out of domain evaluations for the trace and composition columns.

      The inputs to this function are:
          The verifier context.

      The boundary constraints for the trace enforce claims of the form f(g^k*z) = c by
      requiring the quotient (f(x) - c)/(x-g^k*z) to be a low degree polynomial.

      The boundary constraints for the composition enforce claims of the form h(z^d) = c by
      requiring the quotient (h(x) - c)/(x-z^d) to be a low degree polynomial.
      Where:
            f is a trace column.
            h is a composition column.
            z is the out of domain sampling point.
            g is the trace generator
            k is the offset in the mask.
            d is the degree of the composition polynomial.
            c is the evaluation sent by the prover.
    */
    function() external {
        // This funciton assumes that the calldata contains the context as defined in MemoryMap.sol.
        // Note that ctx is a variable size array so the first uint256 cell contrains it's length.
        uint256[] memory ctx;
        assembly {
            let ctxSize := mul(add(calldataload(0), 1), 0x20)
            ctx := mload(0x40)
            mstore(0x40, add(ctx, ctxSize))
            calldatacopy(ctx, 0, ctxSize)
        }
        uint256[] memory batchInverseArray = new uint256[](2 * BATCH_INVERSE_SIZE);

        oodsPrepareInverses(ctx, batchInverseArray);

        uint256 kMontgomeryRInv_ = PrimeFieldElement6.K_MONTGOMERY_R_INV;

        assembly {
            let PRIME := 0x30000003000000010000000000000001
            let kMontgomeryRInv := kMontgomeryRInv_
            let context := ctx
            let friQueue := /*friQueue*/ add(context, 0xda0)
            let friQueueEnd := add(friQueue,  mul(/*n_unique_queries*/ mload(add(context, 0x120)), 0x60))
            let traceQueryResponses := /*traceQueryQesponses*/ add(context, 0x3d80)

            let compositionQueryResponses := /*composition_query_responses*/ add(context, 0xb580)

            // Set denominatorsPtr to point to the batchInverseOut array.
            // The content of batchInverseOut is described in oodsPrepareInverses.
            let denominatorsPtr := add(batchInverseArray, 0x20)

            for {} lt(friQueue, friQueueEnd) {friQueue := add(friQueue, 0x60)} {
                // res accumulates numbers modulo PRIME. Since 1814839283484201961915354863390654471405*PRIME < 2**256, we may add up to
                // 1814839283484201961915354863390654471405 numbers without fear of overflow, and use addmod modulo PRIME only every
                // 1814839283484201961915354863390654471405 iterations, and once more at the very end.
                let res := 0

                // Trace constraints.

                // Mask items for column #0.
                {
                // Read the next element.
                let columnValue := mulmod(mload(traceQueryResponses), kMontgomeryRInv, PRIME)

                // res += c_0*(f_0(x) - f_0(z)) / (x - z).
                res := add(
                    res,
                    mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr),
                                  /*oods_coefficients[0]*/ mload(add(context, 0x3a80)),
                                  PRIME),
                           add(columnValue, sub(PRIME, /*oods_values[0]*/ mload(add(context, 0x3180)))),
                           PRIME))

                // res += c_1*(f_0(x) - f_0(g * z)) / (x - g * z).
                res := add(
                    res,
                    mulmod(mulmod(/*(x - g * z)^(-1)*/ mload(add(denominatorsPtr, 0x20)),
                                  /*oods_coefficients[1]*/ mload(add(context, 0x3aa0)),
                                  PRIME),
                           add(columnValue, sub(PRIME, /*oods_values[1]*/ mload(add(context, 0x31a0)))),
                           PRIME))
                }

                // Mask items for column #1.
                {
                // Read the next element.
                let columnValue := mulmod(mload(add(traceQueryResponses, 0x20)), kMontgomeryRInv, PRIME)

                // res += c_2*(f_1(x) - f_1(z)) / (x - z).
                res := add(
                    res,
                    mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr),
                                  /*oods_coefficients[2]*/ mload(add(context, 0x3ac0)),
                                  PRIME),
                           add(columnValue, sub(PRIME, /*oods_values[2]*/ mload(add(context, 0x31c0)))),
                           PRIME))
                }

                // Mask items for column #2.
                {
                // Read the next element.
                let columnValue := mulmod(mload(add(traceQueryResponses, 0x40)), kMontgomeryRInv, PRIME)

                // res += c_3*(f_2(x) - f_2(z)) / (x - z).
                res := add(
                    res,
                    mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr),
                                  /*oods_coefficients[3]*/ mload(add(context, 0x3ae0)),
                                  PRIME),
                           add(columnValue, sub(PRIME, /*oods_values[3]*/ mload(add(context, 0x31e0)))),
                           PRIME))
                }

                // Mask items for column #3.
                {
                // Read the next element.
                let columnValue := mulmod(mload(add(traceQueryResponses, 0x60)), kMontgomeryRInv, PRIME)

                // res += c_4*(f_3(x) - f_3(z)) / (x - z).
                res := add(
                    res,
                    mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr),
                                  /*oods_coefficients[4]*/ mload(add(context, 0x3b00)),
                                  PRIME),
                           add(columnValue, sub(PRIME, /*oods_values[4]*/ mload(add(context, 0x3200)))),
                           PRIME))
                }

                // Mask items for column #4.
                {
                // Read the next element.
                let columnValue := mulmod(mload(add(traceQueryResponses, 0x80)), kMontgomeryRInv, PRIME)

                // res += c_5*(f_4(x) - f_4(z)) / (x - z).
                res := add(
                    res,
                    mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr),
                                  /*oods_coefficients[5]*/ mload(add(context, 0x3b20)),
                                  PRIME),
                           add(columnValue, sub(PRIME, /*oods_values[5]*/ mload(add(context, 0x3220)))),
                           PRIME))
                }

                // Mask items for column #5.
                {
                // Read the next element.
                let columnValue := mulmod(mload(add(traceQueryResponses, 0xa0)), kMontgomeryRInv, PRIME)

                // res += c_6*(f_5(x) - f_5(z)) / (x - z).
                res := add(
                    res,
                    mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr),
                                  /*oods_coefficients[6]*/ mload(add(context, 0x3b40)),
                                  PRIME),
                           add(columnValue, sub(PRIME, /*oods_values[6]*/ mload(add(context, 0x3240)))),
                           PRIME))
                }

                // Mask items for column #6.
                {
                // Read the next element.
                let columnValue := mulmod(mload(add(traceQueryResponses, 0xc0)), kMontgomeryRInv, PRIME)

                // res += c_7*(f_6(x) - f_6(z)) / (x - z).
                res := add(
                    res,
                    mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr),
                                  /*oods_coefficients[7]*/ mload(add(context, 0x3b60)),
                                  PRIME),
                           add(columnValue, sub(PRIME, /*oods_values[7]*/ mload(add(context, 0x3260)))),
                           PRIME))
                }

                // Mask items for column #7.
                {
                // Read the next element.
                let columnValue := mulmod(mload(add(traceQueryResponses, 0xe0)), kMontgomeryRInv, PRIME)

                // res += c_8*(f_7(x) - f_7(z)) / (x - z).
                res := add(
                    res,
                    mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr),
                                  /*oods_coefficients[8]*/ mload(add(context, 0x3b80)),
                                  PRIME),
                           add(columnValue, sub(PRIME, /*oods_values[8]*/ mload(add(context, 0x3280)))),
                           PRIME))
                }

                // Mask items for column #8.
                {
                // Read the next element.
                let columnValue := mulmod(mload(add(traceQueryResponses, 0x100)), kMontgomeryRInv, PRIME)

                // res += c_9*(f_8(x) - f_8(z)) / (x - z).
                res := add(
                    res,
                    mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr),
                                  /*oods_coefficients[9]*/ mload(add(context, 0x3ba0)),
                                  PRIME),
                           add(columnValue, sub(PRIME, /*oods_values[9]*/ mload(add(context, 0x32a0)))),
                           PRIME))
                }

                // Mask items for column #9.
                {
                // Read the next element.
                let columnValue := mulmod(mload(add(traceQueryResponses, 0x120)), kMontgomeryRInv, PRIME)

                // res += c_10*(f_9(x) - f_9(z)) / (x - z).
                res := add(
                    res,
                    mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr),
                                  /*oods_coefficients[10]*/ mload(add(context, 0x3bc0)),
                                  PRIME),
                           add(columnValue, sub(PRIME, /*oods_values[10]*/ mload(add(context, 0x32c0)))),
                           PRIME))
                }

                // Mask items for column #10.
                {
                // Read the next element.
                let columnValue := mulmod(mload(add(traceQueryResponses, 0x140)), kMontgomeryRInv, PRIME)

                // res += c_11*(f_10(x) - f_10(z)) / (x - z).
                res := add(
                    res,
                    mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr),
                                  /*oods_coefficients[11]*/ mload(add(context, 0x3be0)),
                                  PRIME),
                           add(columnValue, sub(PRIME, /*oods_values[11]*/ mload(add(context, 0x32e0)))),
                           PRIME))

                // res += c_12*(f_10(x) - f_10(g * z)) / (x - g * z).
                res := add(
                    res,
                    mulmod(mulmod(/*(x - g * z)^(-1)*/ mload(add(denominatorsPtr, 0x20)),
                                  /*oods_coefficients[12]*/ mload(add(context, 0x3c00)),
                                  PRIME),
                           add(columnValue, sub(PRIME, /*oods_values[12]*/ mload(add(context, 0x3300)))),
                           PRIME))
                }

                // Mask items for column #11.
                {
                // Read the next element.
                let columnValue := mulmod(mload(add(traceQueryResponses, 0x160)), kMontgomeryRInv, PRIME)

                // res += c_13*(f_11(x) - f_11(z)) / (x - z).
                res := add(
                    res,
                    mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr),
                                  /*oods_coefficients[13]*/ mload(add(context, 0x3c20)),
                                  PRIME),
                           add(columnValue, sub(PRIME, /*oods_values[13]*/ mload(add(context, 0x3320)))),
                           PRIME))
                }

                // Mask items for column #12.
                {
                // Read the next element.
                let columnValue := mulmod(mload(add(traceQueryResponses, 0x180)), kMontgomeryRInv, PRIME)

                // res += c_14*(f_12(x) - f_12(z)) / (x - z).
                res := add(
                    res,
                    mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr),
                                  /*oods_coefficients[14]*/ mload(add(context, 0x3c40)),
                                  PRIME),
                           add(columnValue, sub(PRIME, /*oods_values[14]*/ mload(add(context, 0x3340)))),
                           PRIME))
                }

                // Mask items for column #13.
                {
                // Read the next element.
                let columnValue := mulmod(mload(add(traceQueryResponses, 0x1a0)), kMontgomeryRInv, PRIME)

                // res += c_15*(f_13(x) - f_13(z)) / (x - z).
                res := add(
                    res,
                    mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr),
                                  /*oods_coefficients[15]*/ mload(add(context, 0x3c60)),
                                  PRIME),
                           add(columnValue, sub(PRIME, /*oods_values[15]*/ mload(add(context, 0x3360)))),
                           PRIME))
                }

                // Mask items for column #14.
                {
                // Read the next element.
                let columnValue := mulmod(mload(add(traceQueryResponses, 0x1c0)), kMontgomeryRInv, PRIME)

                // res += c_16*(f_14(x) - f_14(z)) / (x - z).
                res := add(
                    res,
                    mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr),
                                  /*oods_coefficients[16]*/ mload(add(context, 0x3c80)),
                                  PRIME),
                           add(columnValue, sub(PRIME, /*oods_values[16]*/ mload(add(context, 0x3380)))),
                           PRIME))
                }

                // Mask items for column #15.
                {
                // Read the next element.
                let columnValue := mulmod(mload(add(traceQueryResponses, 0x1e0)), kMontgomeryRInv, PRIME)

                // res += c_17*(f_15(x) - f_15(z)) / (x - z).
                res := add(
                    res,
                    mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr),
                                  /*oods_coefficients[17]*/ mload(add(context, 0x3ca0)),
                                  PRIME),
                           add(columnValue, sub(PRIME, /*oods_values[17]*/ mload(add(context, 0x33a0)))),
                           PRIME))
                }

                // Mask items for column #16.
                {
                // Read the next element.
                let columnValue := mulmod(mload(add(traceQueryResponses, 0x200)), kMontgomeryRInv, PRIME)

                // res += c_18*(f_16(x) - f_16(z)) / (x - z).
                res := add(
                    res,
                    mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr),
                                  /*oods_coefficients[18]*/ mload(add(context, 0x3cc0)),
                                  PRIME),
                           add(columnValue, sub(PRIME, /*oods_values[18]*/ mload(add(context, 0x33c0)))),
                           PRIME))
                }

                // Mask items for column #17.
                {
                // Read the next element.
                let columnValue := mulmod(mload(add(traceQueryResponses, 0x220)), kMontgomeryRInv, PRIME)

                // res += c_19*(f_17(x) - f_17(z)) / (x - z).
                res := add(
                    res,
                    mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr),
                                  /*oods_coefficients[19]*/ mload(add(context, 0x3ce0)),
                                  PRIME),
                           add(columnValue, sub(PRIME, /*oods_values[19]*/ mload(add(context, 0x33e0)))),
                           PRIME))
                }

                // Mask items for column #18.
                {
                // Read the next element.
                let columnValue := mulmod(mload(add(traceQueryResponses, 0x240)), kMontgomeryRInv, PRIME)

                // res += c_20*(f_18(x) - f_18(z)) / (x - z).
                res := add(
                    res,
                    mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr),
                                  /*oods_coefficients[20]*/ mload(add(context, 0x3d00)),
                                  PRIME),
                           add(columnValue, sub(PRIME, /*oods_values[20]*/ mload(add(context, 0x3400)))),
                           PRIME))
                }

                // Mask items for column #19.
                {
                // Read the next element.
                let columnValue := mulmod(mload(add(traceQueryResponses, 0x260)), kMontgomeryRInv, PRIME)

                // res += c_21*(f_19(x) - f_19(z)) / (x - z).
                res := add(
                    res,
                    mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr),
                                  /*oods_coefficients[21]*/ mload(add(context, 0x3d20)),
                                  PRIME),
                           add(columnValue, sub(PRIME, /*oods_values[21]*/ mload(add(context, 0x3420)))),
                           PRIME))
                }

                // Advance traceQueryResponses by amount read (0x20 * nTraceColumns).
                traceQueryResponses := add(traceQueryResponses, 0x280)

                // Composition constraints.

                {
                // Read the next element.
                let columnValue := mulmod(mload(compositionQueryResponses), kMontgomeryRInv, PRIME)
                // res += c_22*(h_0(x) - C_0(z^2)) / (x - z^2).
                res := add(
                    res,
                    mulmod(mulmod(/*(x - z^2)^(-1)*/ mload(add(denominatorsPtr, 0x40)),
                                  /*oods_coefficients[22]*/ mload(add(context, 0x3d40)),
                                  PRIME),
                           add(columnValue, sub(PRIME, /*composition_oods_values[0]*/ mload(add(context, 0x3440)))),
                           PRIME))
                }

                {
                // Read the next element.
                let columnValue := mulmod(mload(add(compositionQueryResponses, 0x20)), kMontgomeryRInv, PRIME)
                // res += c_23*(h_1(x) - C_1(z^2)) / (x - z^2).
                res := add(
                    res,
                    mulmod(mulmod(/*(x - z^2)^(-1)*/ mload(add(denominatorsPtr, 0x40)),
                                  /*oods_coefficients[23]*/ mload(add(context, 0x3d60)),
                                  PRIME),
                           add(columnValue, sub(PRIME, /*composition_oods_values[1]*/ mload(add(context, 0x3460)))),
                           PRIME))
                }

                // Advance compositionQueryResponses by amount read (0x20 * constraintDegree).
                compositionQueryResponses := add(compositionQueryResponses, 0x40)

                // Append the friValue, which is the sum of the out-of-domain-sampling boundary
                // constraints for the trace and composition polynomials, to the friQueue array.
                mstore(add(friQueue, 0x20), mod(res, PRIME))

                // Append the friInvPoint of the current query to the friQueue array.
                mstore(add(friQueue, 0x40), /*friInvPoint*/ mload(add(denominatorsPtr,0x60)))

                // Advance denominatorsPtr by chunk size (0x20 * (2+N_ROWS_IN_MASK)).
                denominatorsPtr := add(denominatorsPtr, 0x80)
            }
            return(/*friQueue*/ add(context, 0xda0), 0x1200)
        }
    }

    /*
      Computes and performs batch inverse on all the denominators required for the out of domain
      sampling boundary constraints.

      Since the friEvalPoints are calculated during the computation of the denominators
      this function also adds those to the batch inverse in prepartion for the fri that follows.

      After this function returns, the batch_inverse_out array holds #queries
      chunks of size (2 + N_ROWS_IN_MASK) with the following structure:
      0..(N_ROWS_IN_MASK-1):   [(x - g^i * z)^(-1) for i in rowsInMask]
      N_ROWS_IN_MASK:          (x - z^constraintDegree)^-1
      N_ROWS_IN_MASK+1:        friEvalPointInv.
    */
    function oodsPrepareInverses(
        uint256[] memory context, uint256[] memory batchInverseArray)
        internal view {
        uint256 evalCosetOffset_ = PrimeFieldElement6.GENERATOR_VAL;
        // The array expmodsAndPoints stores subexpressions that are needed
        // for the denominators computation.
        // The array is segmented as follows:
        //    expmodsAndPoints[0:0] (.expmods) expmods used during calculations of the points below.
        //    expmodsAndPoints[0:2] (.points) points used during the denominators calculation.
        uint256[2] memory expmodsAndPoints;
        assembly {
            function expmod(base, exponent, modulus) -> res {
              let p := mload(0x40)
              mstore(p, 0x20)                 // Length of Base.
              mstore(add(p, 0x20), 0x20)      // Length of Exponent.
              mstore(add(p, 0x40), 0x20)      // Length of Modulus.
              mstore(add(p, 0x60), base)      // Base.
              mstore(add(p, 0x80), exponent)  // Exponent.
              mstore(add(p, 0xa0), modulus)   // Modulus.
              // Call modexp precompile.
              if iszero(staticcall(not(0), 0x05, p, 0xc0, p, 0x20)) {
                revert(0, 0)
              }
              res := mload(p)
            }

            let traceGenerator := /*trace_generator*/ mload(add(context, 0x2b40))
            let PRIME := 0x30000003000000010000000000000001

            // Prepare expmods for computations of trace generator powers.

            let oodsPoint := /*oods_point*/ mload(add(context, 0x2b60))
            {
              // point = -z.
              let point := sub(PRIME, oodsPoint)
              // Compute denominators for rows with nonconst mask expression.
              // We compute those first because for the const rows we modify the point variable.

              // Compute denominators for rows with const mask expression.

              // expmods_and_points.points[0] = -z.
              mstore(add(expmodsAndPoints, 0x0), point)

              // point *= g.
              point := mulmod(point, traceGenerator, PRIME)
              // expmods_and_points.points[1] = -(g * z).
              mstore(add(expmodsAndPoints, 0x20), point)
            }


            let evalPointsPtr := /*oodsEvalPoints*/ add(context, 0x3480)
            let evalPointsEndPtr := add(evalPointsPtr,
                                           mul(/*n_unique_queries*/ mload(add(context, 0x120)), 0x20))
            let productsPtr := add(batchInverseArray, 0x20)
            let valuesPtr := add(add(batchInverseArray, 0x20), 0x1800)
            let partialProduct := 1
            let minusPointPow := sub(PRIME, mulmod(oodsPoint, oodsPoint, PRIME))
            for {} lt(evalPointsPtr, evalPointsEndPtr)
                     {evalPointsPtr := add(evalPointsPtr, 0x20)} {
                let evalPoint := mload(evalPointsPtr)

                // Shift evalPoint to evaluation domain coset.
                let shiftedEvalPoint := mulmod(evalPoint, evalCosetOffset_, PRIME)

                {
                // Calculate denominator for row 0: x - z.
                let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x0)))
                mstore(productsPtr, partialProduct)
                mstore(valuesPtr, denominator)
                partialProduct := mulmod(partialProduct, denominator, PRIME)
                }

                {
                // Calculate denominator for row 1: x - g * z.
                let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x20)))
                mstore(add(productsPtr, 0x20), partialProduct)
                mstore(add(valuesPtr, 0x20), denominator)
                partialProduct := mulmod(partialProduct, denominator, PRIME)
                }

                {
                // Calculate the denominator for the composition polynomial columns: x - z^2.
                let denominator := add(shiftedEvalPoint, minusPointPow)
                mstore(add(productsPtr, 0x40), partialProduct)
                mstore(add(valuesPtr, 0x40), denominator)
                partialProduct := mulmod(partialProduct, denominator, PRIME)
                }

                // Add evalPoint to batch inverse inputs.
                // inverse(evalPoint) is going to be used by FRI.
                mstore(add(productsPtr, 0x60), partialProduct)
                mstore(add(valuesPtr, 0x60), evalPoint)
                partialProduct := mulmod(partialProduct, evalPoint, PRIME)

                // Advance pointers.
                productsPtr := add(productsPtr, 0x80)
                valuesPtr := add(valuesPtr, 0x80)
            }

            let productsToValuesOffset := 0x1800
            let firstPartialProductPtr := add(batchInverseArray, 0x20)
            // Compute the inverse of the product.
            let prodInv := expmod(partialProduct, sub(PRIME, 2), PRIME)

            if eq(prodInv, 0) {
                // Solidity generates reverts with reason that look as follows:
                // 1. 4 bytes with the constant 0x08c379a0 (== Keccak256(b'Error(string)')[:4]).
                // 2. 32 bytes offset bytes (always 0x20 as far as i can tell).
                // 3. 32 bytes with the length of the revert reason.
                // 4. Revert reason string.

                mstore(0, 0x08c379a000000000000000000000000000000000000000000000000000000000)
                mstore(0x4, 0x20)
                mstore(0x24, 0x1e)
                mstore(0x44, "Batch inverse product is zero.")
                revert(0, 0x62)
            }

            // Compute the inverses.
            // Loop over denominator_invs in reverse order.
            // currentPartialProductPtr is initialized to one past the end.
            let currentPartialProductPtr := productsPtr
            // Loop in blocks of size 8 as much as possible: we can loop over a full block as long as
            // currentPartialProductPtr >= firstPartialProductPtr + 8*0x20, or equivalently,
            // currentPartialProductPtr > firstPartialProductPtr + 7*0x20.
            // We use the latter comparison since there is no >= evm opcode.
            let midPartialProductPtr := add(firstPartialProductPtr, 0xe0)
            for { } gt(currentPartialProductPtr, midPartialProductPtr) { } {
                currentPartialProductPtr := sub(currentPartialProductPtr, 0x20)
                // Store 1/d_{i} = (d_0 * ... * d_{i-1}) * 1/(d_0 * ... * d_{i}).
                mstore(currentPartialProductPtr,
                       mulmod(mload(currentPartialProductPtr), prodInv, PRIME))
                // Update prodInv to be 1/(d_0 * ... * d_{i-1}) by multiplying by d_i.
                prodInv := mulmod(prodInv,
                                   mload(add(currentPartialProductPtr, productsToValuesOffset)),
                                   PRIME)

                currentPartialProductPtr := sub(currentPartialProductPtr, 0x20)
                // Store 1/d_{i} = (d_0 * ... * d_{i-1}) * 1/(d_0 * ... * d_{i}).
                mstore(currentPartialProductPtr,
                       mulmod(mload(currentPartialProductPtr), prodInv, PRIME))
                // Update prodInv to be 1/(d_0 * ... * d_{i-1}) by multiplying by d_i.
                prodInv := mulmod(prodInv,
                                   mload(add(currentPartialProductPtr, productsToValuesOffset)),
                                   PRIME)

                currentPartialProductPtr := sub(currentPartialProductPtr, 0x20)
                // Store 1/d_{i} = (d_0 * ... * d_{i-1}) * 1/(d_0 * ... * d_{i}).
                mstore(currentPartialProductPtr,
                       mulmod(mload(currentPartialProductPtr), prodInv, PRIME))
                // Update prodInv to be 1/(d_0 * ... * d_{i-1}) by multiplying by d_i.
                prodInv := mulmod(prodInv,
                                   mload(add(currentPartialProductPtr, productsToValuesOffset)),
                                   PRIME)

                currentPartialProductPtr := sub(currentPartialProductPtr, 0x20)
                // Store 1/d_{i} = (d_0 * ... * d_{i-1}) * 1/(d_0 * ... * d_{i}).
                mstore(currentPartialProductPtr,
                       mulmod(mload(currentPartialProductPtr), prodInv, PRIME))
                // Update prodInv to be 1/(d_0 * ... * d_{i-1}) by multiplying by d_i.
                prodInv := mulmod(prodInv,
                                   mload(add(currentPartialProductPtr, productsToValuesOffset)),
                                   PRIME)

                currentPartialProductPtr := sub(currentPartialProductPtr, 0x20)
                // Store 1/d_{i} = (d_0 * ... * d_{i-1}) * 1/(d_0 * ... * d_{i}).
                mstore(currentPartialProductPtr,
                       mulmod(mload(currentPartialProductPtr), prodInv, PRIME))
                // Update prodInv to be 1/(d_0 * ... * d_{i-1}) by multiplying by d_i.
                prodInv := mulmod(prodInv,
                                   mload(add(currentPartialProductPtr, productsToValuesOffset)),
                                   PRIME)

                currentPartialProductPtr := sub(currentPartialProductPtr, 0x20)
                // Store 1/d_{i} = (d_0 * ... * d_{i-1}) * 1/(d_0 * ... * d_{i}).
                mstore(currentPartialProductPtr,
                       mulmod(mload(currentPartialProductPtr), prodInv, PRIME))
                // Update prodInv to be 1/(d_0 * ... * d_{i-1}) by multiplying by d_i.
                prodInv := mulmod(prodInv,
                                   mload(add(currentPartialProductPtr, productsToValuesOffset)),
                                   PRIME)

                currentPartialProductPtr := sub(currentPartialProductPtr, 0x20)
                // Store 1/d_{i} = (d_0 * ... * d_{i-1}) * 1/(d_0 * ... * d_{i}).
                mstore(currentPartialProductPtr,
                       mulmod(mload(currentPartialProductPtr), prodInv, PRIME))
                // Update prodInv to be 1/(d_0 * ... * d_{i-1}) by multiplying by d_i.
                prodInv := mulmod(prodInv,
                                   mload(add(currentPartialProductPtr, productsToValuesOffset)),
                                   PRIME)

                currentPartialProductPtr := sub(currentPartialProductPtr, 0x20)
                // Store 1/d_{i} = (d_0 * ... * d_{i-1}) * 1/(d_0 * ... * d_{i}).
                mstore(currentPartialProductPtr,
                       mulmod(mload(currentPartialProductPtr), prodInv, PRIME))
                // Update prodInv to be 1/(d_0 * ... * d_{i-1}) by multiplying by d_i.
                prodInv := mulmod(prodInv,
                                   mload(add(currentPartialProductPtr, productsToValuesOffset)),
                                   PRIME)
            }

            // Loop over the remainder.
            for { } gt(currentPartialProductPtr, firstPartialProductPtr) { } {
                currentPartialProductPtr := sub(currentPartialProductPtr, 0x20)
                // Store 1/d_{i} = (d_0 * ... * d_{i-1}) * 1/(d_0 * ... * d_{i}).
                mstore(currentPartialProductPtr,
                       mulmod(mload(currentPartialProductPtr), prodInv, PRIME))
                // Update prodInv to be 1/(d_0 * ... * d_{i-1}) by multiplying by d_i.
                prodInv := mulmod(prodInv,
                                   mload(add(currentPartialProductPtr, productsToValuesOffset)),
                                   PRIME)
            }
        }
    }
}
// ---------- End of auto-generated code. ----------

// File: MimcVerifier.sol



pragma solidity ^0.5.2;

import "./StarkVerifier.sol";
import "./StarkParameters.sol";
import "./MimcConstraintPoly.sol";
import "./MimcOods.sol";
import "./PublicInputOffsets.sol";
import "./FactRegistry.sol";

contract PeriodicColumnContract {
    function compute(uint256 x) external pure returns(uint256 result);
}

contract MimcVerifier is StarkParameters, StarkVerifier, FactRegistry, PublicInputOffsets{

    MimcConstraintPoly constraintPoly;
    PeriodicColumnContract[20] constantsCols;

    constructor(
        address[] memory auxPolynomials,
        MimcOods oodsContract,
        uint256 numSecurityBits_,
        uint256 minProofOfWorkBits_)
        StarkVerifier(
            numSecurityBits_,
            minProofOfWorkBits_
        )
        public {
        constraintPoly = MimcConstraintPoly(auxPolynomials[0]);
        for(uint256 i=0; i < 20; i++){
            constantsCols[i] = PeriodicColumnContract(auxPolynomials[i+1]);
        }
        oodsContractAddress = address(oodsContract);
    }

    function verifyProofAndRegister(
        uint256[] calldata proofParams,
        uint256[] calldata proof,
        uint256[] calldata publicInput
    )
        external
    {
        verifyProof(proofParams, proof, publicInput);
        registerFact(keccak256(abi.encodePacked(publicInput)));
    }

    function getNColumnsInTrace() internal pure returns(uint256) {
        return N_COLUMNS_IN_MASK;
    }

    function getNColumnsInComposition() internal pure returns(uint256) {
        return CONSTRAINTS_DEGREE_BOUND;
    }

    function getMmCoefficients() internal pure returns(uint256) {
        return MM_COEFFICIENTS;
    }

    function getMmOodsValues() internal pure returns(uint256) {
        return MM_OODS_VALUES;
    }

    function getMmOodsCoefficients() internal pure returns(uint256) {
        return MM_OODS_COEFFICIENTS;
    }

    function getNCoefficients() internal pure returns(uint256) {
        return N_COEFFICIENTS;
    }

    function getNOodsValues() internal pure returns(uint256) {
        return N_OODS_VALUES;
    }

    function getNOodsCoefficients() internal pure returns(uint256) {
        return N_OODS_COEFFICIENTS;
    }

    function airSpecificInit(uint256[] memory publicInput)
        internal returns (uint256[] memory ctx, uint256 logTraceLength)
    {
        ctx = new uint256[](MM_CONTEXT_SIZE);

        // Context for generated code.
        // Note that the prover does the VDF computation the other way around (uses the inverse
        // function), hence vdf_output is the input for its calculation, and vdf_input should be the
        // result of the calculation.
        ctx[MM_INPUT_VALUE_A] = publicInput[OFFSET_VDF_OUTPUT_X];
        ctx[MM_INPUT_VALUE_B] = publicInput[OFFSET_VDF_OUTPUT_Y];
        ctx[MM_OUTPUT_VALUE_A] = publicInput[OFFSET_VDF_INPUT_X];
        ctx[MM_OUTPUT_VALUE_B] = publicInput[OFFSET_VDF_INPUT_Y];

        // Initialize the MDS matrix values with fixed predefined values.
        ctx[MM_MAT00] = 0x109bbc181e07a285856e0d8bde02619;
        ctx[MM_MAT01] = 0x1eb8859b1b789cd8a80927a32fdf41f7;
        ctx[MM_MAT10] = 0xdc8eaac802c8f9cb9dff6ed0728012d;
        ctx[MM_MAT11] = 0x2c18506f35eab63b58143a34181c89e;

        logTraceLength = publicInput[OFFSET_LOG_TRACE_LENGTH];
        require(logTraceLength <= 50, "logTraceLength must not exceed 50.");
    }

    function getPublicInputHash(uint256[] memory publicInput)
        internal pure
        returns (bytes32) {
        return keccak256(
            abi.encodePacked(
                uint64(2 ** publicInput[OFFSET_LOG_TRACE_LENGTH]),
                publicInput[OFFSET_VDF_OUTPUT_X],
                publicInput[OFFSET_VDF_OUTPUT_Y],
                publicInput[OFFSET_VDF_INPUT_X],
                publicInput[OFFSET_VDF_INPUT_Y])
        );
    }

    /*
      Checks that the trace and the composition agree on the Out of Domain Sampling point, assuming
      the prover provided us with the proper evaluations.

      Later, we use boundary constraints to check that those evaluations are actually
      consistent with the committed trace and composition polynomials.
    */
    function oodsConsistencyCheck(uint256[] memory ctx)
        internal {
        uint256 oodsPoint = ctx[MM_OODS_POINT];
        uint256 nRows = 256;
        uint256 zPointPow = fpow(oodsPoint, ctx[MM_TRACE_LENGTH] / nRows);

        ctx[MM_PERIODIC_COLUMN__CONSTS0_A] = constantsCols[0].compute(zPointPow);
        ctx[MM_PERIODIC_COLUMN__CONSTS1_A] = constantsCols[1].compute(zPointPow);
        ctx[MM_PERIODIC_COLUMN__CONSTS2_A] = constantsCols[2].compute(zPointPow);
        ctx[MM_PERIODIC_COLUMN__CONSTS3_A] = constantsCols[3].compute(zPointPow);
        ctx[MM_PERIODIC_COLUMN__CONSTS4_A] = constantsCols[4].compute(zPointPow);
        ctx[MM_PERIODIC_COLUMN__CONSTS5_A] = constantsCols[5].compute(zPointPow);
        ctx[MM_PERIODIC_COLUMN__CONSTS6_A] = constantsCols[6].compute(zPointPow);
        ctx[MM_PERIODIC_COLUMN__CONSTS7_A] = constantsCols[7].compute(zPointPow);
        ctx[MM_PERIODIC_COLUMN__CONSTS8_A] = constantsCols[8].compute(zPointPow);
        ctx[MM_PERIODIC_COLUMN__CONSTS9_A] = constantsCols[9].compute(zPointPow);

        ctx[MM_PERIODIC_COLUMN__CONSTS0_B] = constantsCols[10].compute(zPointPow);
        ctx[MM_PERIODIC_COLUMN__CONSTS1_B] = constantsCols[11].compute(zPointPow);
        ctx[MM_PERIODIC_COLUMN__CONSTS2_B] = constantsCols[12].compute(zPointPow);
        ctx[MM_PERIODIC_COLUMN__CONSTS3_B] = constantsCols[13].compute(zPointPow);
        ctx[MM_PERIODIC_COLUMN__CONSTS4_B] = constantsCols[14].compute(zPointPow);
        ctx[MM_PERIODIC_COLUMN__CONSTS5_B] = constantsCols[15].compute(zPointPow);
        ctx[MM_PERIODIC_COLUMN__CONSTS6_B] = constantsCols[16].compute(zPointPow);
        ctx[MM_PERIODIC_COLUMN__CONSTS7_B] = constantsCols[17].compute(zPointPow);
        ctx[MM_PERIODIC_COLUMN__CONSTS8_B] = constantsCols[18].compute(zPointPow);
        ctx[MM_PERIODIC_COLUMN__CONSTS9_B] = constantsCols[19].compute(zPointPow);

        uint256 compositionFromTraceValue;
        address lconstraintPoly = address(constraintPoly);
        uint256 offset = 0x20 * (1 + MM_CONSTRAINT_POLY_ARGS_START);
        uint256 size = 0x20 * (MM_CONSTRAINT_POLY_ARGS_END - MM_CONSTRAINT_POLY_ARGS_START);
        assembly {
            // Call MimcConstraintPoly contract.
            let p := mload(0x40)
            if iszero(staticcall(not(0), lconstraintPoly, add(ctx, offset), size, p, 0x20)) {
              returndatacopy(0, 0, returndatasize)
              revert(0, returndatasize)
            }
            compositionFromTraceValue := mload(p)
        }

        uint256 claimedComposition = fadd(
            ctx[MM_OODS_VALUES + MASK_SIZE],
            fmul(oodsPoint, ctx[MM_OODS_VALUES + MASK_SIZE + 1]));

        require(
            compositionFromTraceValue == claimedComposition,
            "claimedComposition does not match trace");
    }
}

// File: PrimeFieldElement6.sol



pragma solidity ^0.5.2;


contract PrimeFieldElement6 {
    uint256 internal constant K_MODULUS = 0x30000003000000010000000000000001;
    uint256 internal constant K_MODULUS_MASK = 0x3fffffffffffffffffffffffffffffff;
    uint256 internal constant K_MONTGOMERY_R = 0xffffff0fffffffafffffffffffffffb;
    uint256 internal constant K_MONTGOMERY_R_INV = 0x9000001200000096000000600000001;
    uint256 internal constant GENERATOR_VAL = 3;
    uint256 internal constant ONE_VAL = 1;
    uint256 internal constant GEN1024_VAL = 0x2361be682e1cc2d366e86e194024739f;

    function fromMontgomery(uint256 val) internal pure returns (uint256 res) {
        // uint256 res = fmul(val, kMontgomeryRInv);
        assembly {
            res := mulmod(
                val,
                0x9000001200000096000000600000001,
                0x30000003000000010000000000000001
            )
        }
        return res;
    }

    function fromMontgomeryBytes(bytes32 bs) internal pure returns (uint256) {
        // Assuming bs is a 256bit bytes object, in Montgomery form, it is read into a field
        // element.
        uint256 res = uint256(bs);
        return fromMontgomery(res);
    }

    function toMontgomeryInt(uint256 val) internal pure returns (uint256 res) {
        //uint256 res = fmul(val, kMontgomeryR);
        assembly {
            res := mulmod(
                val,
                0xffffff0fffffffafffffffffffffffb,
                0x30000003000000010000000000000001
            )
        }
        return res;
    }

    function fmul(uint256 a, uint256 b) internal pure returns (uint256 res) {
        //uint256 res = mulmod(a, b, kModulus);
        assembly {
            res := mulmod(a, b, 0x30000003000000010000000000000001)
        }
        return res;
    }

    function fadd(uint256 a, uint256 b) internal pure returns (uint256 res) {
        // uint256 res = addmod(a, b, kModulus);
        assembly {
            res := addmod(a, b, 0x30000003000000010000000000000001)
        }
        return res;
    }

    function fsub(uint256 a, uint256 b) internal pure returns (uint256 res) {
        // uint256 res = addmod(a, kModulus - b, kModulus);
        assembly {
            res := addmod(
                a,
                sub(0x30000003000000010000000000000001, b),
                0x30000003000000010000000000000001
            )
        }
        return res;
    }

    function fpow(uint256 val, uint256 exp) internal returns (uint256) {
        return expmod(val, exp, K_MODULUS);
    }

    function expmod(uint256 base, uint256 exponent, uint256 modulus)
        internal
        returns (uint256 res)
    {
        assembly {
            let p := mload(0x40)
            mstore(p, 0x20) // Length of Base.
            mstore(add(p, 0x20), 0x20) // Length of Exponent.
            mstore(add(p, 0x40), 0x20) // Length of Modulus.
            mstore(add(p, 0x60), base) // Base.
            mstore(add(p, 0x80), exponent) // Exponent.
            mstore(add(p, 0xa0), modulus) // Modulus.
            // Call modexp precompile.
            if iszero(call(not(0), 0x05, 0, p, 0xc0, p, 0x20)) {
                revert(0, 0)
            }
            res := mload(p)
        }
    }

    function inverse(uint256 val) internal returns (uint256) {
        return expmod(val, K_MODULUS - 2, K_MODULUS);
    }
}

// File: Prng.sol



pragma solidity ^0.5.2;

import "./PrimeFieldElement6.sol";

contract Prng is PrimeFieldElement6 {
    function storePrng(uint256 statePtr, bytes32 digest, uint256 counter)
        internal pure {
        assembly {
            mstore(statePtr, digest)
            mstore(add(statePtr, 0x20), counter)
        }
    }

    function loadPrng(uint256 statePtr)
        internal pure
        returns (bytes32, uint256) {
        bytes32 digest;
        uint256 counter;

        assembly {
            digest := mload(statePtr)
            counter := mload(add(statePtr, 0x20))
        }

        return (digest, counter);
    }

    function initPrng(uint256 prngPtr, bytes32 publicInputHash)
        internal pure
    {
        storePrng(prngPtr, /*keccak256(publicInput)*/ publicInputHash, 0);
    }

    /*
      Auxiliary function for getRandomBytes.
    */
    function getRandomBytesInner(bytes32 digest, uint256 counter)
        internal pure
        returns (bytes32, uint256, bytes32)
    {
        // returns 32 bytes (for random field elements or four queries at a time).
        bytes32 randomBytes = keccak256(abi.encodePacked(digest, counter));

        return (digest, counter + 1, randomBytes);
    }

    /*
      Returns 32 bytes. Used for a random field element, or for 4 query indices.
    */
    function getRandomBytes(uint256 prngPtr)
        internal pure
        returns (bytes32 randomBytes)
    {
        bytes32 digest;
        uint256 counter;
        (digest, counter) = loadPrng(prngPtr);

        // returns 32 bytes (for random field elements or four queries at a time).
        (digest, counter, randomBytes) = getRandomBytesInner(digest, counter);

        storePrng(prngPtr, digest, counter);
        return randomBytes;
    }

    function mixSeedWithBytes(uint256 prngPtr, bytes memory dataBytes)
        internal pure
    {
        bytes32 digest;

        assembly {
            digest := mload(prngPtr)
        }
        initPrng(prngPtr, keccak256(abi.encodePacked(digest, dataBytes)));
    }

    function getPrngDigest(uint256 prngPtr)
        internal pure
        returns (bytes32 digest)
    {
        assembly {
           digest := mload(prngPtr)
        }
    }
}

// File: PublicInputOffsets.sol



pragma solidity ^0.5.2;


contract PublicInputOffsets {
    // The following constants are offsets of data expected in the public input.
    uint256 internal constant OFFSET_LOG_TRACE_LENGTH = 0;
    uint256 internal constant OFFSET_VDF_OUTPUT_X = 1;
    uint256 internal constant OFFSET_VDF_OUTPUT_Y = 2;
    uint256 internal constant OFFSET_VDF_INPUT_X = 3;
    uint256 internal constant OFFSET_VDF_INPUT_Y = 4;
}

// File: StarkParameters.sol



// ---------- The following code was auto-generated. PLEASE DO NOT EDIT. ----------
pragma solidity ^0.5.2;

import "./PrimeFieldElement6.sol";

contract StarkParameters is PrimeFieldElement6 {
    uint256 constant internal N_COEFFICIENTS = 48;
    uint256 constant internal MASK_SIZE = 22;
    uint256 constant internal N_ROWS_IN_MASK = 2;
    uint256 constant internal N_COLUMNS_IN_MASK = 20;
    uint256 constant internal CONSTRAINTS_DEGREE_BOUND = 2;
    uint256 constant internal N_OODS_VALUES = MASK_SIZE + CONSTRAINTS_DEGREE_BOUND;
    uint256 constant internal N_OODS_COEFFICIENTS = N_OODS_VALUES;
    uint256 constant internal MAX_FRI_STEP = 3;
}
// ---------- End of auto-generated code. ----------

// File: StarkVerifier.sol



pragma solidity ^0.5.2;

import "./Fri.sol";
import "./MemoryMap.sol";
import "./MemoryAccessUtils.sol";
import "./IStarkVerifier.sol";
import "./VerifierChannel.sol";


contract StarkVerifier is MemoryMap, MemoryAccessUtils, VerifierChannel, IStarkVerifier, Fri {
    /*
      The work required to generate an invalid proof is 2^numSecurityBits.
      Typical values: 80-128.
    */
    uint256 numSecurityBits;

    /*
      The secuirty of a proof is a composition of bits obtained by PoW and bits obtained by FRI
      queries. The verifier requires at least minProofOfWorkBits to be obtained by PoW.
      Typical values: 20-30.
    */
    uint256 minProofOfWorkBits;

    constructor(uint256 numSecurityBits_, uint256 minProofOfWorkBits_) public {
        numSecurityBits = numSecurityBits_;
        minProofOfWorkBits = minProofOfWorkBits_;
    }

    /*
      To print LogDebug messages from assembly use code like the following:

      assembly {
            let val := 0x1234
            mstore(0, val) // uint256 val
            // log to the LogDebug(uint256) topic
            log1(0, 0x20, 0x2feb477e5c8c82cfb95c787ed434e820b1a28fa84d68bbf5aba5367382f5581c)
      }

      Note that you can't use log in a contract that was called with staticcall
      (ContraintPoly, Oods,...)

      If logging is needed replace the staticcall to call and add a third argument of 0.
    */
    event LogBool(bool val);
    event LogDebug(uint256 val);
    address oodsContractAddress;

    function airSpecificInit(uint256[] memory publicInput)
        internal returns (uint256[] memory ctx, uint256 logTraceLength);

    uint256 constant internal PROOF_PARAMS_N_QUERIES_OFFSET = 0;
    uint256 constant internal PROOF_PARAMS_LOG_BLOWUP_FACTOR_OFFSET = 1;
    uint256 constant internal PROOF_PARAMS_PROOF_OF_WORK_BITS_OFFSET = 2;
    uint256 constant internal PROOF_PARAMS_FRI_LAST_LAYER_DEG_BOUND_OFFSET = 3;
    uint256 constant internal PROOF_PARAMS_N_FRI_STEPS_OFFSET = 4;
    uint256 constant internal PROOF_PARAMS_FRI_STEPS_OFFSET = 5;

    function validateFriParams(
        uint256[] memory friSteps, uint256 logTraceLength, uint256 logFriLastLayerDegBound)
        internal pure {
        require (friSteps[0] == 0, "Only eta0 == 0 is currently supported");

        uint256 expectedLogDegBound = logFriLastLayerDegBound;
        uint256 nFriSteps = friSteps.length;
        for (uint256 i = 1; i < nFriSteps; i++) {
            uint256 friStep = friSteps[i];
            require(friStep > 0, "Only the first fri step can be 0");
            require(friStep <= 4, "Max supported fri step is 4.");
            expectedLogDegBound += friStep;
        }

        // FRI starts with a polynomial of degree 'traceLength'.
        // After applying all the FRI steps we expect to get a polynomial of degree less
        // than friLastLayerDegBound.
        require (
            expectedLogDegBound == logTraceLength, "Fri params do not match trace length");
    }

    function initVerifierParams(uint256[] memory publicInput, uint256[] memory proofParams)
        internal returns (uint256[] memory ctx) {
        require (proofParams.length > PROOF_PARAMS_FRI_STEPS_OFFSET, "Invalid proofParams.");
        require (
            proofParams.length == (
                PROOF_PARAMS_FRI_STEPS_OFFSET + proofParams[PROOF_PARAMS_N_FRI_STEPS_OFFSET]),
            "Invalid proofParams.");
        uint256 logBlowupFactor = proofParams[PROOF_PARAMS_LOG_BLOWUP_FACTOR_OFFSET];
        require (logBlowupFactor <= 16, "logBlowupFactor must be at most 16");
        require (logBlowupFactor >= 1, "logBlowupFactor must be at least 1");

        uint256 proofOfWorkBits = proofParams[PROOF_PARAMS_PROOF_OF_WORK_BITS_OFFSET];
        require (proofOfWorkBits <= 50, "proofOfWorkBits must be at most 50");
        require (proofOfWorkBits >= minProofOfWorkBits, "minimum proofOfWorkBits not satisfied");
        require (proofOfWorkBits < numSecurityBits, "Proofs may not be purely based on PoW.");

        uint256 logFriLastLayerDegBound = (
            proofParams[PROOF_PARAMS_FRI_LAST_LAYER_DEG_BOUND_OFFSET]
        );
        require (
            logFriLastLayerDegBound <= 10, "logFriLastLayerDegBound must be at most 10.");

        uint256 nFriSteps = proofParams[PROOF_PARAMS_N_FRI_STEPS_OFFSET];
        require (nFriSteps <= 10, "Too many fri steps.");
        require (nFriSteps > 1, "Not enough fri steps.");

        uint256[] memory friSteps = new uint256[](nFriSteps);
        for (uint256 i = 0; i < nFriSteps; i++) {
            friSteps[i] = proofParams[PROOF_PARAMS_FRI_STEPS_OFFSET + i];
        }

        uint256 logTraceLength;
        (ctx, logTraceLength) = airSpecificInit(publicInput);

        validateFriParams(friSteps, logTraceLength, logFriLastLayerDegBound);

        uint256 friStepsPtr = getPtr(ctx, MM_FRI_STEPS_PTR);
        assembly {
            mstore(friStepsPtr, friSteps)
        }
        ctx[MM_FRI_LAST_LAYER_DEG_BOUND] = 2**logFriLastLayerDegBound;
        ctx[MM_TRACE_LENGTH] = 2 ** logTraceLength;

        ctx[MM_BLOW_UP_FACTOR] = 2**logBlowupFactor;
        ctx[MM_PROOF_OF_WORK_BITS] = proofOfWorkBits;

        uint256 nQueries = proofParams[PROOF_PARAMS_N_QUERIES_OFFSET];
        require (nQueries > 0, "Number of queries must be at least one");
        require (nQueries <= MAX_N_QUERIES, "Too many queries.");
        require (
            nQueries * logBlowupFactor + proofOfWorkBits >= numSecurityBits,
            "Proof params do not satisfy security requirements.");

        ctx[MM_N_UNIQUE_QUERIES] = nQueries;

        // We start with log_evalDomainSize = logTraceSize and update it here.
        ctx[MM_LOG_EVAL_DOMAIN_SIZE] = logTraceLength + logBlowupFactor;
        ctx[MM_EVAL_DOMAIN_SIZE] = 2**ctx[MM_LOG_EVAL_DOMAIN_SIZE];

        uint256 gen_evalDomain = fpow(GENERATOR_VAL, (K_MODULUS - 1) / ctx[MM_EVAL_DOMAIN_SIZE]);
        ctx[MM_EVAL_DOMAIN_GENERATOR] = gen_evalDomain;
        uint256 genTraceDomain = fpow(gen_evalDomain, ctx[MM_BLOW_UP_FACTOR]);
        ctx[MM_TRACE_GENERATOR] = genTraceDomain;
    }

    function getPublicInputHash(uint256[] memory publicInput) internal pure returns (bytes32);

    function oodsConsistencyCheck(uint256[] memory ctx) internal;

    function getNColumnsInTrace() internal pure returns(uint256);

    function getNColumnsInComposition() internal pure returns(uint256);

    function getMmCoefficients() internal pure returns(uint256);

    function getMmOodsValues() internal pure returns(uint256);

    function getMmOodsCoefficients() internal pure returns(uint256);

    function getNCoefficients() internal pure returns(uint256);

    function getNOodsValues() internal pure returns(uint256);

    function getNOodsCoefficients() internal pure returns(uint256);

    function hashRow(uint256[] memory ctx, uint256 offset, uint256 length)
    internal pure returns (uint256 res) {
        assembly {
            res := keccak256(add(add(ctx, 0x20), offset), length)
        }
        res &= getHashMask();
    }

    /*
      Adjusts the query indices and generates evaluation points for each query index.
      The operations above are independent but we can save gas by combining them as both
      operations require us to iterate the queries array.

      Indices adjustment:
          The query indices adjustment is needed because both the Merkle verification and FRI
          expect queries "full binary tree in array" indices.
          The adjustment is simply adding evalDomainSize to each query.
          Note that evalDomainSize == 2^(#FRI layers) == 2^(Merkle tree hight).

      evalPoints generation:
          for each query index "idx" we compute the corresponding evaluation point:
              g^(bitReverse(idx, log_evalDomainSize).
    */
    function adjustQueryIndicesAndPrepareEvalPoints(uint256[] memory ctx) internal {
        uint256 nUniqueQueries = ctx[MM_N_UNIQUE_QUERIES];
        uint256 friQueue = getPtr(ctx, MM_FRI_QUEUE);
        uint256 friQueueEnd = friQueue + nUniqueQueries * 0x60;
        uint256 evalPointsPtr = getPtr(ctx, MM_OODS_EVAL_POINTS);
        uint256 log_evalDomainSize = ctx[MM_LOG_EVAL_DOMAIN_SIZE];
        uint256 evalDomainSize = ctx[MM_EVAL_DOMAIN_SIZE];
        uint256 evalDomainGenerator = ctx[MM_EVAL_DOMAIN_GENERATOR];

        assembly {
            /*
              Returns the bit reversal of value assuming it has the given number of bits.
              numberOfBits must be <= 64.
            */
            function bitReverse(value, numberOfBits) -> res {
                // Bit reverse value by swapping 1 bit chunks then 2 bit chunks and so forth.
                // Each swap is done by masking out and shifting one of the chunks by twice its size.
                // Finally, we use div to align the result to the right.
                res := value
                // Swap 1 bit chunks.
                res := or(mul(and(res, 0x5555555555555555), 0x4),
                        and(res, 0xaaaaaaaaaaaaaaaa))
                // Swap 2 bit chunks.
                res := or(mul(and(res, 0x6666666666666666), 0x10),
                        and(res, 0x19999999999999998))
                // Swap 4 bit chunks.
                res := or(mul(and(res, 0x7878787878787878), 0x100),
                        and(res, 0x78787878787878780))
                // Swap 8 bit chunks.
                res := or(mul(and(res, 0x7f807f807f807f80), 0x10000),
                        and(res, 0x7f807f807f807f8000))
                // Swap 16 bit chunks.
                res := or(mul(and(res, 0x7fff80007fff8000), 0x100000000),
                        and(res, 0x7fff80007fff80000000))
                // Swap 32 bit chunks.
                res := or(mul(and(res, 0x7fffffff80000000), 0x10000000000000000),
                        and(res, 0x7fffffff8000000000000000))
                // Right align the result.
                res := div(res, exp(2, sub(127, numberOfBits)))
            }

            function expmod(base, exponent, modulus) -> res {
                let p := mload(0x40)
                mstore(p, 0x20)                 // Length of Base.
                mstore(add(p, 0x20), 0x20)      // Length of Exponent.
                mstore(add(p, 0x40), 0x20)      // Length of Modulus.
                mstore(add(p, 0x60), base)      // Base.
                mstore(add(p, 0x80), exponent)  // Exponent.
                mstore(add(p, 0xa0), modulus)   // Modulus.
                // Call modexp precompile.
                if iszero(call(not(0), 0x05, 0, p, 0xc0, p, 0x20)) {
                    revert(0, 0)
                }
                res := mload(p)
            }

            let PRIME := 0x30000003000000010000000000000001

            for {} lt(friQueue, friQueueEnd) {friQueue := add(friQueue, 0x60)} {
                let queryIdx := mload(friQueue)
                // Adjust queryIdx, see comment in function description.
                let adjustedQueryIdx := add(queryIdx, evalDomainSize)
                mstore(friQueue, adjustedQueryIdx)

                // Compute the evaluation point corresponding to the current queryIdx.
                mstore(evalPointsPtr, expmod(evalDomainGenerator,
                                             bitReverse(queryIdx, log_evalDomainSize),
                                             PRIME))
                evalPointsPtr := add(evalPointsPtr, 0x20)
            }
        }
    }

    function readQueryResponsesAndDecommit(
        uint256[] memory ctx, uint256 nColumns, uint256 proofDataPtr, bytes32 merkleRoot)
         internal view {
        require(nColumns <= getNColumnsInTrace() + getNColumnsInComposition(), "Too many columns.");

        uint256 nUniqueQueries = ctx[MM_N_UNIQUE_QUERIES];
        uint256 channelPtr = getPtr(ctx, MM_CHANNEL);
        uint256 friQueue = getPtr(ctx, MM_FRI_QUEUE);
        uint256 friQueueEnd = friQueue + nUniqueQueries * 0x60;
        uint256 merkleQueuePtr = getPtr(ctx, MM_MERKLE_QUEUE);
        uint256 rowSize = 0x20 * nColumns;
        uint256 lhashMask = getHashMask();

        assembly {
            let proofPtr := mload(channelPtr)
            let merklePtr := merkleQueuePtr

            for {} lt(friQueue, friQueueEnd) {friQueue := add(friQueue, 0x60)} {
                let merkleLeaf := and(keccak256(proofPtr, rowSize), lhashMask)
                if eq(rowSize, 0x20) {
                    // If a leaf contains only 1 field element we don't hash it.
                    merkleLeaf := mload(proofPtr)
                }

                // push(queryIdx, hash(row)) to merkleQueue.
                mstore(merklePtr, mload(friQueue))
                mstore(add(merklePtr, 0x20), merkleLeaf)
                merklePtr := add(merklePtr, 0x40)

                // Copy query responses to proofData array.
                // This array will be sent to the OODS contract.
                for {let proofDataChunk_end := add(proofPtr, rowSize)}
                        lt(proofPtr, proofDataChunk_end)
                        {proofPtr := add(proofPtr, 0x20)} {
                    mstore(proofDataPtr, mload(proofPtr))
                    proofDataPtr := add(proofDataPtr, 0x20)
                }
            }

            mstore(channelPtr, proofPtr)
        }

        verify(channelPtr, merkleQueuePtr, merkleRoot, nUniqueQueries);
    }

    /*
      Computes the first FRI layer by reading the query responses and calling
      the OODS contract.

      The OODS contract will build and sum boundary constraints that check that
      the prover provided the proper evaluations for the Out of Domain Sampling.

      I.e. if the prover said that f(z) = c, the first FRI layer will include
      the term (f(x) - c)/(x-z).
    */
    function computeFirstFriLayer(uint256[] memory ctx) internal {
        adjustQueryIndicesAndPrepareEvalPoints(ctx);
        // emit LogGas("Prepare evaluation points", gasleft());
        readQueryResponsesAndDecommit(
            ctx, getNColumnsInTrace(), getPtr(ctx, MM_TRACE_QUERY_RESPONSES),
            bytes32(ctx[MM_TRACE_COMMITMENT]));
        // emit LogGas("Read and decommit trace", gasleft());

        readQueryResponsesAndDecommit(
            ctx, getNColumnsInComposition(), getPtr(ctx, MM_COMPOSITION_QUERY_RESPONSES),
            bytes32(ctx[MM_OODS_COMMITMENT]));

        // emit LogGas("Read and decommit composition", gasleft());

        address oodsAddress = oodsContractAddress;
        uint256 friQueue = getPtr(ctx, MM_FRI_QUEUE);
        uint256 returnDataSize = MAX_N_QUERIES * 0x60;
        assembly {
            // Call the OODS contract.
            if iszero(staticcall(not(0), oodsAddress, ctx,
                                 /*sizeof(ctx)*/ mul(add(mload(ctx), 1), 0x20),
                                 friQueue, returnDataSize)) {
              returndatacopy(0, 0, returndatasize)
              revert(0, returndatasize)
            }
        }
        // emit LogGas("OODS virtual oracle", gasleft());
    }

    /*
      Reads the last FRI layer (i.e. the polynomial's coefficients) from the channel.
      This differs from standard reading of channel field elements in several ways:
      -- The digest is updated by hashing it once with all coefficients simultaneously, rather than
         iteratively one by one.
      -- The coefficients are kept in Montgomery form, as is the case throughout the FRI
         computation.
      -- The coefficients are not actually read and copied elsewhere, but rather only a pointer to
         their location in the channel is stored.
    */
    function readLastFriLayer(uint256[] memory ctx)
        internal pure
    {
        uint256 lmmChannel = MM_CHANNEL;
        uint256 friLastLayerDegBound = ctx[MM_FRI_LAST_LAYER_DEG_BOUND];
        uint256 lastLayerPtr;
        uint256 badInput = 0;

        assembly {
            let primeMinusOne := 0x30000003000000010000000000000000
            let channelPtr := add(add(ctx, 0x20), mul(lmmChannel, 0x20))
            lastLayerPtr := mload(channelPtr)

            // Make sure all the values are valid field elements.
            let length := mul(friLastLayerDegBound, 0x20)
            let lastLayerEnd := add(lastLayerPtr, length)
            for { let coefsPtr := lastLayerPtr } lt(coefsPtr, lastLayerEnd)
                { coefsPtr := add(coefsPtr, 0x20) } {
                badInput := or(badInput, gt(mload(coefsPtr), primeMinusOne))
            }

            // Copy the digest to the proof area
            // (store it before the coefficients - this is done because
            // keccak256 needs all data to be consecutive),
            // then hash and place back in digestPtr.
            let newDigestPtr := sub(lastLayerPtr, 0x20)
            let digestPtr := add(channelPtr, 0x20)
            // Overwriting the proof to minimize copying of data.
            mstore(newDigestPtr, mload(digestPtr))

            // prng.digest := keccak256(digest||lastLayerCoefs).
            mstore(digestPtr, keccak256(newDigestPtr, add(length, 0x20)))
            // prng.counter := 0.
            mstore(add(channelPtr, 0x40), 0)

            // Note: proof pointer is not incremented until this point.
            mstore(channelPtr, lastLayerEnd)
        }

        require(badInput == 0, "Invalid field element.");
        ctx[MM_FRI_LAST_LAYER_PTR] = lastLayerPtr;
    }

    function verifyProof(
        uint256[] memory proofParams, uint256[] memory proof, uint256[] memory publicInput)
        internal {
        // emit LogGas("Transmission", gasleft());
        uint256[] memory ctx = initVerifierParams(publicInput, proofParams);
        uint256 channelPtr = getChannelPtr(ctx);

        initChannel(channelPtr,  getProofPtr(proof), getPublicInputHash(publicInput));
        // emit LogGas("Initializations", gasleft());

        // Read trace commitment.
        ctx[MM_TRACE_COMMITMENT] = uint256(readHash(channelPtr, true));
        VerifierChannel.sendFieldElements(
            channelPtr, getNCoefficients(), getPtr(ctx, getMmCoefficients()));
        // emit LogGas("Generate coefficients", gasleft());

        ctx[MM_OODS_COMMITMENT] = uint256(readHash(channelPtr, true));

        // Send Out of Domain Sampling point.
        VerifierChannel.sendFieldElements(channelPtr, 1, getPtr(ctx, MM_OODS_POINT));

        // Read the answers to the Out of Domain Sampling.
        uint256 lmmOodsValues = getMmOodsValues();
        for (uint256 i = lmmOodsValues; i < lmmOodsValues+getNOodsValues(); i++) {
            ctx[i] = VerifierChannel.readFieldElement(channelPtr, true);
        }
        // emit LogGas("Read OODS commitments", gasleft());
        oodsConsistencyCheck(ctx);
        // emit LogGas("OODS consistency check", gasleft());
        VerifierChannel.sendFieldElements(
            channelPtr, getNOodsCoefficients(), getPtr(ctx, getMmOodsCoefficients()));
        // emit LogGas("Generate OODS coefficients", gasleft());
        ctx[MM_FRI_COMMITMENTS] = uint256(VerifierChannel.readHash(channelPtr, true));

        uint256 nFriSteps = getFriSteps(ctx).length;
        uint256 fri_evalPointPtr = getPtr(ctx, MM_FRI_EVAL_POINTS);
        for (uint256 i = 1; i < nFriSteps - 1; i++) {
            VerifierChannel.sendFieldElements(channelPtr, 1, fri_evalPointPtr + i * 0x20);
            ctx[MM_FRI_COMMITMENTS + i] = uint256(VerifierChannel.readHash(channelPtr, true));
        }

        // Send last random FRI evaluation point.
        VerifierChannel.sendFieldElements(
            channelPtr, 1, getPtr(ctx, MM_FRI_EVAL_POINTS + nFriSteps - 1));

        // Read FRI last layer commitment.
        readLastFriLayer(ctx);

        // Generate queries.
        // emit LogGas("Read FRI commitments", gasleft());
        VerifierChannel.verifyProofOfWork(channelPtr, ctx[MM_PROOF_OF_WORK_BITS]);
        ctx[MM_N_UNIQUE_QUERIES] = VerifierChannel.sendRandomQueries(
            channelPtr, ctx[MM_N_UNIQUE_QUERIES], ctx[MM_EVAL_DOMAIN_SIZE] - 1,
            getPtr(ctx, MM_FRI_QUEUE), 0x60);
        // emit LogGas("Send queries", gasleft());

        computeFirstFriLayer(ctx);

        friVerifyLayers(ctx);
    }
}

// File: VerifierChannel.sol



pragma solidity ^0.5.2;

import "./Prng.sol";

contract VerifierChannel is Prng {

    /*
      We store the state of the channel in uint256[3] as follows:
        [0] proof pointer.
        [1] prng digest.
        [2] prng counter.
    */
    uint256 constant internal CHANNEL_STATE_SIZE = 3;

    event LogValue(bytes32 val);

    event SendRandomnessEvent(uint256 val);

    event ReadFieldElementEvent(uint256 val);

    event ReadHashEvent(bytes32 val);

    function getPrngPtr(uint256 channelPtr)
        internal pure
        returns (uint256)
    {
        return channelPtr + 0x20;
    }

    function initChannel(uint256 channelPtr, uint256 proofPtr, bytes32 publicInputHash)
        internal pure
    {
        assembly {
            // Skip 0x20 bytes length at the beginning of the proof.
            mstore(channelPtr, add(proofPtr, 0x20))
        }

        initPrng(getPrngPtr(channelPtr), publicInputHash);
    }

    function sendFieldElements(uint256 channelPtr, uint256 nElements, uint256 targetPtr)
        internal pure
    {
        require(nElements < 0x1000000, "Overflow protection failed.");
        assembly {
            let PRIME := 0x30000003000000010000000000000001
            let PRIME_MON_R_INV := 0x9000001200000096000000600000001
            let PRIME_MASK := 0x3fffffffffffffffffffffffffffffff
            let digestPtr := add(channelPtr, 0x20)
            let counterPtr := add(channelPtr, 0x40)

            let endPtr := add(targetPtr, mul(nElements, 0x20))
            for { } lt(targetPtr, endPtr) { targetPtr := add(targetPtr, 0x20) } {
                // *targetPtr = getRandomFieldElement(getPrngPtr(channelPtr));

                let fieldElement := PRIME
                // while (fieldElement >= PRIME).
                for { } iszero(lt(fieldElement, PRIME)) { } {
                    // keccak256(abi.encodePacked(digest, counter));
                    fieldElement := and(keccak256(digestPtr, 0x40), PRIME_MASK)
                    // *counterPtr += 1;
                    mstore(counterPtr, add(mload(counterPtr), 1))
                }
                // *targetPtr = fromMontgomery(fieldElement);
                mstore(targetPtr, mulmod(fieldElement, PRIME_MON_R_INV, PRIME))
                // emit ReadFieldElementEvent(fieldElement);
                // log1(targetPtr, 0x20, 0x4bfcc54f35095697be2d635fb0706801e13637312eff0cedcdfc254b3b8c385e);
            }
        }
    }

    /*
      Sends random queries and returns an array of queries sorted in ascending order.
      Generates count queries in the range [0, mask] and returns the number of unique queries.
      Note that mask is of the form 2^k-1 (for some k).

      Note that queriesOutPtr may be (and is) inteleaved with other arrays. The stride parameter
      is passed to indicate the distance between every two entries to the queries array, i.e.
      stride = 0x20*(number of interleaved arrays).
    */
    function sendRandomQueries(
        uint256 channelPtr, uint256 count, uint256 mask, uint256 queriesOutPtr, uint256 stride)
        internal pure returns (uint256)
    {
        uint256 val;
        uint256 shift = 0;
        uint256 endPtr = queriesOutPtr;
        for (uint256 i = 0; i < count; i++) {
            if (shift == 0) {
                val = uint256(getRandomBytes(getPrngPtr(channelPtr)));
                shift = 0x100;
            }
            shift -= 0x40;
            uint256 queryIdx = (val >> shift) & mask;
            // emit sendRandomnessEvent(queryIdx);

            uint256 ptr = endPtr;
            uint256 curr;
            // Insert new queryIdx in the correct place like insertion sort.

            while (ptr > queriesOutPtr) {
                assembly {
                    curr := mload(sub(ptr, stride))
                }

                if (queryIdx >= curr) {
                    break;
                }

                assembly {
                    mstore(ptr, curr)
                }
                ptr -= stride;
            }

            if (queryIdx != curr) {
                assembly {
                    mstore(ptr, queryIdx)
                }
                endPtr += stride;
            } else {
                // Revert right shuffling.
                while (ptr < endPtr) {
                    assembly {
                        mstore(ptr, mload(add(ptr, stride)))
                        ptr := add(ptr, stride)
                    }
                }
            }
        }

        return (endPtr - queriesOutPtr) / stride;
    }

    function readBytes(uint256 channelPtr, bool mix)
        internal pure
        returns (bytes32)
    {
        uint256 proofPtr;
        bytes32 val;

        assembly {
            proofPtr := mload(channelPtr)
            val := mload(proofPtr)
            mstore(channelPtr, add(proofPtr, 0x20))
        }
        if (mix) {
            // inline: Prng.mixSeedWithBytes(getPrngPtr(channelPtr), abi.encodePacked(val));
            assembly {
                let digestPtr := add(channelPtr, 0x20)
                let counterPtr := add(digestPtr, 0x20)
                mstore(counterPtr, val)
                // prng.digest := keccak256(digest||val), nonce was written earlier.
                mstore(digestPtr, keccak256(digestPtr, 0x40))
                // prng.counter := 0.
                mstore(counterPtr, 0)
            }
        }

        return val;
    }

    function readHash(uint256 channelPtr, bool mix)
        internal pure
        returns (bytes32)
    {
        bytes32 val = readBytes(channelPtr, mix);
        // emit ReadHashEvent(val);

        return val;
    }

    function readFieldElement(uint256 channelPtr, bool mix)
        internal pure returns (uint256) {
        uint256 val = fromMontgomery(uint256(readBytes(channelPtr, mix)));
        // emit ReadFieldElementEvent(val);

        return val;
    }

    function verifyProofOfWork(uint256 channelPtr, uint256 proofOfWorkBits) internal pure {
        if (proofOfWorkBits == 0) {
            return;
        }

        uint256 proofOfWorkDigest;
        assembly {
            // [0:29] := 0123456789abcded || digest || workBits.
            mstore(0, 0x0123456789abcded000000000000000000000000000000000000000000000000)
            let digest := mload(add(channelPtr, 0x20))
            mstore(0x8, digest)
            mstore8(0x28, proofOfWorkBits)
            mstore(0, keccak256(0, 0x29))

            let proofPtr := mload(channelPtr)
            mstore(0x20, mload(proofPtr))
            // proofOfWorkDigest:= keccak256(keccak256(0123456789abcded || digest || workBits) || nonce).
            proofOfWorkDigest := keccak256(0, 0x28)

            mstore(0, digest)
            // prng.digest := keccak256(digest||nonce), nonce was written earlier.
            mstore(add(channelPtr, 0x20), keccak256(0, 0x28))
            // prng.counter := 0.
            mstore(add(channelPtr, 0x40), 0)

            mstore(channelPtr, add(proofPtr, 0x8))
        }

        uint256 proofOfWorkThreshold = uint256(1) << (256 - proofOfWorkBits);
        require(proofOfWorkDigest < proofOfWorkThreshold, "Proof of work check failed.");
    }
}