#include <iostream>
#include <fstream>

#include "base.hpp"

extern const scalar_t bn_n;
extern const twistpoint_fp2_t bn_twistgen;

/* These lines need to be here so these static variables are defined,
 * but in C++ putting code here doesn't actually execute
 * (or at least, with g++, whenever it would execute is not at a useful time)
 * so we have an init() function to actually put the correct values in them. */
size_t PrsonaBase::MAX_ALLOWED_VOTE = 2;
Twistpoint PrsonaBase::EL_GAMAL_GENERATOR = Twistpoint();

Scalar PrsonaBase::SCALAR_N = Scalar();
Scalar PrsonaBase::DEFAULT_TALLY = Scalar();
Scalar PrsonaBase::DEFAULT_VOTE = Scalar();

bool PrsonaBase::SERVER_IS_MALICIOUS = false;
bool PrsonaBase::CLIENT_IS_MALICIOUS = false;
size_t PrsonaBase::LAMBDA = 0;

// Quick and dirty function to calculate ceil(log base 2) with mpz_class
mpz_class log2(mpz_class x)
{
    mpz_class retval = 0;
    while (x > 0)
    {
        retval++;
        x = x >> 1;
    }

    return retval;
}

mpz_class bit(mpz_class x)
{
    return x > 0 ? 1 : 0;
}

/********************
 * PUBLIC FUNCTIONS *
 ********************/

/*
 * SETUP FUNCTIONS
 */

// Must be called once before any usage of this class
void PrsonaBase::init()
{
    EL_GAMAL_GENERATOR = Twistpoint(bn_twistgen);
    SCALAR_N = Scalar(bn_n);
    DEFAULT_TALLY = Scalar(1);
    DEFAULT_VOTE = Scalar(1);
}

// Call this (once) if using malicious-security servers
void PrsonaBase::set_server_malicious()
{
    SERVER_IS_MALICIOUS = true;
}

// Call this (once) if using malicious-security clients
void PrsonaBase::set_client_malicious()
{
    CLIENT_IS_MALICIOUS = true;
}

// Call this (once) if using proof batching
void PrsonaBase::set_lambda(size_t lambda)
{
    LAMBDA = lambda;
}

/*
 * CONST GETTERS
 */

size_t PrsonaBase::get_max_allowed_vote()
{
    return MAX_ALLOWED_VOTE;
}

Twistpoint PrsonaBase::get_blinding_generator() const
{
    return elGamalBlindGenerator;
}

Twistpoint PrsonaBase::get_blinding_generator(
    std::vector<Proof>& pi) const
{
    pi = elGamalBlindGeneratorProof;

    return elGamalBlindGenerator;
}

/***********************
 * PROTECTED FUNCTIONS *
 ***********************/

/*
 * PRIVATE ELEMENT SETTER
 */

bool PrsonaBase::set_EG_blind_generator(
    const std::vector<Proof>& pi,
    const Twistpoint& currGenerator,
    size_t numServers)
{
    if (!verify_generator_proof(pi, currGenerator, numServers))
    {
        std::cerr << "Could not set EG blind generator correctly." << std::endl;
        return false;
    }

    elGamalBlindGeneratorProof = pi;
    elGamalBlindGenerator = currGenerator;
    return true;
}

/*
 * BINARY SEARCH
 */

/* Completely normal binary search
 * There might be a standard function for this in <algorithms>?
 * But it returns an iterator, not a size_t, so less useful. */
size_t PrsonaBase::binary_search(
    const std::vector<Twistpoint> list,
    const Twistpoint& index) const
{
    size_t lo, hi;
    lo = 0;
    hi = list.size() - 1;

    while (lo < hi)
    {
        size_t mid = (lo + hi) / 2;
        if (list[mid] < index)
            lo = mid + 1;
        else if (index == list[mid])
            return mid;
        else if (mid == lo)
            return lo;
        else hi = mid - 1;
    }

    return lo;
}

/*
 * SCHNORR PROOFS
 */

Proof PrsonaBase::schnorr_generation(
    const Twistpoint& generator,
    const Twistpoint& commitment,
    const Scalar& log) const
{
    Proof retval;

    std::stringstream oracleInput;
    
    Scalar u;
    u.set_random();
    
    Twistpoint U = generator * u;
    oracleInput << generator << commitment << U;

    Scalar x = oracle(oracleInput.str());
    Scalar z = log * x + u;

    retval.challengeParts.push_back(x);
    retval.responseParts.push_back(z);

    return retval;
}

bool PrsonaBase::schnorr_verification(
    const Twistpoint& generator,
    const Twistpoint& commitment,
    const Scalar& x,
    const Scalar& z) const
{
    Twistpoint U = generator * z - commitment * x;

    std::stringstream oracleInput;
    oracleInput << generator << commitment << U;
    
    return x == oracle(oracleInput.str());
}

/*
 * OWNERSHIP PROOFS
 */

// Prove ownership of the short term public key
Proof PrsonaBase::generate_ownership_proof(
    const Twistpoint& generator,
    const Twistpoint& commitment,
    const Scalar& log) const
{
    if (!CLIENT_IS_MALICIOUS)
    {
        Proof retval;
        retval.hbc = "PROOF";

        return retval;
    }

    return schnorr_generation(generator, commitment, log);
}

bool PrsonaBase::verify_ownership_proof(
    const Proof& pi,
    const Twistpoint& generator,
    const Twistpoint& commitment) const
{
    if (!CLIENT_IS_MALICIOUS)
        return pi.hbc == "PROOF";

    Scalar c = pi.challengeParts[0];
    Scalar z = pi.responseParts[0];

    return schnorr_verification(generator, commitment, c, z);
}

/*
 * ITERATED SCHNORR PROOFS
 */

Proof PrsonaBase::add_to_generator_proof(
    const Twistpoint& currGenerator, 
    const Scalar& seed) const
{
    Proof retval;
    if (!SERVER_IS_MALICIOUS)
    {
        retval.hbc = "PROOF";
        return retval;
    }

    Twistpoint nextGenerator = currGenerator * seed;
    retval = schnorr_generation(currGenerator, nextGenerator, seed);

    retval.curvepointUniversals.push_back(currGenerator);
    return retval;
}

bool PrsonaBase::verify_generator_proof(
    const std::vector<Proof>& pi,
    const Twistpoint& currGenerator,
    size_t numServers) const
{
    if (pi.size() != numServers || numServers == 0)
        return false;

    bool retval = true;

    if (!SERVER_IS_MALICIOUS)
    {
        for (size_t i = 0; i < pi.size(); i++)
            retval = retval && pi[i].hbc == "PROOF";

        return retval;
    }

    if (pi[0].curvepointUniversals[0] != EL_GAMAL_GENERATOR)
        return false;

    for (size_t i = 0; i < pi.size(); i++)
    {
        Twistpoint generator = pi[i].curvepointUniversals[0];
        Twistpoint commitment = (i == pi.size() - 1 ? currGenerator : pi[i + 1].curvepointUniversals[0]);
        Scalar c = pi[i].challengeParts[0];
        Scalar z = pi[i].responseParts[0];

        retval = retval && schnorr_verification(generator, commitment, c, z);
        if (!retval)
            std::cerr << "Error in index " << i+1 << " of " << pi.size() << std::endl;
    }
    
    return retval;
}

/*
 * REPUTATION PROOFS
 */

// A pretty straightforward range proof (generation)
std::vector<Proof> PrsonaBase::generate_reputation_proof(
    const Proof& ownershipProof,
    const EGCiphertext& commitment,
    const Scalar& currentScore,
    const Scalar& threshold,
    const Scalar& inverseKey,
    size_t numClients) const
{
    std::vector<Proof> retval;

    // Base case
    if (!CLIENT_IS_MALICIOUS)
    {
        retval.push_back(Proof("PROOF"));

        return retval;
    }

    // Don't even try if the user asks to make an illegitimate proof
    if (threshold.toInt() > (numClients * MAX_ALLOWED_VOTE))
        return retval;

    // We really have two consecutive proofs in a junction.
    // The first is to prove that we are the stpk we claim we are
    retval.push_back(ownershipProof);

    // The value we're actually using in our proof
    mpz_class proofVal = (currentScore - threshold).toInt();
    // Top of the range in our proof determined by what scores are even possible
    mpz_class proofBits = log2(numClients * MAX_ALLOWED_VOTE - threshold.toInt());
    
    // Don't risk a situation that would divulge our private key
    if (proofBits <= 1)
        proofBits = 2;

    // This seems weird, but remember our base is A_t^r, not g^t
    std::vector<Scalar> masksPerBit;
    masksPerBit.push_back(inverseKey);
    for (size_t i = 1; i < proofBits; i++)
    {
        Scalar currMask;
        currMask.set_random();

        masksPerBit.push_back(currMask);
        masksPerBit[0] = masksPerBit[0] - (currMask * Scalar(1 << i));
    }

    // Taken from Fig. 1 in https://eprint.iacr.org/2014/764.pdf
    for (size_t i = 0; i < proofBits; i++)
    {
        Proof currProof;
        Twistpoint g, h, C, C_a, C_b;
        g = commitment.mask;
        h = elGamalBlindGenerator;
    
        mpz_class currBit = bit(proofVal & (1 << i));
        Scalar a, s, t, m, r;
        a.set_random();
        s.set_random();
        t.set_random();
        m = Scalar(currBit);
        r = masksPerBit[i];
        
        C = g * r + h * m;
        currProof.curvepointUniversals.push_back(C);

        C_a = g * s + h * a;
        C_b = g * t + h * a * m;

        std::stringstream oracleInput;
        oracleInput << g << h << C << C_a << C_b;

        Scalar x = oracle(oracleInput.str());
        currProof.challengeParts.push_back(x);

        Scalar f, z_a, z_b;
        f = m * x + a;
        z_a = r * x + s;
        z_b = r * (x - f) + t;

        currProof.responseParts.push_back(f);
        currProof.responseParts.push_back(z_a);
        currProof.responseParts.push_back(z_b);

        retval.push_back(currProof);
    }

    return retval;
}

// A pretty straightforward range proof (verification)
bool PrsonaBase::verify_reputation_proof(
    const std::vector<Proof>& pi,
    const Twistpoint& generator,
    const Twistpoint& owner,
    const EGCiphertext& commitment,
    const Scalar& threshold) const
{
    // Reject outright if there's no proof to check
    if (pi.empty())
    {
        std::cerr << "Proof was empty, aborting." << std::endl;
        return false;
    }

    // If the range is so big that it wraps around mod n,
    // there's a chance the user actually made a proof for a very low reputation
    if (pi.size() > 256)
    {
        std::cerr << "Proof was too big, prover could have cheated." << std::endl;
        return false;
    }

    if (!CLIENT_IS_MALICIOUS)
        return pi[0].hbc == "PROOF";

    Scalar ownerChallenge, ownerResponse;
    ownerChallenge = pi[0].challengeParts[0];
    ownerResponse = pi[0].responseParts[0];

    // User should be able to prove they are who they say they are
    if (!schnorr_verification(generator, owner, ownerChallenge, ownerResponse))
    {
        std::cerr << "Schnorr proof failed, aborting." << std::endl;
        return false;
    }

    // X is the thing we're going to be checking in on throughout
    // to try to get our score commitment back in the end.
    Twistpoint X;
    for (size_t i = 1; i < pi.size(); i++)
    {
        Twistpoint C, g, h;
        C = pi[i].curvepointUniversals[0];
        g = commitment.mask;
        h = elGamalBlindGenerator;

        X = X + C * Scalar(1 << (i - 1));

        Scalar x, f, z_a, z_b;
        x = pi[i].challengeParts[0];
        f = pi[i].responseParts[0];
        z_a = pi[i].responseParts[1];
        z_b = pi[i].responseParts[2];

        // Taken from Fig. 1 in https://eprint.iacr.org/2014/764.pdf
        Twistpoint C_a, C_b;
        C_a = g * z_a + h * f - C * x;
        C_b = g * z_b - C * (x - f);

        std::stringstream oracleInput;
        oracleInput << g << h << C << C_a << C_b;

        if (oracle(oracleInput.str()) != x)
        {
            std::cerr << "0 or 1 proof failed at index " << i << " of " << pi.size() - 1 << ", aborting." << std::endl;
            return false;
        }
    }

    Twistpoint scoreCommitment = commitment.encryptedMessage + elGamalBlindGenerator * -threshold;
    
    return X == scoreCommitment;
}

