package profiling;

import com.google.protobuf.InvalidProtocolBufferException;
import meerkat.crypto.concrete.ECElGamalEncryption;
import meerkat.crypto.concrete.Util;
import meerkat.mixer.Utils;
import meerkat.protobuf.ConcreteCrypto;
import meerkat.protobuf.Crypto;
import meerkat.protobuf.Voting;
import org.factcenter.qilin.primitives.concrete.ECElGamal;
import org.factcenter.qilin.primitives.concrete.ECGroup;

import java.math.BigInteger;
import java.util.Random;

/**
 * Created by Tzlil on 1/20/2016.
 */
public class Rerandomize {

    Random rand;
    ECElGamal.SK key;
    ECGroup group;
    ECElGamalEncryption enc;
    ConcreteCrypto.ElGamalPublicKey serializedPk;
    int n;
    Crypto.EncryptionRandomness[] randomnesses;
    Crypto.RerandomizableEncryptedMessage[] encryptedMessage;

    public void setup() throws Exception {
        rand = new Random();
        group = new ECGroup("secp256k1");
        BigInteger sk = ECElGamal.generateSecretKey(group, rand);
        key = new ECElGamal.SK(group, sk);
        serializedPk = Util.encodePK(group, key);
        enc = new ECElGamalEncryption();
        enc.init(serializedPk);
        int LogVotes = 10;
        int layers = 2*LogVotes - 1;
        n = layers * (1<<LogVotes) / 2;
        randomnesses = new Crypto.EncryptionRandomness[n];
        encryptedMessage = new Crypto.RerandomizableEncryptedMessage[n];

        Voting.PlaintextBallot msg;

        for (int i = 0; i < n ; i ++){
            msg = Utils.genRandomBallot(2,3,16);
            randomnesses[i] = enc.generateRandomness(rand);
            encryptedMessage[i] = enc.encrypt(msg, enc.generateRandomness(rand));
        }
    }

    public void RerandomizeProfiling() throws InvalidProtocolBufferException {

        System.out.println("Rerandomiz");
        System.out.println("n is : " + n);
        System.out.println("start n operations");
        long startTime = System.currentTimeMillis();

        for (int i = 0; i < n ; i ++){
            enc.rerandomize(encryptedMessage[i],randomnesses[i]);
        }

        long finishTime = System.currentTimeMillis();
        System.out.println("    that took: "+(finishTime-startTime)+ " ms");
        System.out.println("    avg of"+((double)(finishTime-startTime))/n + " ms");
    }
}
