/*
 * Copyright 2018 Scytl Secure Electronic Voting SA
 *
 * All rights reserved
 *
 * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
 */
package com.scytl.cryptolib.proofs.service;

import java.security.Security;
import java.util.List;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

import com.scytl.cryptolib.api.exceptions.GeneralCryptoLibException;
import com.scytl.cryptolib.elgamal.bean.ElGamalPublicKey;
import com.scytl.cryptolib.elgamal.cryptoapi.Ciphertext;
import com.scytl.cryptolib.elgamal.cryptoapi.Witness;
import com.scytl.cryptolib.elgamal.utils.ElGamalTestDataGenerator;
import com.scytl.cryptolib.mathematical.groups.impl.ZpGroupElement;
import com.scytl.cryptolib.mathematical.groups.impl.ZpSubgroup;
import com.scytl.cryptolib.mathematical.groups.utils.MathematicalTestDataGenerator;
import com.scytl.cryptolib.proofs.bean.ProofPreComputedValues;
import com.scytl.cryptolib.proofs.bean.SimplePlaintextCiphertextPair;
import com.scytl.cryptolib.proofs.bean.SimplePlaintextPublicKeyPair;
import com.scytl.cryptolib.proofs.proof.Proof;
import com.scytl.cryptolib.proofs.utils.ProofsTestDataGenerator;

/**
 * Tests of the Proofs service API for simple plaintext equality zero knowledge
 * proofs of knowledge.
 */
public class SimplePlaintextEqualityProofTest {

    private static final int NUM_PLAINTEXT_ELEMENTS = 6;

    private static ProofsService _proofsServiceForDefaultPolicy;

    private static ZpSubgroup _zpSubgroup;

    private static ElGamalPublicKey _parentPublicKey;

    private static ElGamalPublicKey _primaryPublicKey;

    private static ElGamalPublicKey _secondaryPublicKey;

    private static Ciphertext _primaryCiphertext;

    private static Ciphertext _secondaryCiphertext;

    private static Witness _witness;

    private static Proof _proof;

    private static ProofPreComputedValues _preComputedValues;

    private static ZpSubgroup _differentZpSubgroup;

    private static ElGamalPublicKey _differentPrimaryPublicKey;

    private static ElGamalPublicKey _differentSecondaryPublicKey;

    private static Ciphertext _differentPrimaryCiphertext;

    private static Ciphertext _differentSecondaryCiphertext;

    @BeforeClass
    public static void setUp() throws Exception {

        Security.addProvider(new BouncyCastleProvider());

        _proofsServiceForDefaultPolicy = new ProofsService();

        _zpSubgroup = MathematicalTestDataGenerator.getZpSubgroup();

        _parentPublicKey = ElGamalTestDataGenerator
            .getKeyPair(_zpSubgroup, NUM_PLAINTEXT_ELEMENTS)
            .getPublicKeys();

        SimplePlaintextPublicKeyPair publicKeyPair =
            ProofsTestDataGenerator.getSimplePlaintextPublicKeyPair(
                _zpSubgroup, _parentPublicKey);
        _primaryPublicKey = publicKeyPair.getPrimaryPublicKey();
        _secondaryPublicKey = publicKeyPair.getSecondaryPublicKey();

        List<ZpGroupElement> simplePlaintext = ProofsTestDataGenerator
            .getSimplePlaintext(_zpSubgroup, NUM_PLAINTEXT_ELEMENTS);

        SimplePlaintextCiphertextPair ciphertextPair =
            ProofsTestDataGenerator
                .encryptSimplePlaintext(_parentPublicKey, simplePlaintext);
        _primaryCiphertext = ciphertextPair.getPrimaryCiphertext();
        _secondaryCiphertext = ciphertextPair.getSecondaryCiphertext();
        _witness = ciphertextPair.getWitness();

        _proof = _proofsServiceForDefaultPolicy
            .createProofProverAPI(_zpSubgroup)
            .createSimplePlaintextEqualityProof(_primaryCiphertext,
                _primaryPublicKey, _witness, _secondaryCiphertext,
                _secondaryPublicKey);

        _preComputedValues = _proofsServiceForDefaultPolicy
            .createProofPreComputerAPI(_zpSubgroup)
            .preComputeSimplePlaintextEqualityProof(_primaryPublicKey,
                _secondaryPublicKey);

        _differentZpSubgroup =
            MathematicalTestDataGenerator.getQrSubgroup();

        do {
            _differentPrimaryPublicKey = ElGamalTestDataGenerator
                .getKeyPair(_zpSubgroup, (NUM_PLAINTEXT_ELEMENTS / 2))
                .getPublicKeys();
        } while (_differentPrimaryPublicKey.equals(_primaryPublicKey));
        do {
            _differentSecondaryPublicKey = ElGamalTestDataGenerator
                .getKeyPair(_zpSubgroup, (NUM_PLAINTEXT_ELEMENTS / 2))
                .getPublicKeys();
        } while (_differentSecondaryPublicKey.equals(_secondaryPublicKey));

        List<ZpGroupElement> differentSimplePlaintext;
        do {
            differentSimplePlaintext = ProofsTestDataGenerator
                .getSimplePlaintext(_zpSubgroup, NUM_PLAINTEXT_ELEMENTS);
        } while (differentSimplePlaintext.equals(simplePlaintext));

        ciphertextPair = ProofsTestDataGenerator.encryptSimplePlaintext(
            _parentPublicKey, differentSimplePlaintext);
        _differentPrimaryCiphertext =
            ciphertextPair.getPrimaryCiphertext();
        _differentSecondaryCiphertext =
            ciphertextPair.getSecondaryCiphertext();
    }