/*
 * VALID VOTE PROOFS
 */

std::vector<Proof> PrsonaBase::generate_vote_proof(
    const Proof& ownershipProof,
    const TwistBipoint& g,
    const TwistBipoint& h,
    const std::vector<bool>& replaces,
    const std::vector<TwistBipoint>& oldEncryptedVotes,
    const std::vector<TwistBipoint>& newEncryptedVotes,
    const std::vector<Scalar>& seeds,
    const std::vector<Scalar>& votes) const
{
    std::vector<Proof> retval;

    // Base case
    if (!CLIENT_IS_MALICIOUS)
    {
        retval.push_back(Proof("PROOF"));
        
        return retval;
    }

    // The first need is to prove that we are the stpk we claim we are
    retval.push_back(ownershipProof);

    // Then, we iterate over all votes for the proofs that they are correct
    for (size_t i = 0; i < replaces.size(); i++)
    {
        std::stringstream oracleInput;
        oracleInput << g << h << oldEncryptedVotes[i] << newEncryptedVotes[i];

        Scalar m = votes[i];
        Scalar r = seeds[i];
        
        /* This proof structure is documented in my notes.
         * It's inspired by the proof in Fig. 1 at
         * https://eprint.iacr.org/2014/764.pdf, but adapted so that you prove
         * m(m-1)(m-2) = 0 instead of m(m-1) = 0.
         *
         * The rerandomization part is just a slight variation on an
         * ordinary Schnorr proof, so that part's less scary. */
        if (replaces[i])     // CASE: Make new vote
        {
            Proof currProof;

            Scalar x_r, z_r, a, s, t_1, t_2;
            x_r.set_random();
            z_r.set_random();
            a.set_random();
            s.set_random();
            t_1.set_random();
            t_2.set_random();

            TwistBipoint U = h * z_r +
                oldEncryptedVotes[i] * x_r -
                newEncryptedVotes[i] * x_r;

            TwistBipoint C_a = g * a + h * s;

            Scalar power = ((a + a) * m * m - (a + a + a) * m);
            TwistBipoint C_b = g * power + h * t_1;
            currProof.curveBipointUniversals.push_back(C_b);

            TwistBipoint C_c = g * (a * a * m) + h * t_2;

            oracleInput << U << C_a << C_b << C_c;

            Scalar x = oracle(oracleInput.str());
            Scalar x_n = x - x_r;
            currProof.challengeParts.push_back(x_r);
            currProof.challengeParts.push_back(x_n);

            Scalar f = m * x_n + a;
            Scalar z_na = r * x_n + s;
            Scalar z_nb = r * (f - x_n) * (x_n + x_n - f) + t_1 * x_n + t_2;

            currProof.responseParts.push_back(z_r);
            currProof.responseParts.push_back(f);
            currProof.responseParts.push_back(z_na);
            currProof.responseParts.push_back(z_nb);

            retval.push_back(currProof);
        }
        else                // CASE: Rerandomize existing vote
        {
            Proof currProof;

            Scalar u, commitmentLambda_1, commitmentLambda_2, x_n, z_na, z_nb, f;
            u.set_random();
            commitmentLambda_1.set_random();
            commitmentLambda_2.set_random();
            x_n.set_random();
            z_na.set_random();
            z_nb.set_random();
            f.set_random();

            TwistBipoint U = h * u;

            TwistBipoint C_a = g * f +
                h * z_na -
                newEncryptedVotes[i] * x_n;

            TwistBipoint C_b = g * commitmentLambda_1 + h * commitmentLambda_2;
            currProof.curveBipointUniversals.push_back(C_b);

            TwistBipoint C_c = h * z_nb -
                newEncryptedVotes[i] * ((f - x_n) * (x_n + x_n - f)) -
                C_b * x_n;

            oracleInput << U << C_a << C_b << C_c;

            Scalar x = oracle(oracleInput.str());
            Scalar x_r = x - x_n;
            currProof.challengeParts.push_back(x_r);
            currProof.challengeParts.push_back(x_n);

            Scalar z_r = r * x_r + u;
            currProof.responseParts.push_back(z_r);
            currProof.responseParts.push_back(f);
            currProof.responseParts.push_back(z_na);
            currProof.responseParts.push_back(z_nb);

            retval.push_back(currProof);
        }
    }

    return retval;
}

bool PrsonaBase::verify_vote_proof(
    const TwistBipoint& g,
    const TwistBipoint& h,
    const std::vector<Proof>& pi,
    const std::vector<TwistBipoint>& oldEncryptedVotes,
    const std::vector<TwistBipoint>& newEncryptedVotes,
    const Twistpoint& freshGenerator,
    const Twistpoint& owner) const
{
    // Reject outright if there's no proof to check
    if (pi.empty())
    {
        std::cerr << "Proof was empty, aborting." << std::endl;
        return false;
    }

    // Base case
    if (!CLIENT_IS_MALICIOUS)
        return pi[0].hbc == "PROOF";

    // User should be able to prove they are who they say they are
    if (!verify_ownership_proof(pi[0], freshGenerator, owner))
    {
        std::cerr << "Schnorr proof failed, aborting." << std::endl;
        return false;
    }

    /* This proof structure is documented in my notes.
     * It's inspired by the proof in Fig. 1 at
     * https://eprint.iacr.org/2014/764.pdf, but adapted so that you prove
     * m(m-1)(m-2) = 0 instead of m(m-1) = 0.
     *
     * The rerandomization part is just a slight variation on an
     * ordinary Schnorr proof, so that part's less scary. */
    for (size_t i = 1; i < pi.size(); i++)
    {
        size_t voteIndex = i - 1;
        TwistBipoint C_b;
        C_b = pi[i].curveBipointUniversals[0];

        Scalar x_r, x_n, z_r, f, z_na, z_nb;
        x_r = pi[i].challengeParts[0];
        x_n = pi[i].challengeParts[1];

        z_r  = pi[i].responseParts[0];
        f  = pi[i].responseParts[1];
        z_na = pi[i].responseParts[2];
        z_nb = pi[i].responseParts[3];

        TwistBipoint U, C_a, C_c;
        U = h * z_r +
            oldEncryptedVotes[voteIndex] * x_r -
            newEncryptedVotes[voteIndex] * x_r;
        C_a = g * f + h * z_na - newEncryptedVotes[voteIndex] * x_n;

        C_c = h * z_nb -
            newEncryptedVotes[voteIndex] * ((f - x_n) * (x_n + x_n - f)) -
            C_b * x_n;

        std::stringstream oracleInput;
        oracleInput << g << h << oldEncryptedVotes[voteIndex] << newEncryptedVotes[voteIndex] << U << C_a << C_b << C_c;

        if (oracle(oracleInput.str()) != x_r + x_n)
            return false;
    }

    return true;
}

/*
 * NEW USER PROOFS
 */

std::vector<Proof> PrsonaBase::generate_proof_of_added_user(
    const Scalar& twistBipointSeed,
    const Scalar& EGCiphertextSeed,
    const std::vector<Scalar>& curveBipointSelfSeeds,
    const std::vector<Scalar>& curveBipointOtherSeeds) const
{
    std::vector<Proof> retval;

    if (!SERVER_IS_MALICIOUS)
    {
        retval.push_back(Proof("PROOF"));
        return retval;
    }

    Proof currProof;
    currProof.responseParts.push_back(twistBipointSeed);
    retval.push_back(currProof);

    currProof.responseParts.clear();
    currProof.responseParts.push_back(EGCiphertextSeed);
    retval.push_back(currProof);

    currProof.responseParts.clear();
    for (size_t i = 0; i < curveBipointSelfSeeds.size(); i++)
        currProof.responseParts.push_back(curveBipointSelfSeeds[i]);
    retval.push_back(currProof);

    currProof.responseParts.clear();
    for (size_t i = 0; i < curveBipointOtherSeeds.size(); i++)
        currProof.responseParts.push_back(curveBipointOtherSeeds[i]);
    retval.push_back(currProof);

    return retval;
}

bool PrsonaBase::verify_proof_of_added_user(
    const std::vector<Proof>& pi,
    const Twistpoint& currentFreshGenerator,
    const Twistpoint& shortTermPublicKey,
    const TwistBipoint& curveG,
    const TwistBipoint& curveH,
    const CurveBipoint& twistG,
    const CurveBipoint& twistH,
    size_t selfIndex,
    const EGCiphertext& userEncryptedScore,
    const CurveBipoint& serverEncryptedScore,
    const std::vector<std::vector<TwistBipoint>> encryptedVoteMatrix) const
{
    if (pi.empty())
    {
        std::cerr << "Proof empty." << std::endl;
        return false;
    }

    if (!SERVER_IS_MALICIOUS)
        return true;

    Scalar currSeed = pi[0].responseParts[0];
    if (serverEncryptedScore !=
        twistG * DEFAULT_TALLY + twistH * currSeed)
    {
        std::cerr << "Issue in server encrypted score." << std::endl;
        return false;
    }

    currSeed = pi[1].responseParts[0];
    if (userEncryptedScore.mask != shortTermPublicKey * currSeed)
    {
        std::cerr << "Issue in user encrypted score: mask." << std::endl;
        return false;
    }
    if (userEncryptedScore.encryptedMessage !=
        currentFreshGenerator * currSeed + elGamalBlindGenerator * DEFAULT_TALLY)
    {
        std::cerr << "Issue in user encrypted score: value." << std::endl;
        return false;
    }
    
    for (size_t i = 0; i < pi[2].responseParts.size(); i++)
    {
        TwistBipoint currVote = encryptedVoteMatrix[selfIndex][i];
        currSeed = pi[2].responseParts[i];

        if (i == selfIndex)
        {
            if (currVote !=
                curveG * Scalar(MAX_ALLOWED_VOTE) + curveH * currSeed)
            {
                std::cerr << "Issue in self vote." << std::endl;
                return false;
            }
        }
        else
        {
            if (currVote !=
                curveG * DEFAULT_VOTE + curveH * currSeed)
            {
                std::cerr << "Issue in vote by verifier for user " << i + 1 << " of " << pi[2].responseParts.size() << "." << std::endl;
                return false;
            }
        }
    }

    for (size_t i = 0; i < pi[3].responseParts.size(); i++)
    {
        TwistBipoint currVote = encryptedVoteMatrix[i][selfIndex];
        currSeed = pi[3].responseParts[i];

        if (i != selfIndex)
        {
            if (currVote !=
                curveG * DEFAULT_VOTE + curveH * currSeed)
            {
                std::cerr << "Issue in vote for verifier by user " << i + 1 << " of " << pi[3].responseParts.size() << "." << std::endl;
                return false;
            }
        }
    }

    return true;
}

