#include "ecqv_Client.h"
#include "ecqv_Hash.h"
#include "ecqv_Key_Pair.h"

namespace ECQV
{
Client::Client(Random& randomGenerator, p256_ec_parameter* pEcParams, bool isUsePointCompression)
    : m_Random(randomGenerator)
    , m_pEcParams(pEcParams)
    , m_isPublicKeyValid(false)
    , m_isUsePointCompression(isUsePointCompression)
{
    NERD_ASSERT(m_pEcParams != NULL);
}

void Client::RequestCertificate() { KeyPair::GenerateKeyPair(m_Random, m_pEcParams, m_ku, &m_Ru); }

void Client::ExtractPublickey(p256_point* pCaPublicKey,
                              p256_point* pCert,
                              p256_point* pOutClientPublicKey)
{
    if (m_isUsePointCompression)
    {
        p256_function(pCert->x, &m_pEcParams->par_curve, pCert->y);
        NERD_ASSERT(p256_validate(pCert, &m_pEcParams->par_curve));
    }

    // compute e = Hn(CertU)
    bigint_digit e[ECC_P256_BIGINT_DIGITS];
    Hash::PointToIntegerHash(pCert, e, m_pEcParams->point_order);

    // Qu = ePu + Qca
    p256_point ePu;
    p256_mul(&ePu, e, ECC_P256_BIGINT_DIGITS, pCert, &m_pEcParams->par_curve);
    NERD_ASSERT(p256_validate(&ePu, &m_pEcParams->par_curve));

    p256_add(pOutClientPublicKey, &ePu, pCaPublicKey, &m_pEcParams->par_curve);
    NERD_ASSERT(p256_validate(pOutClientPublicKey, &m_pEcParams->par_curve));
}

bool Client::ReceiveCertificate(p256_point* pCaPublicKey, bigint_digit* pR, p256_point* pCert)
{
    ExtractPublickey(pCaPublicKey, pCert, &m_PublicKey);

    bigint_digit e[ECC_P256_BIGINT_DIGITS];
    Hash::PointToIntegerHash(pCert, e, m_pEcParams->point_order);

    // Compute the private key dU = r + ekU (mod n)
    bigint_digit dU[ECC_P256_BIGINT_DIGITS];
    bigint_digit eKu[ECC_P256_BIGINT_DIGITS];

    bigint_mod_mult(eKu, e, m_ku, m_pEcParams->point_order, ECC_P256_BIGINT_DIGITS);
    bigint_add_mod(dU, eKu, pR, m_pEcParams->point_order, ECC_P256_BIGINT_DIGITS);
    bigint_copy(m_PrivateKey, dU, ECC_P256_BIGINT_DIGITS);

    // Compute Qu = du*G
    p256_point Qu;
    p256_mul(&Qu, dU, ECC_P256_BIGINT_DIGITS, &m_pEcParams->par_point, &m_pEcParams->par_curve);
    NERD_ASSERT(p256_validate(&Qu, &m_pEcParams->par_curve));

    // Validate that Qu == m_publicKey
    if (bigint_cmp(Qu.x, m_PublicKey.x, ECC_P256_BIGINT_DIGITS) == 0 &&
        bigint_cmp(Qu.y, m_PublicKey.y, ECC_P256_BIGINT_DIGITS) == 0)
    {
        m_isPublicKeyValid = true;
        return true;
    }
    else
    {
        NERD_ASSERT_NOT_REACHED();
        m_isPublicKeyValid = false;
        return false;
    }
}
}