    @AfterClass
    public static void tearDown() {

        Security.removeProvider(BouncyCastleProvider.PROVIDER_NAME);
    }

    @Rule
    public ExpectedException thrown = ExpectedException.none();

    @Test
    public final void whenGenerateAndVerifyProofThenOk()
            throws GeneralCryptoLibException {

        Assert.assertTrue(_proofsServiceForDefaultPolicy
            .createProofVerifierAPI(_zpSubgroup)
            .verifySimplePlaintextEqualityProof(_primaryCiphertext,
                _primaryPublicKey, _secondaryCiphertext,
                _secondaryPublicKey, _proof));
    }

    @Test
    public final void whenGenerateProofUsingPreComputedValuesAndVerifyThenOk()
            throws GeneralCryptoLibException {

        Proof proof = _proofsServiceForDefaultPolicy
            .createProofProverAPI(_zpSubgroup)
            .createSimplePlaintextEqualityProof(_primaryCiphertext,
                _primaryPublicKey, _witness, _secondaryCiphertext,
                _secondaryPublicKey, _preComputedValues);

        Assert.assertTrue(_proofsServiceForDefaultPolicy
            .createProofVerifierAPI(_zpSubgroup)
            .verifySimplePlaintextEqualityProof(_primaryCiphertext,
                _primaryPublicKey, _secondaryCiphertext,
                _secondaryPublicKey, proof));
    }

    @Test
    public final void whenSerializeAndDeserializeProofThenOk()
            throws GeneralCryptoLibException {

        Proof deserializedProof = Proof.fromJson(_proof.toJson());

        Assert.assertTrue(_proofsServiceForDefaultPolicy
            .createProofVerifierAPI(_zpSubgroup)
            .verifySimplePlaintextEqualityProof(_primaryCiphertext,
                _primaryPublicKey, _secondaryCiphertext,
                _secondaryPublicKey, deserializedProof));
    }

    @Test
    public final void whenGenerateProofUsingInvalidPreComputedValuesThenVerificationIsFalse()
            throws GeneralCryptoLibException {

        ProofPreComputedValues differentPreComputedValues;
        do {
            differentPreComputedValues = _proofsServiceForDefaultPolicy
                .createProofPreComputerAPI(_zpSubgroup)
                .preComputeSimplePlaintextEqualityProof(
                    _differentPrimaryPublicKey,
                    _differentSecondaryPublicKey);
        } while (differentPreComputedValues.getExponents()
            .equals(_preComputedValues.getExponents()));

        Proof proof = _proofsServiceForDefaultPolicy
            .createProofProverAPI(_zpSubgroup)
            .createSimplePlaintextEqualityProof(_primaryCiphertext,
                _primaryPublicKey, _witness, _secondaryCiphertext,
                _secondaryPublicKey, differentPreComputedValues);

        Assert.assertFalse(_proofsServiceForDefaultPolicy
            .createProofVerifierAPI(_zpSubgroup)
            .verifySimplePlaintextEqualityProof(_primaryCiphertext,
                _primaryPublicKey, _secondaryCiphertext,
                _secondaryPublicKey, proof));
    }