/*
 * EPOCH PROOFS
 */

std::vector<Proof> PrsonaBase::generate_valid_permutation_proof(
    const std::vector<std::vector<Scalar>>& permutations,
    const std::vector<std::vector<Scalar>>& seeds,
    const std::vector<std::vector<Twistpoint>>& commits) const
{
    std::vector<Proof> retval;

    if (!SERVER_IS_MALICIOUS)
    {
        retval.push_back(Proof("PROOF"));
        return retval;
    }

    Twistpoint g, h;
    g = EL_GAMAL_GENERATOR;
    h = elGamalBlindGenerator;

    std::stringstream oracleInput;
    oracleInput << g << h;

    retval.push_back(Proof());
    std::vector<std::vector<Scalar>> a, s, t;

    for (size_t i = 0; i < commits.size(); i++)
    {
        std::vector<Scalar> currA, currS, currT;
        for (size_t j = 0; j < commits[i].size(); j++)
        {
            oracleInput << commits[i][j];

            currA.push_back(Scalar());
            currS.push_back(Scalar());
            currT.push_back(Scalar());

            retval.push_back(Proof());
        }

        a.push_back(currA);
        s.push_back(currS);
        t.push_back(currT);
    }

    // Taken from Fig. 1 in https://eprint.iacr.org/2014/764.pdf
    for (size_t i = 0; i < permutations.size(); i++)
    {
        for (size_t j = 0; j < permutations[i].size(); j++)
        {
            Twistpoint C, C_a, C_b;
        
            Scalar p, r;
            a[i][j].set_random();
            s[i][j].set_random();
            t[i][j].set_random();
            p = permutations[i][j];
            r = seeds[i][j];
            
            C = commits[i][j];

            C_a = g * a[i][j] + h * s[i][j];
            C_b = g * a[i][j] * p + h * t[i][j];

            oracleInput << C << C_a << C_b;
        }
    }

    Scalar x = oracle(oracleInput.str());
    retval[0].challengeParts.push_back(x);

    for (size_t i = 0; i < permutations.size(); i++)
    {
        for (size_t j = 0; j < permutations[i].size(); j++)
        {
            size_t piIndex = i * permutations.size() + j + 1;

            Scalar f, z_a, z_b, p, r;
            p = permutations[i][j];
            r = seeds[i][j];

            f = p * x + a[i][j];
            z_a = r * x + s[i][j];
            z_b = r * (x - f) + t[i][j];

            retval[piIndex].responseParts.push_back(f);
            retval[piIndex].responseParts.push_back(z_a);
            retval[piIndex].responseParts.push_back(z_b);
        }
    }

    return retval;
}

bool PrsonaBase::verify_valid_permutation_proof(
    const std::vector<Proof>& pi,
    const std::vector<std::vector<Twistpoint>>& commits) const
{
   // Reject outright if there's no proof to check
    if (pi.empty())
    {
        std::cerr << "Proof was empty, aborting." << std::endl;
        return false;
    }

    if (!SERVER_IS_MALICIOUS)
        return true;

    Twistpoint g, h;
    g = EL_GAMAL_GENERATOR;
    h = elGamalBlindGenerator;

    std::stringstream oracleInput;
    oracleInput << g << h;

    for (size_t i = 0; i < commits.size(); i++)
        for (size_t j = 0; j < commits[i].size(); j++)
            oracleInput << commits[i][j];

    Scalar x = pi[0].challengeParts[0];

    for (size_t i = 0; i < commits.size(); i++)
    {
        for (size_t j = 0; j < commits[i].size(); j++)
        {
            size_t piIndex = i * commits.size() + j + 1;

            Twistpoint C, C_a, C_b;

            C = commits[i][j];

            Scalar f, z_a, z_b;
            f = pi[piIndex].responseParts[0];
            z_a = pi[piIndex].responseParts[1];
            z_b = pi[piIndex].responseParts[2];

            // Taken from Fig. 1 in https://eprint.iacr.org/2014/764.pdf
            C_a = g * f + h * z_a - C * x;
            C_b = h * z_b - C * (x - f);

            oracleInput << C << C_a << C_b;
        }
    }

    if (oracle(oracleInput.str()) != x)
    {
        std::cerr << "0 or 1 proof failed, aborting." << std::endl;
        return false;
    }

    for (size_t i = 0; i < commits.size(); i++)
    {
        Twistpoint sum = commits[i][0];

        for (size_t j = 1; j < commits[i].size(); j++)
            sum = sum + commits[i][j];

        if (sum != g)
        {
            std::cerr << "Commits did not sum to g, aborting." << std::endl;
            return false;
        }
    }

    return true;
}

template <typename T>
std::vector<Proof> PrsonaBase::generate_proof_of_reordering(
    const std::vector<std::vector<Scalar>>& permutations,
    const std::vector<std::vector<Scalar>>& permutationSeeds,
    const std::vector<std::vector<Scalar>>& productSeeds,
    const std::vector<T>& oldValues,
    const std::vector<std::vector<Twistpoint>>& permutationCommits,
    const std::vector<std::vector<T>>& productCommits,
    const T& otherG,
    const T& otherH) const
{
    if (LAMBDA > 0)
        return generate_batched_proof_of_reordering<T>(permutations, permutationSeeds, productSeeds, oldValues, permutationCommits, productCommits, otherG, otherH);
    else
        return generate_unbatched_proof_of_reordering<T>(permutations, permutationSeeds, productSeeds, oldValues, permutationCommits, productCommits, otherG, otherH);
}

template <typename T>
bool PrsonaBase::verify_proof_of_reordering(
    const std::vector<Proof>& pi,
    const std::vector<T>& oldValues,
    const std::vector<std::vector<Twistpoint>>& permutationCommits,
    const std::vector<std::vector<T>>& productCommits,
    const T& otherG,
    const T& otherH) const
{
    if (LAMBDA > 0)
        return verify_batched_proof_of_reordering<T>(pi, oldValues, permutationCommits, productCommits, otherG, otherH);
    else
        return verify_unbatched_proof_of_reordering<T>(pi, oldValues, permutationCommits, productCommits, otherG, otherH);
}

template <typename T>
std::vector<Proof> PrsonaBase::generate_unbatched_proof_of_reordering(
    const std::vector<std::vector<Scalar>>& permutations,
    const std::vector<std::vector<Scalar>>& permutationSeeds,
    const std::vector<std::vector<Scalar>>& productSeeds,
    const std::vector<T>& oldValues,
    const std::vector<std::vector<Twistpoint>>& permutationCommits,
    const std::vector<std::vector<T>>& productCommits,
    const T& otherG,
    const T& otherH) const
{
    std::vector<Proof> retval;

    if (!SERVER_IS_MALICIOUS)
    {
        retval.push_back(Proof("PROOF"));
        return retval;
    }

    Proof first;
    retval.push_back(first);

    Twistpoint g = EL_GAMAL_GENERATOR;
    Twistpoint h = elGamalBlindGenerator;

    std::stringstream oracleInput;
    oracleInput << g << h << otherG << otherH;

    for (size_t i = 0; i < oldValues.size(); i++)
        oracleInput << oldValues[i];

    for (size_t i = 0; i < permutationCommits.size(); i++)
        for (size_t j = 0; j < permutationCommits[i].size(); j++)
            oracleInput << permutationCommits[i][j];

    for (size_t i = 0; i < productCommits.size(); i++)
        for (size_t j = 0; j < productCommits[i].size(); j++)
            oracleInput << productCommits[i][j];

    std::vector<std::vector<Scalar>> a;
    std::vector<std::vector<Scalar>> t1;
    std::vector<std::vector<Scalar>> t2;

    for (size_t i = 0; i < permutationCommits.size(); i++)
    {
        std::vector<Scalar> curraRow;
        std::vector<Scalar> currt1Row;
        std::vector<Scalar> currt2Row;

        for (size_t j = 0; j < permutationCommits[i].size(); j++)
        {
            Proof currProof;

            Scalar curra;
            Scalar currt1;
            Scalar currt2;

            Twistpoint U1;
            T U2;

            curra.set_random();
            currt1.set_random();
            currt2.set_random();

            U1 = g * curra + h * currt1;
            U2 = oldValues[j] * curra + otherH * currt2;

            oracleInput << U1 << U2;

            curraRow.push_back(curra);
            currt1Row.push_back(currt1);
            currt2Row.push_back(currt2);

            retval.push_back(currProof);
        }

        a.push_back(curraRow);
        t1.push_back(currt1Row);
        t2.push_back(currt2Row);
    }

    Scalar x = oracle(oracleInput.str());
    retval[0].challengeParts.push_back(x);

    for (size_t i = 0; i < permutationCommits.size(); i++)
    {
        for (size_t j = 0; j < permutationCommits[i].size(); j++)
        {
            size_t piIndex = i * permutationCommits.size() + j + 1;

            Scalar f = permutations[j][i] * x + a[i][j];
            Scalar z1 = permutationSeeds[j][i] * x + t1[i][j];
            Scalar z2 = productSeeds[i][j] * x + t2[i][j];

            retval[piIndex].responseParts.push_back(f);
            retval[piIndex].responseParts.push_back(z1);
            retval[piIndex].responseParts.push_back(z2);
        }
    }

    return retval;
}

template <typename T>
bool PrsonaBase::verify_unbatched_proof_of_reordering(
    const std::vector<Proof>& pi,
    const std::vector<T>& oldValues,
    const std::vector<std::vector<Twistpoint>>& permutationCommits,
    const std::vector<std::vector<T>>& productCommits,
    const T& otherG,
    const T& otherH) const
{
    if (pi.empty())
        return false;

    if (!SERVER_IS_MALICIOUS)
        return true;

    Twistpoint g = EL_GAMAL_GENERATOR;
    Twistpoint h = elGamalBlindGenerator;

    std::stringstream oracleInput;
    oracleInput << g << h << otherG << otherH;

    for (size_t i = 0; i < oldValues.size(); i++)
        oracleInput << oldValues[i];

    for (size_t i = 0; i < permutationCommits.size(); i++)
        for (size_t j = 0; j < permutationCommits[i].size(); j++)
            oracleInput << permutationCommits[i][j];

    for (size_t i = 0; i < productCommits.size(); i++)
        for (size_t j = 0; j < productCommits[i].size(); j++)
            oracleInput << productCommits[i][j];

    Scalar x = pi[0].challengeParts[0];

    for (size_t i = 0; i < permutationCommits.size(); i++)
    {
        for (size_t j = 0; j < permutationCommits[i].size(); j++)
        {
            size_t piIndex = i * permutationCommits.size() + j + 1;

            Twistpoint U1;
            T U2;

            Scalar f = pi[piIndex].responseParts[0];
            Scalar z1 = pi[piIndex].responseParts[1];
            Scalar z2 = pi[piIndex].responseParts[2];

            U1 = g * f +
                h * z1 -
                permutationCommits[j][i] * x;
            
            U2 = oldValues[j] * f +
                otherH * z2 -
                productCommits[i][j] * x;

            oracleInput << U1 << U2;
        }
    }

    if (x != oracle(oracleInput.str()))
    {
        std::cerr << "Reordered things not generated by permutation matrix." << std::endl;
        return false;
    }

    return true;
}

