#include "ecqv_Ca.h"
#include "ecqv_Hash.h"
#include "../crypto_ec/crypto_EccP256Algorithms.h"
#include "../crypto_ec/crypto_Sha256Generator.h"
#include "ecqv_Key_Pair.h"

#include <iostream>

namespace ECQV
{
CertificateAuthority::CertificateAuthority(Random&            randomGenerator,
                                             p256_ec_parameter* pEcParams,
                                             bool               isUsePointCompression)
    : m_pEcParams(pEcParams)
    , m_Random(randomGenerator)
    , m_isUsePointCompression(isUsePointCompression)
{
    NERD_ASSERT(pEcParams != NULL);

    // Setup ec curve domain parameters
    // p parameter is implicit and not part of p256_ec_parameter
    // it is hard coded in crypto_EccP256Math.cpp
    m_pEcParams = pEcParams;

    // Generate a public/private key pair for the CA
    KeyPair::GenerateKeyPair(m_Random, m_pEcParams, m_PrivateKey, &m_PublicKey);

    // Generate a delta key pair for
    // https://tools.ietf.org/html/draft-jivsov-ecc-compact-05
    // 4.2.3.  The key generation algorithm for the sum of points
    KeyPair::GenerateKeyPair(m_Random, m_pEcParams, m_d, &m_D);
}

void CertificateAuthority::GenerateCertificate(p256_point*   pRu,
                                                bigint_digit* pOutR,
                                                p256_point*   pOutCert)
{
    // Generate a new EC key pair
    bigint_digit k[ECC_P256_BIGINT_DIGITS];
    p256_point   kG;
    KeyPair::GenerateKeyPair(m_Random, m_pEcParams, k, &kG);

    // Pu = Ru + kG (or gamma = alpha*G + kG)
    p256_point Pu;
    p256_add(&Pu, pRu, &kG, &m_pEcParams->par_curve);
    NERD_ASSERT(p256_validate(&Pu, &m_pEcParams->par_curve));

    // Fix Pu so it is compliant with y = min(y, p-y)
    // https://tools.ietf.org/html/draft-jivsov-ecc-compact-05
    // 4.2.3.  The key generation algorithm for the sum of points
    if (m_isUsePointCompression)
    {
        bigint_digit pMinusY[ECC_P256_BIGINT_DIGITS];
        bigint_digit minimum[ECC_P256_BIGINT_DIGITS];
        bigint_sub_mod(pMinusY, m_pEcParams->p, Pu.y, m_pEcParams->p, ECC_P256_BIGINT_DIGITS);
        bigint_min(minimum, Pu.y, pMinusY, ECC_P256_BIGINT_DIGITS);

        while (bigint_cmp(Pu.y, minimum, ECC_P256_BIGINT_DIGITS) != 0)
        {
            p256_add(&Pu, &Pu, &m_D, &m_pEcParams->par_curve);
            NERD_ASSERT(p256_validate(&Pu, &m_pEcParams->par_curve));

            bigint_add_mod(k, k, m_d, m_pEcParams->point_order, ECC_P256_BIGINT_DIGITS);

            bigint_sub_mod(pMinusY, m_pEcParams->p, Pu.y, m_pEcParams->p, ECC_P256_BIGINT_DIGITS);
            bigint_min(minimum, Pu.y, pMinusY, ECC_P256_BIGINT_DIGITS);
        }
    }

    // Compute CertU and its integer hash e (we skip the encoding part which uses IDa)
    bigint_digit e[ECC_P256_BIGINT_DIGITS];
    Hash::PointToIntegerHash(&Pu, e, m_pEcParams->point_order);

    // Check t is not the identity element
    // t = ePu + Qca
    p256_point t;
    p256_point ePu;
    p256_mul(&ePu, e, ECC_P256_BIGINT_DIGITS, &Pu, &m_pEcParams->par_curve);
    p256_add(&t, &ePu, &m_PublicKey, &m_pEcParams->par_curve);

    // TODO: go back to GenKeyPair(k, &kG) if t is the identity element
    NERD_ASSERT(!(bigint_iszero(t.x, ECC_P256_BIGINT_DIGITS) &&
                  bigint_iszero(t.y, ECC_P256_BIGINT_DIGITS)));

    // Compute private key reconstruction data "r"
    // r = ek + dca (mod n), (a = e*alpha + s)
    bigint_digit r[ECC_P256_BIGINT_DIGITS];
    bigint_digit ek[ECC_P256_BIGINT_DIGITS];
    bigint_mod_mult(ek, e, k, m_pEcParams->point_order, ECC_P256_BIGINT_DIGITS);
    bigint_add_mod(r, ek, m_PrivateKey, m_pEcParams->point_order, ECC_P256_BIGINT_DIGITS);

    // Output results
    bigint_copy(pOutR, r, ECC_P256_BIGINT_DIGITS);
    bigint_copy(pOutCert->x, Pu.x, ECC_P256_BIGINT_DIGITS);

    if (m_isUsePointCompression)
        bigint_zero(pOutCert->y, ECC_P256_BIGINT_DIGITS);
    else
        bigint_copy(pOutCert->y, Pu.y, ECC_P256_BIGINT_DIGITS);
}
};