    @Test
    public final void whenGenerateProofUsingInvalidPrimaryCiphertextThenVerificationIsFalse()
            throws GeneralCryptoLibException {

        Proof proof = _proofsServiceForDefaultPolicy
            .createProofProverAPI(_zpSubgroup)
            .createSimplePlaintextEqualityProof(
                _differentPrimaryCiphertext, _primaryPublicKey, _witness,
                _secondaryCiphertext, _secondaryPublicKey);

        Assert.assertFalse(_proofsServiceForDefaultPolicy
            .createProofVerifierAPI(_zpSubgroup)
            .verifySimplePlaintextEqualityProof(
                _differentPrimaryCiphertext, _primaryPublicKey,
                _secondaryCiphertext, _secondaryPublicKey, proof));
    }

    @Test
    public final void whenGenerateProofUsingInvalidPrimaryPublicKeyThenVerificationIsFalse()
            throws GeneralCryptoLibException {

        Proof proof = _proofsServiceForDefaultPolicy
            .createProofProverAPI(_zpSubgroup)
            .createSimplePlaintextEqualityProof(_primaryCiphertext,
                _differentPrimaryPublicKey, _witness, _secondaryCiphertext,
                _secondaryPublicKey);

        Assert.assertFalse(_proofsServiceForDefaultPolicy
            .createProofVerifierAPI(_zpSubgroup)
            .verifySimplePlaintextEqualityProof(_primaryCiphertext,
                _differentPrimaryPublicKey, _secondaryCiphertext,
                _secondaryPublicKey, proof));
    }

    @Test
    public final void whenGenerateProofUsingInvalidSecondaryCiphertextThenVerificationIsFalse()
            throws GeneralCryptoLibException {

        Proof proof = _proofsServiceForDefaultPolicy
            .createProofProverAPI(_zpSubgroup)
            .createSimplePlaintextEqualityProof(_primaryCiphertext,
                _primaryPublicKey, _witness, _differentSecondaryCiphertext,
                _secondaryPublicKey);

        Assert.assertFalse(_proofsServiceForDefaultPolicy
            .createProofVerifierAPI(_zpSubgroup)
            .verifySimplePlaintextEqualityProof(_primaryCiphertext,
                _primaryPublicKey, _differentSecondaryCiphertext,
                _secondaryPublicKey, proof));
    }

    @Test
    public final void whenGenerateProofUsingInvalidSecondaryPublicKeyThenVerificationIsFalse()
            throws GeneralCryptoLibException {

        Proof proof = _proofsServiceForDefaultPolicy
            .createProofProverAPI(_zpSubgroup)
            .createSimplePlaintextEqualityProof(_primaryCiphertext,
                _primaryPublicKey, _witness, _secondaryCiphertext,
                _differentSecondaryPublicKey);

        Assert.assertFalse(_proofsServiceForDefaultPolicy
            .createProofVerifierAPI(_zpSubgroup)
            .verifySimplePlaintextEqualityProof(_primaryCiphertext,
                _primaryPublicKey, _secondaryCiphertext,
                _differentSecondaryPublicKey, proof));
    }

    @Test
    public final void whenGenerateProofUsingInvalidWitnessThenVerificationIsFalse()
            throws GeneralCryptoLibException {

        Witness differentWitness;
        do {
            differentWitness =
                ElGamalTestDataGenerator.getWitness(_zpSubgroup);
        } while (differentWitness.getExponent()
            .equals(_witness.getExponent()));

        Proof proof = _proofsServiceForDefaultPolicy
            .createProofProverAPI(_zpSubgroup)
            .createSimplePlaintextEqualityProof(_primaryCiphertext,
                _primaryPublicKey, differentWitness, _secondaryCiphertext,
                _secondaryPublicKey);

        Assert.assertFalse(_proofsServiceForDefaultPolicy
            .createProofVerifierAPI(_zpSubgroup)
            .verifySimplePlaintextEqualityProof(_primaryCiphertext,
                _primaryPublicKey, _secondaryCiphertext,
                _secondaryPublicKey, proof));
    }