template <typename T>
std::vector<Proof> PrsonaBase::generate_batched_proof_of_reordering(
    const std::vector<std::vector<Scalar>>& permutations,
    const std::vector<std::vector<Scalar>>& permutationSeeds,
    const std::vector<std::vector<Scalar>>& productSeeds,
    const std::vector<T>& oldValues,
    const std::vector<std::vector<Twistpoint>>& permutationCommits,
    const std::vector<std::vector<T>>& productCommits,
    const T& otherG,
    const T& otherH) const
{
    std::vector<Proof> retval;

    if (!SERVER_IS_MALICIOUS)
    {
        retval.push_back(Proof("PROOF"));
        return retval;
    }

    Proof first;
    retval.push_back(first);

    Twistpoint g = EL_GAMAL_GENERATOR;
    Twistpoint h = elGamalBlindGenerator;

    std::stringstream oracleInput;
    oracleInput << g << h << otherG << otherH;

    for (size_t i = 0; i < oldValues.size(); i++)
        oracleInput << oldValues[i];

    for (size_t i = 0; i < permutationCommits.size(); i++)
        for (size_t j = 0; j < permutationCommits[i].size(); j++)
            oracleInput << permutationCommits[i][j];

    for (size_t i = 0; i < productCommits.size(); i++)
        for (size_t j = 0; j < productCommits[i].size(); j++)
            oracleInput << productCommits[i][j];

    std::vector<Scalar> a;
    std::vector<Scalar> t1;
    std::vector<Scalar> t2;

    for (size_t i = 0; i < permutationCommits.size(); i++)
    {
        Proof currProof;

        Scalar curra;
        Scalar currt1;
        Scalar currt2;

        Twistpoint U1;
        T U2;

        curra.set_random();
        currt1.set_random();
        currt2.set_random();

        U1 = g * curra + h * currt1;
        U2 = oldValues[i] * curra + otherH * currt2;

        oracleInput << U1 << U2;

        a.push_back(curra);
        t1.push_back(currt1);
        t2.push_back(currt2);

        retval.push_back(currProof);
    }

    Scalar x = oracle(oracleInput.str());
    retval[0].challengeParts.push_back(x);

    for (size_t i = 0; i < permutationCommits.size(); i++)
    {
        size_t piIndex = i + 1;

        Scalar f = a[i];
        Scalar z1 = t1[i];
        Scalar z2 = t2[i];

        for (size_t j = 0; j < permutationCommits[i].size(); j++)
        {
            std::stringstream currOracle;
            currOracle << permutationCommits[i][j] << productCommits[j][i];
            Scalar currx = oracle(currOracle.str(), LAMBDA);

            f = f + permutations[i][j] * currx;
            z1 = z1 + permutationSeeds[i][j] * currx;
            z2 = z2 + productSeeds[j][i] * currx;
        }

        retval[piIndex].responseParts.push_back(f);
        retval[piIndex].responseParts.push_back(z1);
        retval[piIndex].responseParts.push_back(z2);
    }

    return retval;
}

template <typename T>
bool PrsonaBase::verify_batched_proof_of_reordering(
    const std::vector<Proof>& pi,
    const std::vector<T>& oldValues,
    const std::vector<std::vector<Twistpoint>>& permutationCommits,
    const std::vector<std::vector<T>>& productCommits,
    const T& otherG,
    const T& otherH) const
{
    if (pi.empty())
        return false;

    if (!SERVER_IS_MALICIOUS)
        return true;

    Twistpoint g = EL_GAMAL_GENERATOR;
    Twistpoint h = elGamalBlindGenerator;

    std::stringstream oracleInput;
    oracleInput << g << h << otherG << otherH;

    for (size_t i = 0; i < oldValues.size(); i++)
        oracleInput << oldValues[i];

    for (size_t i = 0; i < permutationCommits.size(); i++)
        for (size_t j = 0; j < permutationCommits[i].size(); j++)
            oracleInput << permutationCommits[i][j];

    for (size_t i = 0; i < productCommits.size(); i++)
        for (size_t j = 0; j < productCommits[i].size(); j++)
            oracleInput << productCommits[i][j];

    Scalar x = pi[0].challengeParts[0];

    for (size_t i = 0; i < permutationCommits.size(); i++)
    {
        size_t piIndex = i + 1;

        Scalar f = pi[piIndex].responseParts[0];
        Scalar z1 = pi[piIndex].responseParts[1];
        Scalar z2 = pi[piIndex].responseParts[2];

        Twistpoint U1 = g * f + h * z1;
        T U2 = oldValues[i] * f + otherH * z2;

        for (size_t j = 0; j < permutationCommits[i].size(); j++)
        {
            std::stringstream currOracle;
            currOracle << permutationCommits[i][j] << productCommits[j][i];
            Scalar currx = oracle(currOracle.str(), LAMBDA);
            
            U1 = U1 - permutationCommits[i][j] * currx;
            U2 = U2 - productCommits[j][i] * currx;
        }

        oracleInput << U1 << U2;
    }

    if (x != oracle(oracleInput.str()))
    {
        std::cerr << "Reordered things not generated by permutation matrix." << std::endl;
        return false;
    }

    return true;
}

std::vector<Proof> PrsonaBase::generate_proof_of_reordering_plus_power(
    const std::vector<std::vector<Scalar>>& permutations,
    const Scalar& power,
    const std::vector<std::vector<Scalar>>& permutationSeeds,
    const std::vector<std::vector<Scalar>>& productSeeds,
    const std::vector<Twistpoint>& oldValues,
    const std::vector<std::vector<Twistpoint>>& permutationCommits,
    const std::vector<std::vector<Twistpoint>>& productCommits,
    const std::vector<std::vector<Twistpoint>>& seedCommits) const
{
    if (LAMBDA > 0)
        return generate_batched_proof_of_reordering_plus_power(permutations, power, permutationSeeds, productSeeds, oldValues, permutationCommits, productCommits, seedCommits);
    else
        return generate_unbatched_proof_of_reordering_plus_power(permutations, power, permutationSeeds, productSeeds, oldValues, permutationCommits, productCommits, seedCommits);
}

bool PrsonaBase::verify_proof_of_reordering_plus_power(
    const std::vector<Proof>& pi,
    const std::vector<Twistpoint>& oldValues,
    const std::vector<std::vector<Twistpoint>>& permutationCommits,
    const std::vector<std::vector<Twistpoint>>& productCommits,
    const std::vector<std::vector<Twistpoint>>& seedCommits) const
{
    if (LAMBDA > 0)
        return verify_batched_proof_of_reordering_plus_power(pi, oldValues, permutationCommits, productCommits, seedCommits);
    else
        return verify_unbatched_proof_of_reordering_plus_power(pi, oldValues, permutationCommits, productCommits, seedCommits);
}

std::vector<Proof> PrsonaBase::generate_unbatched_proof_of_reordering_plus_power(
    const std::vector<std::vector<Scalar>>& permutations,
    const Scalar& power,
    const std::vector<std::vector<Scalar>>& permutationSeeds,
    const std::vector<std::vector<Scalar>>& productSeeds,
    const std::vector<Twistpoint>& oldValues,
    const std::vector<std::vector<Twistpoint>>& permutationCommits,
    const std::vector<std::vector<Twistpoint>>& productCommits,
    const std::vector<std::vector<Twistpoint>>& seedCommits) const
{
    std::vector<Proof> retval;

    if (!SERVER_IS_MALICIOUS)
    {
        retval.push_back(Proof("PROOF"));
        return retval;
    }

    Proof first;
    retval.push_back(first);
    
    Twistpoint g = EL_GAMAL_GENERATOR;
    Twistpoint h = elGamalBlindGenerator;

    std::stringstream oracleInput;
    oracleInput << g << h;

    for (size_t i = 0; i < oldValues.size(); i++)
        oracleInput << oldValues[i];

    for (size_t i = 0; i < permutationCommits.size(); i++)
        for (size_t j = 0; j < permutationCommits[i].size(); j++)
            oracleInput << permutationCommits[i][j];

    for (size_t i = 0; i < productCommits.size(); i++)
        for (size_t j = 0; j < productCommits[i].size(); j++)
            oracleInput << productCommits[i][j];

    for (size_t i = 0; i < seedCommits.size(); i++)
        for (size_t j = 0; j < seedCommits[i].size(); j++)
            oracleInput << seedCommits[i][j];

    Scalar b1;
    b1.set_random();
    std::vector<std::vector<Scalar>> b2;
    std::vector<std::vector<Scalar>> t1;
    std::vector<std::vector<Scalar>> t2;

    for (size_t i = 0; i < permutationCommits.size(); i++)
    {
        std::vector<Scalar> currb2Row;
        std::vector<Scalar> currt1Row;
        std::vector<Scalar> currt2Row;

        for (size_t j = 0; j < permutationCommits[i].size(); j++)
        {
            Proof currProof;

            Scalar currb2;
            Scalar currt1;
            Scalar currt2;

            Twistpoint U1, U2, U3, U4;

            currb2.set_random();
            currt1.set_random();
            currt2.set_random();

            U1 = g * currb2 + h * currt1;
            U2 = oldValues[j] *
                (b1 * permutations[j][i] + currb2 * power);
            U3 = oldValues[j] * b1 * currb2 + h * currt2;
            U4 = g * currt2;

            currProof.curvepointUniversals.push_back(U2);

            oracleInput << U1 << U2 << U3 << U4;

            currb2Row.push_back(currb2);
            currt1Row.push_back(currt1);
            currt2Row.push_back(currt2);

            retval.push_back(currProof);
        }

        b2.push_back(currb2Row);
        t1.push_back(currt1Row);
        t2.push_back(currt2Row);
    }

    Scalar x = oracle(oracleInput.str());
    retval[0].challengeParts.push_back(x);

    Scalar f1 = power * x + b1;
    retval[0].responseParts.push_back(f1);

    for (size_t i = 0; i < permutationCommits.size(); i++)
    {
        for (size_t j = 0; j < permutationCommits[i].size(); j++)
        {
            size_t piIndex = i * permutationCommits.size() + j + 1;

            Scalar f2 = permutations[j][i] * x + b2[i][j];
            Scalar z1 = permutationSeeds[j][i] * x + t1[i][j];
            Scalar z2 = productSeeds[i][j] * x * x + t2[i][j];

            retval[piIndex].responseParts.push_back(f2);
            retval[piIndex].responseParts.push_back(z1);
            retval[piIndex].responseParts.push_back(z2);
        }
    }

    return retval;
}