    @Test
    public final void whenGenerateProofUsingNonSimplePlaintextThenVerificationIsFalse()
            throws GeneralCryptoLibException {

        List<ZpGroupElement> nonSimplePlaintext =
            MathematicalTestDataGenerator.getZpGroupElements(_zpSubgroup,
                NUM_PLAINTEXT_ELEMENTS);

        SimplePlaintextCiphertextPair ciphertextPair =
            ProofsTestDataGenerator.encryptSimplePlaintext(
                _parentPublicKey, nonSimplePlaintext);
        Ciphertext primaryCiphertext =
            ciphertextPair.getPrimaryCiphertext();
        Ciphertext secondaryCiphertext =
            ciphertextPair.getSecondaryCiphertext();
        Witness witness = ciphertextPair.getWitness();

        Proof proof = _proofsServiceForDefaultPolicy
            .createProofProverAPI(_zpSubgroup)
            .createSimplePlaintextEqualityProof(primaryCiphertext,
                _primaryPublicKey, witness, secondaryCiphertext,
                _secondaryPublicKey);

        Assert.assertFalse(_proofsServiceForDefaultPolicy
            .createProofVerifierAPI(_zpSubgroup)
            .verifySimplePlaintextEqualityProof(primaryCiphertext,
                _primaryPublicKey, secondaryCiphertext,
                _secondaryPublicKey, proof));
    }

    @Test
    public final void whenVerifyProofUsingInvalidPrimaryCiphertextThenVerificationIsFalse()
            throws GeneralCryptoLibException {

        Assert.assertFalse(_proofsServiceForDefaultPolicy
            .createProofVerifierAPI(_zpSubgroup)
            .verifySimplePlaintextEqualityProof(
                _differentPrimaryCiphertext, _primaryPublicKey,
                _secondaryCiphertext, _secondaryPublicKey, _proof));
    }

    @Test
    public final void whenVerifyProofUsingInvalidPrimaryPublicKeyThenVerificationIsFalse()
            throws GeneralCryptoLibException {

        Assert.assertFalse(_proofsServiceForDefaultPolicy
            .createProofVerifierAPI(_zpSubgroup)
            .verifySimplePlaintextEqualityProof(_primaryCiphertext,
                _differentPrimaryPublicKey, _secondaryCiphertext,
                _secondaryPublicKey, _proof));
    }

    @Test
    public final void whenVerifyProofUsingInvalidSecondaryCiphertextThenVerificationIsFalse()
            throws GeneralCryptoLibException {

        Assert.assertFalse(_proofsServiceForDefaultPolicy
            .createProofVerifierAPI(_zpSubgroup)
            .verifySimplePlaintextEqualityProof(_primaryCiphertext,
                _primaryPublicKey, _differentSecondaryCiphertext,
                _secondaryPublicKey, _proof));
    }

    @Test
    public final void whenVerifyProofUsingInvalidSecondaryPublicKeyThenVerificationIsFalse()
            throws GeneralCryptoLibException {

        Assert.assertFalse(_proofsServiceForDefaultPolicy
            .createProofVerifierAPI(_zpSubgroup)
            .verifySimplePlaintextEqualityProof(_primaryCiphertext,
                _primaryPublicKey, _secondaryCiphertext,
                _differentSecondaryPublicKey, _proof));
    }

    @Test
    public final void whenGenerateProofUsingInvalidMathematicalGroupThenExceptionThrown()
            throws GeneralCryptoLibException {

        thrown.expect(GeneralCryptoLibException.class);
        thrown.expectMessage(
            "The exponent should be of the same Zp subgroup order as this Zp group element");

        _proofsServiceForDefaultPolicy
            .createProofProverAPI(_differentZpSubgroup)
            .createSimplePlaintextEqualityProof(_primaryCiphertext,
                _primaryPublicKey, _witness, _secondaryCiphertext,
                _secondaryPublicKey);
    }

    @Test
    public final void whenVerifyProofUsingInvalidMathematicalGroupThenExceptionThrown()
            throws GeneralCryptoLibException {

        thrown.expect(GeneralCryptoLibException.class);
        thrown.expectMessage(
            "All elements of list of public values must be elements of mathematical group associated with proof.");

        _proofsServiceForDefaultPolicy
            .createProofVerifierAPI(_differentZpSubgroup)
            .verifySimplePlaintextEqualityProof(_primaryCiphertext,
                _primaryPublicKey, _secondaryCiphertext,
                _secondaryPublicKey, _proof);
    }
}