bool PrsonaBase::verify_unbatched_proof_of_reordering_plus_power(
    const std::vector<Proof>& pi,
    const std::vector<Twistpoint>& oldValues,
    const std::vector<std::vector<Twistpoint>>& permutationCommits,
    const std::vector<std::vector<Twistpoint>>& productCommits,
    const std::vector<std::vector<Twistpoint>>& seedCommits) const
{
    if (pi.empty())
        return false;

    if (!SERVER_IS_MALICIOUS)
        return true;
    
    Twistpoint g = EL_GAMAL_GENERATOR;
    Twistpoint h = elGamalBlindGenerator;

    std::stringstream oracleInput;
    oracleInput << g << h;

    for (size_t i = 0; i < oldValues.size(); i++)
        oracleInput << oldValues[i];

    for (size_t i = 0; i < permutationCommits.size(); i++)
        for (size_t j = 0; j < permutationCommits[i].size(); j++)
            oracleInput << permutationCommits[i][j];

    for (size_t i = 0; i < productCommits.size(); i++)
        for (size_t j = 0; j < productCommits[i].size(); j++)
            oracleInput << productCommits[i][j];

    for (size_t i = 0; i < seedCommits.size(); i++)
        for (size_t j = 0; j < seedCommits[i].size(); j++)
            oracleInput << seedCommits[i][j];

    Scalar x = pi[0].challengeParts[0];
    Scalar f1 = pi[0].responseParts[0];

    for (size_t i = 0; i < permutationCommits.size(); i++)
    {
        for (size_t j = 0; j < permutationCommits[i].size(); j++)
        {
            size_t piIndex = i * permutationCommits.size() + j + 1;

            Twistpoint U1, U2, U3, U4;
            U2 = pi[piIndex].curvepointUniversals[0];

            Scalar f2 = pi[piIndex].responseParts[0];
            Scalar z1 = pi[piIndex].responseParts[1];
            Scalar z2 = pi[piIndex].responseParts[2];

            U1 = g * f2 + h * z1 - permutationCommits[j][i] * x;
            
            U3 = oldValues[j] * f1 * f2 +
                h * z2 -
                productCommits[i][j] * x * x -
                U2 * x;

            U4 = g * z2 - seedCommits[i][j] * x * x;

            oracleInput << U1 << U2 << U3 << U4;
        }
    }

    if (x != oracle(oracleInput.str()))
    {
        std::cerr << "Reordered + power things not generated by permutation matrix." << std::endl;
        return false;
    }

    for (size_t i = 0; i < seedCommits.size(); i++)
    {
        Twistpoint sum = seedCommits[i][0];

        for (size_t j = 1; j < seedCommits[i].size(); j++)
            sum = sum + seedCommits[i][j];

        if (sum != Twistpoint())
        {
            std::cerr << "seed commits did not sum to 0, aborting." << std::endl;
            return false;
        }
    }

    return true;
}

std::vector<Proof> PrsonaBase::generate_batched_proof_of_reordering_plus_power(
    const std::vector<std::vector<Scalar>>& permutations,
    const Scalar& power,
    const std::vector<std::vector<Scalar>>& permutationSeeds,
    const std::vector<std::vector<Scalar>>& productSeeds,
    const std::vector<Twistpoint>& oldValues,
    const std::vector<std::vector<Twistpoint>>& permutationCommits,
    const std::vector<std::vector<Twistpoint>>& productCommits,
    const std::vector<std::vector<Twistpoint>>& seedCommits) const
{
    std::vector<Proof> retval;

    if (!SERVER_IS_MALICIOUS)
    {
        retval.push_back(Proof("PROOF"));
        return retval;
    }

    Proof first;
    retval.push_back(first);
    
    Twistpoint g = EL_GAMAL_GENERATOR;
    Twistpoint h = elGamalBlindGenerator;

    std::stringstream oracleInput;
    oracleInput << g << h;

    for (size_t i = 0; i < oldValues.size(); i++)
        oracleInput << oldValues[i];

    for (size_t i = 0; i < permutationCommits.size(); i++)
        for (size_t j = 0; j < permutationCommits[i].size(); j++)
            oracleInput << permutationCommits[i][j];

    for (size_t i = 0; i < productCommits.size(); i++)
        for (size_t j = 0; j < productCommits[i].size(); j++)
            oracleInput << productCommits[i][j];

    for (size_t i = 0; i < seedCommits.size(); i++)
        for (size_t j = 0; j < seedCommits[i].size(); j++)
            oracleInput << seedCommits[i][j];

    std::vector<Scalar> b1;
    std::vector<Scalar> b2;
    std::vector<std::vector<Scalar>> b3;
    std::vector<Scalar> t1;
    std::vector<Scalar> t2;
    std::vector<Scalar> t3;

    for (size_t i = 0; i < permutationCommits.size(); i++)
    {
        Proof currProof;

        Scalar currb1;
        Scalar currb2;
        std::vector<Scalar> currb3Row;
        Scalar currt1;
        Scalar currt2;
        Scalar currt3;

        Twistpoint U1, U3, U4;
        std::vector<Twistpoint> U2;

        currb1.set_random();
        currb2.set_random();
        currt1.set_random();
        currt2.set_random();
        currt3.set_random();

        U1 = g * currb2 + h * currt1;
        U3 = oldValues[i] * (currb1 * currb2 + currt3) + h * currt2;
        U4 = g * currt2;

        oracleInput << U1;

        for (size_t j = 0; j < permutationCommits[i].size(); j++)
        {
            Twistpoint U2;
            Scalar currb3;
            currb3.set_random();
            
            Scalar U2mult = (currb1 * permutations[i][j] + currb2 * power + currb3);
            for (size_t k = 0; k < permutationCommits[i].size(); k++)
            {
                if (k == j)
                    continue;

                std::stringstream currOracle;
                currOracle << permutationCommits[i][k] << productCommits[k][i] << seedCommits[k][i];
                Scalar currx = oracle(currOracle.str(), LAMBDA);

                U2mult = U2mult + power * permutations[i][j] * currx;
            }
            U2 = oldValues[i] * U2mult;
            currProof.curvepointUniversals.push_back(U2);

            oracleInput << U2;

            currb3Row.push_back(currb3);
        }
        oracleInput << U3 << U4;

        b1.push_back(currb1);
        b2.push_back(currb2);
        b3.push_back(currb3Row);
        t1.push_back(currt1);
        t2.push_back(currt2);
        t3.push_back(currt3);

        retval.push_back(currProof);
    }

    Scalar x = oracle(oracleInput.str());
    retval[0].challengeParts.push_back(x);

    for (size_t i = 0; i < permutationCommits.size(); i++)
    {
        size_t piIndex = i + 1;

        Scalar f1 = b1[i];
        Scalar f2 = b2[i];
        Scalar z1 = t1[i];
        Scalar z2 = t2[i];
        Scalar z3 = t3[i];

        for (size_t j = 0; j < permutationCommits[i].size(); j++)
        {
            std::stringstream currOracle;
            currOracle << permutationCommits[i][j] << productCommits[j][i] << seedCommits[j][i];
            Scalar currx = oracle(currOracle.str(), LAMBDA);

            f1 = f1 + power * currx;
            f2 = f2 + permutations[i][j] * currx;
            z1 = z1 + permutationSeeds[i][j] * currx;
            z2 = z2 + productSeeds[j][i] * currx * currx;
            z3 = z3 + b3[i][j] * currx;
        }

        retval[piIndex].responseParts.push_back(f1);
        retval[piIndex].responseParts.push_back(f2);
        retval[piIndex].responseParts.push_back(z1);
        retval[piIndex].responseParts.push_back(z2);
        retval[piIndex].responseParts.push_back(z3);
    }

    return retval;
}

bool PrsonaBase::verify_batched_proof_of_reordering_plus_power(
    const std::vector<Proof>& pi,
    const std::vector<Twistpoint>& oldValues,
    const std::vector<std::vector<Twistpoint>>& permutationCommits,
    const std::vector<std::vector<Twistpoint>>& productCommits,
    const std::vector<std::vector<Twistpoint>>& seedCommits) const
{
    if (pi.empty())
        return false;

    if (!SERVER_IS_MALICIOUS)
        return true;
    
    Twistpoint g = EL_GAMAL_GENERATOR;
    Twistpoint h = elGamalBlindGenerator;

    std::stringstream oracleInput;
    oracleInput << g << h;

    for (size_t i = 0; i < oldValues.size(); i++)
        oracleInput << oldValues[i];

    for (size_t i = 0; i < permutationCommits.size(); i++)
        for (size_t j = 0; j < permutationCommits[i].size(); j++)
            oracleInput << permutationCommits[i][j];

    for (size_t i = 0; i < productCommits.size(); i++)
        for (size_t j = 0; j < productCommits[i].size(); j++)
            oracleInput << productCommits[i][j];

    for (size_t i = 0; i < seedCommits.size(); i++)
        for (size_t j = 0; j < seedCommits[i].size(); j++)
            oracleInput << seedCommits[i][j];

    Scalar x = pi[0].challengeParts[0];

    for (size_t i = 0; i < permutationCommits.size(); i++)
    {
        size_t piIndex = i + 1;

        Scalar f1 = pi[piIndex].responseParts[0];
        Scalar f2 = pi[piIndex].responseParts[1];
        Scalar z1 = pi[piIndex].responseParts[2];
        Scalar z2 = pi[piIndex].responseParts[3];
        Scalar z3 = pi[piIndex].responseParts[4];

        Twistpoint U1 = g * f2 + h * z1;
        std::vector<Twistpoint> U2 = pi[piIndex].curvepointUniversals;
        Twistpoint U3 = oldValues[i] * (f1 * f2 + z3) + h * z2;
        Twistpoint U4 = g * z2;

        for (size_t j = 0; j < permutationCommits[i].size(); j++)
        {
            std::stringstream currOracle;
            currOracle << permutationCommits[i][j] << productCommits[j][i] << seedCommits[j][i];
            Scalar currx = oracle(currOracle.str(), LAMBDA);
        
            U1 = U1 - permutationCommits[i][j] * currx;
            U3 = U3 -
                productCommits[j][i] * currx * currx -
                U2[j] * currx;
            U4 = U4 - seedCommits[j][i] * currx * currx;
        }

        oracleInput << U1;
        for (size_t j = 0; j < permutationCommits[i].size(); j++)
            oracleInput << U2[j];
        oracleInput << U3 << U4;
    }

    if (x != oracle(oracleInput.str()))
    {
        std::cerr << "Reordered + power things not generated by permutation matrix." << std::endl;
        return false;
    }

    for (size_t i = 0; i < seedCommits.size(); i++)
    {
        Twistpoint sum = seedCommits[i][0];

        for (size_t j = 1; j < seedCommits[i].size(); j++)
            sum = sum + seedCommits[i][j];

        if (sum != Twistpoint())
        {
            std::cerr << "seed commits did not sum to 0, aborting." << std::endl;
            return false;
        }
    }

    return true;
}

std::vector<Proof> PrsonaBase::generate_user_tally_proofs(
    const std::vector<std::vector<Scalar>>& permutations,
    const Scalar& power,
    const Twistpoint& nextGenerator,
    const std::vector<std::vector<Scalar>>& permutationSeeds,
    const std::vector<std::vector<Scalar>>& userTallySeeds,
    const std::vector<Twistpoint>& currPseudonyms,
    const std::vector<Twistpoint>& userTallyMasks,
    const std::vector<Twistpoint>& userTallyMessages,
    const std::vector<std::vector<Twistpoint>>& permutationCommits,
    const std::vector<std::vector<Twistpoint>>& userTallyMaskCommits,
    const std::vector<std::vector<Twistpoint>>& userTallyMessageCommits,
    const std::vector<std::vector<Twistpoint>>& userTallySeedCommits) const
{
    if (LAMBDA > 0)
        return generate_batched_user_tally_proofs(permutations, power, nextGenerator, permutationSeeds, userTallySeeds, currPseudonyms, userTallyMasks, userTallyMessages, permutationCommits, userTallyMaskCommits, userTallyMessageCommits, userTallySeedCommits);
    else
        return generate_unbatched_user_tally_proofs(permutations, power, nextGenerator, permutationSeeds, userTallySeeds, currPseudonyms, userTallyMasks, userTallyMessages, permutationCommits, userTallyMaskCommits, userTallyMessageCommits, userTallySeedCommits);
}

bool PrsonaBase::verify_user_tally_proofs(
    const std::vector<Proof>& pi,
    const Twistpoint& nextGenerator,
    const std::vector<Twistpoint>& currPseudonyms,
    const std::vector<Twistpoint>& userTallyMasks,
    const std::vector<Twistpoint>& userTallyMessages,
    const std::vector<std::vector<Twistpoint>>& permutationCommits,
    const std::vector<std::vector<Twistpoint>>& userTallyMaskCommits,
    const std::vector<std::vector<Twistpoint>>& userTallyMessageCommits,
    const std::vector<std::vector<Twistpoint>>& userTallySeedCommits) const
{
    if (LAMBDA > 0)
        return verify_batched_user_tally_proofs(pi, nextGenerator, currPseudonyms, userTallyMasks, userTallyMessages, permutationCommits, userTallyMaskCommits, userTallyMessageCommits, userTallySeedCommits);
    else
        return verify_unbatched_user_tally_proofs(pi, nextGenerator, currPseudonyms, userTallyMasks, userTallyMessages, permutationCommits, userTallyMaskCommits, userTallyMessageCommits, userTallySeedCommits);
}

std::vector<Proof> PrsonaBase::generate_unbatched_user_tally_proofs(
    const std::vector<std::vector<Scalar>>& permutations,
    const Scalar& power,
    const Twistpoint& nextGenerator,
    const std::vector<std::vector<Scalar>>& permutationSeeds,
    const std::vector<std::vector<Scalar>>& userTallySeeds,
    const std::vector<Twistpoint>& currPseudonyms,
    const std::vector<Twistpoint>& userTallyMasks,
    const std::vector<Twistpoint>& userTallyMessages,
    const std::vector<std::vector<Twistpoint>>& permutationCommits,
    const std::vector<std::vector<Twistpoint>>& userTallyMaskCommits,
    const std::vector<std::vector<Twistpoint>>& userTallyMessageCommits,
    const std::vector<std::vector<Twistpoint>>& userTallySeedCommits) const
{
    std::vector<Proof> retval;

    if (!SERVER_IS_MALICIOUS)
    {
        retval.push_back(Proof("PROOF"));
        return retval;
    }

    Proof first;
    retval.push_back(first);
    
    Twistpoint g = EL_GAMAL_GENERATOR;
    Twistpoint h = elGamalBlindGenerator;

    std::stringstream oracleInput;
    oracleInput << g << h << nextGenerator;

    for (size_t i = 0; i < currPseudonyms.size(); i++)
        oracleInput << currPseudonyms[i];

    for (size_t i = 0; i < userTallyMasks.size(); i++)
        oracleInput << userTallyMasks[i];

    for (size_t i = 0; i < userTallyMessages.size(); i++)
        oracleInput << userTallyMessages[i];

    for (size_t i = 0; i < permutationCommits.size(); i++)
        for (size_t j = 0; j < permutationCommits[i].size(); j++)
            oracleInput << permutationCommits[i][j];

    for (size_t i = 0; i < userTallyMaskCommits.size(); i++)
        for (size_t j = 0; j < userTallyMaskCommits[i].size(); j++)
            oracleInput << userTallyMaskCommits[i][j];

    for (size_t i = 0; i < userTallyMessageCommits.size(); i++)
        for (size_t j = 0; j < userTallyMessageCommits[i].size(); j++)
            oracleInput << userTallyMessageCommits[i][j];

    for (size_t i = 0; i < userTallySeedCommits.size(); i++)
        for (size_t j = 0; j < userTallySeedCommits[i].size(); j++)
            oracleInput << userTallySeedCommits[i][j];

    Scalar b1;
    b1.set_random();
    std::vector<std::vector<Scalar>> b2;
    std::vector<std::vector<Scalar>> t1;
    std::vector<std::vector<Scalar>> t2;

    for (size_t i = 0; i < permutationCommits.size(); i++)
    {
        std::vector<Scalar> currb2Row;
        std::vector<Scalar> currt1Row;
        std::vector<Scalar> currt2Row;

        for (size_t j = 0; j < permutationCommits[i].size(); j++)
        {
            Proof currProof;

            Scalar currb2;
            Scalar currt1;
            Scalar currt2;

            Twistpoint U1, U2, U3, U4, U5, U6, U7;

            currb2.set_random();
            currt1.set_random();
            currt2.set_random();

            U1 = g * currb2 + h * currt1;
            U2 = userTallyMasks[j] * (b1 * permutations[j][i] + currb2 * power) +
                currPseudonyms[j] * (permutations[j][i] * b1 * userTallySeeds[i][j] + power * currb2 * userTallySeeds[i][j] + permutations[j][i] * power * currt2) +
                h * currt2;
            U3 = userTallyMasks[j] * (b1 * currb2) +
                currPseudonyms[j] * (b1 * currb2 * userTallySeeds[i][j] + permutations[j][i] * b1 * currt2 + power * currb2 * currt2);
            U4 = currPseudonyms[j] * (b1 * currb2 * currt2);
            U5 = userTallyMessages[j] * currb2 +
                nextGenerator * (permutations[j][i] * currt2 + userTallySeeds[i][j] * currb2) +
                h * currt2;
            U6 = nextGenerator * (currb2 * currt2);
            U7 = g * currt2;

            currProof.curvepointUniversals.push_back(U2);
            currProof.curvepointUniversals.push_back(U3);
            currProof.curvepointUniversals.push_back(U5);

            oracleInput << U1 << U2 << U3 << U4 << U5 << U6 << U7;

            currb2Row.push_back(currb2);
            currt1Row.push_back(currt1);
            currt2Row.push_back(currt2);

            retval.push_back(currProof);
        }

        b2.push_back(currb2Row);
        t1.push_back(currt1Row);
        t2.push_back(currt2Row);
    }

    Scalar x = oracle(oracleInput.str());
    retval[0].challengeParts.push_back(x);

    Scalar f1 = power * x + b1;
    retval[0].responseParts.push_back(f1);

    for (size_t i = 0; i < permutationCommits.size(); i++)
    {
        for (size_t j = 0; j < permutationCommits[i].size(); j++)
        {
            size_t piIndex = i * permutationCommits.size() + j + 1;

            Scalar f2 = permutations[j][i] * x + b2[i][j];
            Scalar z1 = permutationSeeds[j][i] * x + t1[i][j];
            Scalar z2 = userTallySeeds[i][j] * x + t2[i][j];

            retval[piIndex].responseParts.push_back(f2);
            retval[piIndex].responseParts.push_back(z1);
            retval[piIndex].responseParts.push_back(z2);
        }
    }

    return retval;
}

bool PrsonaBase::verify_unbatched_user_tally_proofs(
    const std::vector<Proof>& pi,
    const Twistpoint& nextGenerator,
    const std::vector<Twistpoint>& currPseudonyms,
    const std::vector<Twistpoint>& userTallyMasks,
    const std::vector<Twistpoint>& userTallyMessages,
    const std::vector<std::vector<Twistpoint>>& permutationCommits,
    const std::vector<std::vector<Twistpoint>>& userTallyMaskCommits,
    const std::vector<std::vector<Twistpoint>>& userTallyMessageCommits,
    const std::vector<std::vector<Twistpoint>>& userTallySeedCommits) const
{
    if (pi.empty())
        return false;

    if (!SERVER_IS_MALICIOUS)
        return true;
    
    Twistpoint g = EL_GAMAL_GENERATOR;
    Twistpoint h = elGamalBlindGenerator;

    std::stringstream oracleInput;
    oracleInput << g << h << nextGenerator;

    for (size_t i = 0; i < currPseudonyms.size(); i++)
        oracleInput << currPseudonyms[i];

    for (size_t i = 0; i < userTallyMasks.size(); i++)
        oracleInput << userTallyMasks[i];

    for (size_t i = 0; i < userTallyMessages.size(); i++)
        oracleInput << userTallyMessages[i];

    for (size_t i = 0; i < permutationCommits.size(); i++)
        for (size_t j = 0; j < permutationCommits[i].size(); j++)
            oracleInput << permutationCommits[i][j];

    for (size_t i = 0; i < userTallyMaskCommits.size(); i++)
        for (size_t j = 0; j < userTallyMaskCommits[i].size(); j++)
            oracleInput << userTallyMaskCommits[i][j];

    for (size_t i = 0; i < userTallyMessageCommits.size(); i++)
        for (size_t j = 0; j < userTallyMessageCommits[i].size(); j++)
            oracleInput << userTallyMessageCommits[i][j];

    for (size_t i = 0; i < userTallySeedCommits.size(); i++)
        for (size_t j = 0; j < userTallySeedCommits[i].size(); j++)
            oracleInput << userTallySeedCommits[i][j];

    Scalar x = pi[0].challengeParts[0];
    Scalar f1 = pi[0].responseParts[0];

    for (size_t i = 0; i < permutationCommits.size(); i++)
    {
        for (size_t j = 0; j < permutationCommits[i].size(); j++)
        {
            size_t piIndex = i * permutationCommits.size() + j + 1;

            Twistpoint U1, U2, U3, U4, U5, U6, U7;
            U2 = pi[piIndex].curvepointUniversals[0];
            U3 = pi[piIndex].curvepointUniversals[1];
            U5 = pi[piIndex].curvepointUniversals[2];

            Scalar f2 = pi[piIndex].responseParts[0];
            Scalar z1 = pi[piIndex].responseParts[1];
            Scalar z2 = pi[piIndex].responseParts[2];

            U1 = g * f2 + h * z1 - permutationCommits[j][i] * x;
            
            U4 = userTallyMasks[j] * (f1 * f2 * x) +
                currPseudonyms[j] * (f1 * f2 * z2) +
                h * (z2 * x * x) -
                userTallyMaskCommits[i][j] * (x * x * x) -
                U2 * (x * x) -
                U3 * x;

            U6 = userTallyMessages[j] * (f2 * x) +
                nextGenerator * (f2 * z2) +
                h * (z2 * x) -
                userTallyMessageCommits[i][j] * (x * x) -
                U5 * x;

            U7 = g * z2 - userTallySeedCommits[i][j] * x;

            oracleInput << U1 << U2 << U3 << U4 << U5 << U6 << U7;
        }
    }

    if (x != oracle(oracleInput.str()))
    {
        std::cerr << "User tallies not generated by permutation matrix." << std::endl;
        return false;
    }

    for (size_t i = 0; i < userTallySeedCommits.size(); i++)
    {
        Twistpoint sum = userTallySeedCommits[i][0];

        for (size_t j = 1; j < userTallySeedCommits[i].size(); j++)
            sum = sum + userTallySeedCommits[i][j];

        if (sum != Twistpoint())
        {
            std::cerr << "seed commits did not sum to 0, aborting." << std::endl;
            return false;
        }
    }

    return true;
}

std::vector<Proof> PrsonaBase::generate_batched_user_tally_proofs(
    const std::vector<std::vector<Scalar>>& permutations,
    const Scalar& power,
    const Twistpoint& nextGenerator,
    const std::vector<std::vector<Scalar>>& permutationSeeds,
    const std::vector<std::vector<Scalar>>& userTallySeeds,
    const std::vector<Twistpoint>& currPseudonyms,
    const std::vector<Twistpoint>& userTallyMasks,
    const std::vector<Twistpoint>& userTallyMessages,
    const std::vector<std::vector<Twistpoint>>& permutationCommits,
    const std::vector<std::vector<Twistpoint>>& userTallyMaskCommits,
    const std::vector<std::vector<Twistpoint>>& userTallyMessageCommits,
    const std::vector<std::vector<Twistpoint>>& userTallySeedCommits) const
{
    std::vector<Proof> retval;

    if (!SERVER_IS_MALICIOUS)
    {
        retval.push_back(Proof("PROOF"));
        return retval;
    }

    Proof first;
    retval.push_back(first);
    
    Twistpoint g = EL_GAMAL_GENERATOR;
    Twistpoint h = elGamalBlindGenerator;

    std::stringstream oracleInput;
    oracleInput << g << h << nextGenerator;

    for (size_t i = 0; i < currPseudonyms.size(); i++)
        oracleInput << currPseudonyms[i];

    for (size_t i = 0; i < userTallyMasks.size(); i++)
        oracleInput << userTallyMasks[i];

    for (size_t i = 0; i < userTallyMessages.size(); i++)
        oracleInput << userTallyMessages[i];

    for (size_t i = 0; i < permutationCommits.size(); i++)
        for (size_t j = 0; j < permutationCommits[i].size(); j++)
            oracleInput << permutationCommits[i][j];

    for (size_t i = 0; i < userTallyMaskCommits.size(); i++)
        for (size_t j = 0; j < userTallyMaskCommits[i].size(); j++)
            oracleInput << userTallyMaskCommits[i][j];

    for (size_t i = 0; i < userTallyMessageCommits.size(); i++)
        for (size_t j = 0; j < userTallyMessageCommits[i].size(); j++)
            oracleInput << userTallyMessageCommits[i][j];

    for (size_t i = 0; i < userTallySeedCommits.size(); i++)
        for (size_t j = 0; j < userTallySeedCommits[i].size(); j++)
            oracleInput << userTallySeedCommits[i][j];

    std::vector<Scalar> b1;
    std::vector<Scalar> b2;
    std::vector<Scalar> t1;
    std::vector<Scalar> t2;

    for (size_t i = 0; i < permutationCommits.size(); i++)
    {
        Proof currProof;

        Scalar currb1;
        Scalar currb2;
        Scalar currt1;
        Scalar currt2;

        Twistpoint U1, U4, U6, U7;
        std::vector<Twistpoint> U2, U3, U5;

        currb1.set_random();
        currb2.set_random();
        currt1.set_random();
        currt2.set_random();

        U1 = g * currb2 + h * currt1;
        U4 = currPseudonyms[i] * (currb1 * currb2 * currt2);
        U6 = nextGenerator * (currb2 * currt2);
        U7 = g * currt2;
        for (size_t j = 0; j < permutationCommits[i].size(); j++)
        {
            Twistpoint currU2, currU3, currU5;
            
            Scalar U2MaskMult = power * currb2 + currb1 * permutations[i][j];
            Scalar U2PseudMult = 
                power * currt2 * permutations[i][j] +
                power * currb2 * userTallySeeds[j][i] +
                currb1 * permutations[i][j] * userTallySeeds[j][i];
            Scalar U2hMult = currt2;

            Scalar U3MaskMult = currb1 * currb2;
            Scalar U3PseudMult = power * currb2 * currt2 + 
                currb1 * currt2 * permutations[i][j] +
                currb1 * currb2 * userTallySeeds[j][i];
            Scalar U3hMult = Scalar(0);

            Scalar U5MessageMult = currb2;
            Scalar U5GenMult = currb2 * userTallySeeds[j][i] + currt2 * permutations[i][j];
            Scalar U5hMult = currt2;
            for (size_t k = 0; k < permutationCommits[i].size(); k++)
            {
                if (k == j)
                    continue;

                std::stringstream xkOracle;
                xkOracle << permutationCommits[i][k] << userTallyMaskCommits[k][i] << userTallyMessageCommits[k][i] << userTallySeedCommits[k][i];
                Scalar x_k = oracle(xkOracle.str(), LAMBDA);

                for (size_t l = 0; l < permutationCommits[i].size(); l++)
                {
                    if (l == j)
                        continue;
                    if (l == k)
                        continue;

                    std::stringstream xlOracle;
                    xlOracle << permutationCommits[i][l] << userTallyMaskCommits[l][i] << userTallyMessageCommits[l][i] << userTallySeedCommits[l][i];
                    Scalar x_l = oracle(xlOracle.str(), LAMBDA);

                    U3MaskMult = U3MaskMult +
                        power * permutations[i][j] * x_k * x_l;
                    U3PseudMult = U3PseudMult +
                        power * permutations[i][j] * userTallySeeds[k][i] * x_k * x_l;
                    U3hMult = U3hMult +
                        userTallySeeds[j][i] * x_k * x_l;
                }

                U2MaskMult = U2MaskMult +
                    Scalar(2) * power * permutations[i][j] * x_k +
                    power * permutations[i][k] * x_k;
                U2PseudMult = U2PseudMult +
                    power * permutations[i][j] * userTallySeeds[j][i] * x_k +
                    power * permutations[i][k] * userTallySeeds[j][i] * x_k +
                    power * permutations[i][j] * userTallySeeds[k][i] * x_k;
                U2hMult = U2hMult +
                    Scalar(2) * userTallySeeds[j][i] * x_k +
                    userTallySeeds[k][i] * x_k;

                U3MaskMult = U3MaskMult +
                    power * currb2 * x_k +
                    currb1 * permutations[i][j] * x_k;
                U3PseudMult = U3PseudMult +
                    power * currt2 * permutations[i][j] * x_k +
                    power * currb2 * userTallySeeds[j][i] * x_k +
                    currb1 * permutations[i][j] * userTallySeeds[k][i] * x_k;
                U3hMult = U3hMult +
                    currt2 * x_k;

                U5MessageMult = U5MessageMult +
                    permutations[i][j] * x_k;
                U5GenMult = U5GenMult + 
                    permutations[i][j] * userTallySeeds[k][i] * x_k;
                U5hMult = U5hMult +
                    userTallySeeds[j][i] * x_k;
            }
            currU2 = userTallyMasks[i] * U2MaskMult +
                currPseudonyms[i] * U2PseudMult +
                h * U2hMult;

            currU3 = userTallyMasks[i] * U3MaskMult +
                currPseudonyms[i] * U3PseudMult +
                h * U3hMult;

            currU5 = userTallyMessages[i] * U5MessageMult +
                nextGenerator * U5GenMult +
                h * U5hMult;
        
            U2.push_back(currU2);
            U3.push_back(currU3);
            U5.push_back(currU5);
        }

        oracleInput << U1;
        for (size_t j = 0; j < permutationCommits[i].size(); j++)
        {
            oracleInput << U2[j];
            currProof.curvepointUniversals.push_back(U2[j]);
        }
        for (size_t j = 0; j < permutationCommits[i].size(); j++)
        {
            oracleInput << U3[j];
            currProof.curvepointUniversals.push_back(U3[j]);
        }
        oracleInput << U4;
        for (size_t j = 0; j < permutationCommits[i].size(); j++)
        {
            oracleInput << U5[j];
            currProof.curvepointUniversals.push_back(U5[j]);
        }
        oracleInput << U6 << U7;

        b1.push_back(currb1);
        b2.push_back(currb2);
        t1.push_back(currt1);
        t2.push_back(currt2);

        retval.push_back(currProof);
    }

    Scalar x = oracle(oracleInput.str());
    retval[0].challengeParts.push_back(x);

    for (size_t i = 0; i < permutationCommits.size(); i++)
    {
        size_t piIndex = i + 1;

        Scalar f1 = b1[i];
        Scalar f2 = b2[i];
        Scalar z1 = t1[i];
        Scalar z2 = t2[i];

        for (size_t j = 0; j < permutationCommits[i].size(); j++)
        {
            std::stringstream currOracle;
            currOracle << permutationCommits[i][j] << userTallyMaskCommits[j][i] << userTallyMessageCommits[j][i] << userTallySeedCommits[j][i];
            Scalar currx = oracle(currOracle.str(), LAMBDA);

            f1 = f1 + power * currx;
            f2 = f2 + permutations[i][j] * currx;
            z1 = z1 + permutationSeeds[i][j] * currx;
            z2 = z2 + userTallySeeds[j][i] * currx;
        }

        retval[piIndex].responseParts.push_back(f1);
        retval[piIndex].responseParts.push_back(f2);
        retval[piIndex].responseParts.push_back(z1);
        retval[piIndex].responseParts.push_back(z2);
    }

    return retval;
}

bool PrsonaBase::verify_batched_user_tally_proofs(
    const std::vector<Proof>& pi,
    const Twistpoint& nextGenerator,
    const std::vector<Twistpoint>& currPseudonyms,
    const std::vector<Twistpoint>& userTallyMasks,
    const std::vector<Twistpoint>& userTallyMessages,
    const std::vector<std::vector<Twistpoint>>& permutationCommits,
    const std::vector<std::vector<Twistpoint>>& userTallyMaskCommits,
    const std::vector<std::vector<Twistpoint>>& userTallyMessageCommits,
    const std::vector<std::vector<Twistpoint>>& userTallySeedCommits) const
{
    if (pi.empty())
        return false;

    if (!SERVER_IS_MALICIOUS)
        return true;
    
    Twistpoint g = EL_GAMAL_GENERATOR;
    Twistpoint h = elGamalBlindGenerator;

    std::stringstream oracleInput;
    oracleInput << g << h << nextGenerator;

    for (size_t i = 0; i < currPseudonyms.size(); i++)
        oracleInput << currPseudonyms[i];

    for (size_t i = 0; i < userTallyMasks.size(); i++)
        oracleInput << userTallyMasks[i];

    for (size_t i = 0; i < userTallyMessages.size(); i++)
        oracleInput << userTallyMessages[i];

    for (size_t i = 0; i < permutationCommits.size(); i++)
        for (size_t j = 0; j < permutationCommits[i].size(); j++)
            oracleInput << permutationCommits[i][j];

    for (size_t i = 0; i < userTallyMaskCommits.size(); i++)
        for (size_t j = 0; j < userTallyMaskCommits[i].size(); j++)
            oracleInput << userTallyMaskCommits[i][j];

    for (size_t i = 0; i < userTallyMessageCommits.size(); i++)
        for (size_t j = 0; j < userTallyMessageCommits[i].size(); j++)
            oracleInput << userTallyMessageCommits[i][j];

    for (size_t i = 0; i < userTallySeedCommits.size(); i++)
        for (size_t j = 0; j < userTallySeedCommits[i].size(); j++)
            oracleInput << userTallySeedCommits[i][j];

    Scalar x = pi[0].challengeParts[0];

    for (size_t i = 0; i < permutationCommits.size(); i++)
    {
        Scalar sum_of_sub_xs = Scalar(0);
        std::vector<Scalar> sub_xs;
        for (size_t j = 0; j < permutationCommits[i].size(); j++)
        {
            std::stringstream currOracle;
            currOracle << permutationCommits[i][j] << userTallyMaskCommits[j][i] << userTallyMessageCommits[j][i] << userTallySeedCommits[j][i];
            sub_xs.push_back(oracle(currOracle.str(), LAMBDA));
            sum_of_sub_xs = sum_of_sub_xs + sub_xs[j];
        }

        size_t piIndex = i + 1;

        std::vector<Twistpoint> U2(pi[piIndex].curvepointUniversals.begin(), pi[piIndex].curvepointUniversals.begin() + permutationCommits.size());
        std::vector<Twistpoint> U3(pi[piIndex].curvepointUniversals.begin() + permutationCommits.size(), pi[piIndex].curvepointUniversals.begin() + (2 * permutationCommits.size()));
        std::vector<Twistpoint> U5(pi[piIndex].curvepointUniversals.begin() + (2 * permutationCommits.size()), pi[piIndex].curvepointUniversals.end());

        Scalar f1 = pi[piIndex].responseParts[0];
        Scalar f2 = pi[piIndex].responseParts[1];
        Scalar z1 = pi[piIndex].responseParts[2];
        Scalar z2 = pi[piIndex].responseParts[3];

        Twistpoint U1 = g * f2 + h * z1;
        Twistpoint U4 = userTallyMasks[i] * (f1 * f2 * sum_of_sub_xs) +
            currPseudonyms[i] * (f1 * f2 * z2) +
            h * (z2 * sum_of_sub_xs * sum_of_sub_xs);
        Twistpoint U6 = userTallyMessages[i] * (f2 * sum_of_sub_xs) +
            nextGenerator * (f2 * z2) +
            h * (z2 * sum_of_sub_xs);
        Twistpoint U7 = g * z2;

        for (size_t j = 0; j < permutationCommits[i].size(); j++)
        {
            U1 = U1 - permutationCommits[i][j] * sub_xs[j];
            
            U4 = U4 -
                userTallyMaskCommits[j][i] * (sub_xs[j] * sub_xs[j] * sub_xs[j]) -
                U2[j] * (sub_xs[j] * sub_xs[j]) -
                U3[j] * sub_xs[j];

            U6 = U6 -
                userTallyMessageCommits[j][i] * (sub_xs[j] * sub_xs[j]) -
                U5[j] * sub_xs[j];

            U7 = U7 - userTallySeedCommits[j][i] * sub_xs[j];
        }

        oracleInput << U1;
        for (size_t j = 0; j < permutationCommits[i].size(); j++)
            oracleInput << U2[j];
        for (size_t j = 0; j < permutationCommits[i].size(); j++)
            oracleInput << U3[j];
        oracleInput << U4;
        for (size_t j = 0; j < permutationCommits[i].size(); j++)
            oracleInput << U5[j];
        oracleInput << U6 << U7;
    }

    if (x != oracle(oracleInput.str()))
    {
        std::cerr << "User tallies not generated by permutation matrix." << std::endl;
        return false;
    }

    for (size_t i = 0; i < userTallySeedCommits.size(); i++)
    {
        Twistpoint sum = userTallySeedCommits[i][0];

        for (size_t j = 1; j < userTallySeedCommits[i].size(); j++)
            sum = sum + userTallySeedCommits[i][j];

        if (sum != Twistpoint())
        {
            std::cerr << "seed commits did not sum to 0, aborting." << std::endl;
            return false;
        }
    }

    return true;
}

/*
 * SERVER AGREEMENT PROOFS
 */

Proof PrsonaBase::generate_valid_vote_row_proof(
    const std::vector<TwistBipoint>& commitment) const
{
    Proof retval;

    if (!SERVER_IS_MALICIOUS)
    {
        retval.hbc = "PROOF";
        return retval;
    }

    std::stringstream oracleInput;
    for (size_t i = 0; i < commitment.size(); i++)
        oracleInput << commitment[i];

    Scalar val = oracle(oracleInput.str());

    retval.responseParts.push_back(val);
    return retval;
}

Proof PrsonaBase::generate_valid_vote_matrix_proof(
    const std::vector<std::vector<TwistBipoint>>& commitment) const
{
    Proof retval;

    if (!SERVER_IS_MALICIOUS)
    {
        retval.hbc = "PROOF";
        return retval;
    }

    std::stringstream oracleInput;
    for (size_t i = 0; i < commitment.size(); i++)
        for (size_t j = 0; j < commitment[i].size(); j++)
            oracleInput << commitment[i][j];

    Scalar val = oracle(oracleInput.str());

    retval.responseParts.push_back(val);
    return retval;
}

Proof PrsonaBase::generate_valid_user_tally_proof(
    const EGCiphertext& commitment) const
{
    Proof retval;

    if (!SERVER_IS_MALICIOUS)
    {
        retval.hbc = "PROOF";
        return retval;
    }

    std::stringstream oracleInput;
    oracleInput << commitment;

    Scalar val = oracle(oracleInput.str());

    retval.responseParts.push_back(val);
    return retval;
}

Proof PrsonaBase::generate_valid_server_tally_proof(
    const CurveBipoint& commitment) const
{
    Proof retval;

    if (!SERVER_IS_MALICIOUS)
    {
        retval.hbc = "PROOF";
        return retval;
    }

    std::stringstream oracleInput;
    oracleInput << commitment;

    Scalar val = oracle(oracleInput.str());

    retval.responseParts.push_back(val);
    return retval;
}

Proof PrsonaBase::generate_valid_pseudonyms_proof(
    const std::vector<Twistpoint>& commitment) const
{
    Proof retval;

    if (!SERVER_IS_MALICIOUS)
    {
        retval.hbc = "PROOF";
        return retval;
    }

    std::stringstream oracleInput;
    for (size_t i = 0; i < commitment.size(); i++)
        oracleInput << commitment[i];

    Scalar val = oracle(oracleInput.str());

    retval.responseParts.push_back(val);
    return retval;
}

bool PrsonaBase::verify_valid_vote_row_proof(
    const std::vector<Proof>& pi,
    const std::vector<TwistBipoint>& commitment) const
{
    if (pi.empty())
        return false;

    if (!SERVER_IS_MALICIOUS)
        return true;

    Scalar comparison = pi[0].responseParts[0];

    std::stringstream oracleInput;
    for (size_t i = 0; i < commitment.size(); i++)
        oracleInput << commitment[i];

    if (oracle(oracleInput.str()) != comparison)
    {
        std::cerr << "Server's claimed value doesn't match their own commitment." << std::endl;
        return false;
    }

    size_t agreement = 1;
    for (size_t i = 1; i < pi.size(); i++)
        if (comparison == pi[i].responseParts[0])
            agreement++;

    return agreement * 2 > pi.size();
}

bool PrsonaBase::verify_valid_vote_matrix_proof(
    const std::vector<Proof>& pi,
    const std::vector<std::vector<TwistBipoint>>& commitment) const
{
    if (pi.empty())
        return false;

    if (!SERVER_IS_MALICIOUS)
        return true;

    Scalar comparison = pi[0].responseParts[0];

    std::stringstream oracleInput;
    for (size_t i = 0; i < commitment.size(); i++)
        for (size_t j = 0; j < commitment[i].size(); j++)
            oracleInput << commitment[i][j];

    if (oracle(oracleInput.str()) != comparison)
    {
        std::cerr << "Server's claimed value doesn't match their own commitment." << std::endl;
        return false;
    }

    size_t agreement = 1;
    for (size_t i = 1; i < pi.size(); i++)
        if (comparison == pi[i].responseParts[0])
            agreement++;

    return agreement * 2 > pi.size();
}

bool PrsonaBase::verify_valid_user_tally_proof(
    const std::vector<Proof>& pi,
    const EGCiphertext& commitment) const
{
    if (pi.empty())
        return false;

    if (!SERVER_IS_MALICIOUS)
        return true;

    Scalar comparison = pi[0].responseParts[0];

    std::stringstream oracleInput;
    oracleInput << commitment;

    if (oracle(oracleInput.str()) != comparison)
    {
        std::cerr << "Server's claimed value doesn't match their own commitment." << std::endl;
        return false;
    }

    size_t agreement = 1;
    for (size_t i = 1; i < pi.size(); i++)
        if (comparison == pi[i].responseParts[0])
            agreement++;

    return agreement * 2 > pi.size();
}

bool PrsonaBase::verify_valid_server_tally_proof(
    const std::vector<Proof>& pi,
    const CurveBipoint& commitment) const
{
    if (pi.empty())
        return false;

    if (!SERVER_IS_MALICIOUS)
        return true;

    Scalar comparison = pi[0].responseParts[0];

    std::stringstream oracleInput;
    oracleInput << commitment;

    if (oracle(oracleInput.str()) != comparison)
    {
        std::cerr << "Server's claimed value doesn't match their own commitment." << std::endl;
        return false;
    }

    size_t agreement = 1;
    for (size_t i = 1; i < pi.size(); i++)
        if (comparison == pi[i].responseParts[0])
            agreement++;

    return agreement * 2 > pi.size();
}

bool PrsonaBase::verify_valid_pseudonyms_proof(
    const std::vector<Proof>& pi,
    const std::vector<Twistpoint>& commitment) const
{
    if (pi.empty())
        return false;

    if (!SERVER_IS_MALICIOUS)
        return true;

    Scalar comparison = pi[0].responseParts[0];

    std::stringstream oracleInput;
    for (size_t i = 0; i < commitment.size(); i++)
        oracleInput << commitment[i];

    if (oracle(oracleInput.str()) != comparison)
    {
        std::cerr << "Server's claimed value doesn't match their own commitment." << std::endl;
        return false;
    }

    size_t agreement = 1;
    for (size_t i = 1; i < pi.size(); i++)
        if (comparison == pi[i].responseParts[0])
            agreement++;

    return agreement * 2 > pi.size();
}

template std::vector<Proof> PrsonaBase::generate_proof_of_reordering<Twistpoint>(
    const std::vector<std::vector<Scalar>>& permutations,
    const std::vector<std::vector<Scalar>>& permutationSeeds,
    const std::vector<std::vector<Scalar>>& productSeeds,
    const std::vector<Twistpoint>& oldValues,
    const std::vector<std::vector<Twistpoint>>& permutationCommits,
    const std::vector<std::vector<Twistpoint>>& productCommits,
    const Twistpoint& otherG,
    const Twistpoint& otherH) const;

template std::vector<Proof> PrsonaBase::generate_proof_of_reordering<TwistBipoint>(
    const std::vector<std::vector<Scalar>>& permutations,
    const std::vector<std::vector<Scalar>>& permutationSeeds,
    const std::vector<std::vector<Scalar>>& productSeeds,
    const std::vector<TwistBipoint>& oldValues,
    const std::vector<std::vector<Twistpoint>>& permutationCommits,
    const std::vector<std::vector<TwistBipoint>>& productCommits,
    const TwistBipoint& otherG,
    const TwistBipoint& otherH) const;

template std::vector<Proof> PrsonaBase::generate_proof_of_reordering<CurveBipoint>(
    const std::vector<std::vector<Scalar>>& permutations,
    const std::vector<std::vector<Scalar>>& permutationSeeds,
    const std::vector<std::vector<Scalar>>& productSeeds,
    const std::vector<CurveBipoint>& oldValues,
    const std::vector<std::vector<Twistpoint>>& permutationCommits,
    const std::vector<std::vector<CurveBipoint>>& productCommits,
    const CurveBipoint& otherG,
    const CurveBipoint& otherH) const;

template bool PrsonaBase::verify_proof_of_reordering<Twistpoint>(
    const std::vector<Proof>& pi,
    const std::vector<Twistpoint>& oldValues,
    const std::vector<std::vector<Twistpoint>>& permutationCommits,
    const std::vector<std::vector<Twistpoint>>& productCommits,
    const Twistpoint& otherG,
    const Twistpoint& otherH) const;

template bool PrsonaBase::verify_proof_of_reordering<TwistBipoint>(
    const std::vector<Proof>& pi,
    const std::vector<TwistBipoint>& oldValues,
    const std::vector<std::vector<Twistpoint>>& permutationCommits,
    const std::vector<std::vector<TwistBipoint>>& productCommits,
    const TwistBipoint& otherG,
    const TwistBipoint& otherH) const;

template bool PrsonaBase::verify_proof_of_reordering<CurveBipoint>(
    const std::vector<Proof>& pi,
    const std::vector<CurveBipoint>& oldValues,
    const std::vector<std::vector<Twistpoint>>& permutationCommits,
    const std::vector<std::vector<CurveBipoint>>& productCommits,
    const CurveBipoint& otherG,
    const CurveBipoint& otherH) const;
