﻿/*--------------------------------------------------------------------------------*
  Copyright (C)Nintendo All rights reserved.

  These coded instructions, statements, and computer programs contain proprietary
  information of Nintendo and/or its licensed developers and are protected by
  national and international copyright laws. They may not be disclosed to third
  parties or copied or duplicated in any form, in whole or in part, without the
  prior written consent of Nintendo.

  The content herein is highly confidential and should be handled accordingly.
 *--------------------------------------------------------------------------------*/
#include "crypto_EccP256Math.h"
//#include <nn/nn_SdkAssert.h>
//#define assert NN_SDK_ASSERT

namespace nn { namespace crypto0 { namespace detail {

/* the bigint implementation stores the least significant words first */
/*static const bigint_digit p[ECC_P256_BIGINT_DIGITS] =
{
    0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0x00000000,
    0x00000000, 0x00000000, 0x00000001, 0xFFFFFFFF,
};*/

static const bigint_digit p[ECC_P256_BIGINT_DIGITS] =
{
    0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFD,
};

/* parameters for NIST curve on field Fp */
/*
#define SEED_SIZE 5
static bigint_digit seed[SEED_SIZE] =
{
    0x819f7e90, 0x139d26b7, 0x6a6678e1, 0x86e70493, 0xc49d3608,
};

static bigint_digit c[ECC_P256_BIGINT_DIGITS] =
{
    0x0104fa0d, 0xaf317768, 0xc5114abc, 0xce8d84a9,
    0x75d4f7e0, 0x03cb055c, 0x2985be94, 0x7efba166,
};
*/

/*const p256_ec_parameter p256_named_parameter =
{
    {// curve
        {// a4 = 3
            0x00000003, 0x00000000, 0x00000000, 0x00000000,
            0x00000000, 0x00000000, 0x00000000, 0x00000000,
        },
        {// a6 = b
            0x27d2604b, 0x3bce3c3e, 0xcc53b0f6, 0x651d06b0,
            0x769886bc, 0xb3ebbd55, 0xaa3a93e7, 0x5ac635d8,
        },
    },
    {
        {// gx
            0xd898c296, 0xf4a13945, 0x2deb33a0, 0x77037d81,
            0x63a440f2, 0xf8bce6e5, 0xe12c4247, 0x6b17d1f2,
        },
        {// gy
            0x37bf51f5, 0xcbb64068, 0x6b315ece, 0x2bce3357,
            0x7c0f9e16, 0x8ee7eb4a, 0xfe1a7f9b, 0x4fe342e2,
        },
    },
    {// order
        0xFC632551, 0xF3B9CAC2, 0xA7179E84, 0xBCE6FAAD,
        0xFFFFFFFF, 0xFFFFFFFF, 0x00000000, 0xFFFFFFFF,
    },
    {// cofactor
        0x00000001, 0x00000000, 0x00000000, 0x00000000,
        0x00000000, 0x00000000, 0x00000000, 0x00000000,
    },
    {// p
        0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0x00000000,
        0x00000000, 0x00000000, 0x00000001, 0xFFFFFFFF,
    }
};*/

const p256_ec_parameter p256_named_parameter =
{
    {// curve
        {// a4 = 
            0x00000003, 0x00000000, 0x00000000, 0x00000000,
        },
        {// a6 = b
            0x2CEE5ED3, 0xD824993C, 0x1079F43D, 0xE87579C1,
        },
    },
    {
        {// gx
            0xA52C5B86, 0x0C28607C, 0x8B899B2D, 0x161FF752,
        },
        {// gy
            0xDDED7A83, 0xC02DA292, 0x5BAFEB13, 0xCF5AC839,
        },
    },
    {// order
        0x9038A115, 0x75A30D1B, 0x00000000, 0xFFFFFFFE,
    },
    {// cofactor
        0x00000001, 0x00000000, 0x00000000, 0x00000000,
    },
    {// p
        0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFD,
    }
};

/*
  return res = a mod p
*/
static void p256_mod(bigint_digit* r, bigint_digit* a, int a_digits)
{
    bigint_mod(r, a, a_digits, p, ECC_P256_BIGINT_DIGITS);

    /*bigint_digit res[ECC_P256_BIGINT_DIGITS];
    bigint_digit ap[2 * ECC_P256_BIGINT_DIGITS];
    bigint_digit x[ECC_P256_BIGINT_DIGITS];
    assert(a_digits <= 2 * ECC_P256_BIGINT_DIGITS);
    bigint_zero(ap, 2 * ECC_P256_BIGINT_DIGITS);
    bigint_copy(ap, a, a_digits);

    // res = t + 2 s1 + 2 s2 + s3 + s4 - d1 - d2 - d3 - d4 mod p

    // t
    res[0] = ap[0]; res[1] = ap[1]; res[2] = ap[2]; res[3] = ap[3];
    res[4] = ap[4]; res[5] = ap[5]; res[6] = ap[6]; res[7] = ap[7];

    // s1
    x[0] = 0;      x[1] = 0;      x[2] = 0;      x[3] = ap[11];
    x[4] = ap[12]; x[5] = ap[13]; x[6] = ap[14]; x[7] = ap[15];

    bigint_add_mod(res, res, x, p, ECC_P256_BIGINT_DIGITS);
    bigint_add_mod(res, res, x, p, ECC_P256_BIGINT_DIGITS);

    // s2
    x[0] = 0;      x[1] = 0;      x[2] = 0;      x[3] = ap[12];
    x[4] = ap[13]; x[5] = ap[14]; x[6] = ap[15]; x[7] = 0;

    bigint_add_mod(res, res, x, p, ECC_P256_BIGINT_DIGITS);
    bigint_add_mod(res, res, x, p, ECC_P256_BIGINT_DIGITS);

    // s3
    x[0] = ap[8];  x[1] = ap[9];  x[2] = ap[10]; x[3] = 0;
    x[4] = 0;      x[5] = 0;      x[6] = ap[14]; x[7] = ap[15];

    bigint_add_mod(res, res, x, p, ECC_P256_BIGINT_DIGITS);

    // s4
    x[0] = ap[9];  x[1] = ap[10]; x[2] = ap[11]; x[3] = ap[13];
    x[4] = ap[14]; x[5] = ap[15]; x[6] = ap[13]; x[7] = ap[8];

    bigint_add_mod(res, res, x, p, ECC_P256_BIGINT_DIGITS);

    // d1
    x[0] = ap[11]; x[1] = ap[12]; x[2] = ap[13]; x[3] = 0;
    x[4] = 0;      x[5] = 0;      x[6] = ap[8];  x[7] = ap[10];

    bigint_sub_mod(res, res, x, p, ECC_P256_BIGINT_DIGITS);

    // d2
    x[0] = ap[12]; x[1] = ap[13]; x[2] = ap[14]; x[3] = ap[15];
    x[4] = 0;      x[5] = 0;      x[6] = ap[9];  x[7] = ap[11];

    bigint_sub_mod(res, res, x, p, ECC_P256_BIGINT_DIGITS);

    // d3
    x[0] = ap[13]; x[1] = ap[14]; x[2] = ap[15]; x[3] = ap[8];
    x[4] = ap[9];  x[5] = ap[10]; x[6] = 0;      x[7] = ap[12];

    bigint_sub_mod(res, res, x, p, ECC_P256_BIGINT_DIGITS);

    // d4
    x[0] = ap[14]; x[1] = ap[15]; x[2] = 0;      x[3] = ap[9];
    x[4] = ap[10]; x[5] = ap[11]; x[6] = 0;      x[7] = ap[13];

    bigint_sub_mod(res, res, x, p, ECC_P256_BIGINT_DIGITS);

    bigint_copy(r, res, ECC_P256_BIGINT_DIGITS);*/
}

// Addition in elliptic curve. One must verify beforehand that a and b are elements
// of the curve! If a and b are elements of the curve, the result will be an element of
// the curve.
void p256_add(p256_point* c, const p256_point* a, const p256_point* b, const p256_curve* curv)
{
    bigint_digit s[ECC_P256_BIGINT_DIGITS];
    bigint_digit t[2 * ECC_P256_BIGINT_DIGITS];
    bigint_digit x[2 * ECC_P256_BIGINT_DIGITS];
    /*--------------------------------------------------------------------*
       Definition of addition over an elliptic curve
       A (ax, ay) + B (bx, by) = C (cx, cy)

       cx = k^2 - ax - bx
       cy = k * (ax - cx) - a1

       where

       if (A == B) k = (3 * ax * ax - 3) * (2 * ay)^(-1)
       if (A != B) k = (by - ay) * (bx - ax)^(-1)
     *--------------------------------------------------------------------*/

    // point at infinity is the neutral element for the group law
    if (bigint_iszero(a->x, ECC_P256_BIGINT_DIGITS) && bigint_iszero(a->y, ECC_P256_BIGINT_DIGITS))
    {
        bigint_copy(c->x, b->x, ECC_P256_BIGINT_DIGITS);
        bigint_copy(c->y, b->y, ECC_P256_BIGINT_DIGITS);
        return;
    }
    if (bigint_iszero(b->x, ECC_P256_BIGINT_DIGITS) && bigint_iszero(b->y, ECC_P256_BIGINT_DIGITS))
    {
        bigint_copy(c->x, a->x, ECC_P256_BIGINT_DIGITS);
        bigint_copy(c->y, a->y, ECC_P256_BIGINT_DIGITS);
        return;
    }

    if (bigint_cmp(a->x, b->x, ECC_P256_BIGINT_DIGITS) == 0)
    {
        // if a = -b, then a+b=O
        if (bigint_cmp(a->y, b->y, ECC_P256_BIGINT_DIGITS) != 0)
        {
            bigint_zero(c->x, ECC_P256_BIGINT_DIGITS);
            bigint_zero(c->y, ECC_P256_BIGINT_DIGITS);
            return;
        }

        //doubling: prepare x and s such that k = x / s
        // x <- ax ^ 2
        bigint_mult(x, a->x, a->x, ECC_P256_BIGINT_DIGITS);
        p256_mod(x, x, 2 * ECC_P256_BIGINT_DIGITS);

        // s <- 3
        bigint_zero(s, ECC_P256_BIGINT_DIGITS);
        s[0] = 3;

        // x <- 3 * ax ^ 2
        bigint_mult(t, x, s, ECC_P256_BIGINT_DIGITS);
        p256_mod(x, t, 2 * ECC_P256_BIGINT_DIGITS);

        // x <- 3 * ax ^ 2 - a4
        bigint_sub_mod(x, x, curv->a4, p, ECC_P256_BIGINT_DIGITS);

        // s <- 2 * ay
        bigint_add_mod(s, a->y, a->y, p, ECC_P256_BIGINT_DIGITS);
    }
    else
    {
        // x <- by-ay, s <- bx-ax
        bigint_sub_mod(x, b->y, a->y, p, ECC_P256_BIGINT_DIGITS);
        bigint_sub_mod(s, b->x, a->x, p, ECC_P256_BIGINT_DIGITS);
    }

    // s <- k
    bigint_mod_inv(s, s, p, ECC_P256_BIGINT_DIGITS);
    bigint_mult(t, x, s, ECC_P256_BIGINT_DIGITS);
    p256_mod(s, t, 2 * ECC_P256_BIGINT_DIGITS);

    // cx <- k^2 - ax - bx
    bigint_mult(x, s, s, ECC_P256_BIGINT_DIGITS);
    p256_mod(x, x, 2 * ECC_P256_BIGINT_DIGITS);
    bigint_sub_mod(x, x, a->x, p, ECC_P256_BIGINT_DIGITS);
    bigint_sub_mod(x, x, b->x, p, ECC_P256_BIGINT_DIGITS);

    // do a copy of a->x for the case where c = a
    bigint_copy(t, a->x, ECC_P256_BIGINT_DIGITS);
    bigint_copy(c->x, x, ECC_P256_BIGINT_DIGITS);

    // x <- ax - cx
    bigint_sub_mod(x, t, c->x, p, ECC_P256_BIGINT_DIGITS);

    // cy <- (ax - cx)*k - ay
    bigint_mult(t, x, s, ECC_P256_BIGINT_DIGITS);
    p256_mod(t, t, 2 * ECC_P256_BIGINT_DIGITS);
    bigint_sub_mod(c->y, t, a->y, p, ECC_P256_BIGINT_DIGITS);
}

/* res <- n * a, simple version susceptible to timing attacks.
   a and res must not alias. */
void p256_mul(p256_point* res, const bigint_digit* n, int n_digits, const p256_point* a,
              const p256_curve* curv)
{
    static const bigint_digit HIGH_BIT_MASK = 1U << (BIGINT_DIGIT_BITS - 1);

    bigint_digit window = HIGH_BIT_MASK;
    int bits = n_digits * BIGINT_DIGIT_BITS - 1;
    const bigint_digit* cur = n + n_digits - 1;

    if (bigint_iszero(n, n_digits))
    {
        bigint_zero(res->x, ECC_P256_BIGINT_DIGITS);
        bigint_zero(res->y, ECC_P256_BIGINT_DIGITS);
        return;
    }

    bigint_copy(res->x, a->x, ECC_P256_BIGINT_DIGITS);
    bigint_copy(res->y, a->y, ECC_P256_BIGINT_DIGITS);
    assert(p256_validate(res, curv));

    while (*cur == 0)
    {
        bits -= BIGINT_DIGIT_BITS;
        cur--;
    }

    while (!(window & *cur))
    {
        window >>= 1;
        bits--;
    }
    window >>= 1;
    if (window == 0)
    {
        window = HIGH_BIT_MASK;
        cur--;
    }

    while (bits--)
    {
        p256_add(res, res, res, curv);
        assert(p256_validate(res, curv));

        if (*cur & window)
        {
            p256_add(res, res, a, curv);
            assert(p256_validate(res, curv));
        }

        if (bits % BIGINT_DIGIT_BITS == 0)
        {
            cur--;
        }

        window >>= 1;
        if (window == 0)
        {
            window = HIGH_BIT_MASK;
        }
    }
}

int p256_validate(const p256_point* a, const p256_curve* c)
{
    bigint_digit x[2 * ECC_P256_BIGINT_DIGITS];
    bigint_digit t[2 * ECC_P256_BIGINT_DIGITS];
    bigint_digit y[2 * ECC_P256_BIGINT_DIGITS];

    // point at infinity
    if (bigint_iszero(a->x, ECC_P256_BIGINT_DIGITS) &&
        bigint_iszero(a->y, ECC_P256_BIGINT_DIGITS))
    {
        return 1;
    }

    // x <- ax^3
    bigint_mult(t, a->x, a->x, ECC_P256_BIGINT_DIGITS);
    p256_mod(t, t, 2 * ECC_P256_BIGINT_DIGITS);
    bigint_mult(x, t, a->x, ECC_P256_BIGINT_DIGITS);
    p256_mod(x, x, 2 * ECC_P256_BIGINT_DIGITS);

    // t <- a4 * ax
    bigint_mult(t, c->a4, a->x, ECC_P256_BIGINT_DIGITS);
    p256_mod(t, t, 2 * ECC_P256_BIGINT_DIGITS);

    // x <- ax^3 - a4 * ax + a6
    bigint_sub_mod(x, x, t, p, ECC_P256_BIGINT_DIGITS);
    bigint_add_mod(x, x, c->a6, p, ECC_P256_BIGINT_DIGITS);

    // y <- ay^2
    bigint_mult(y, a->y, a->y, ECC_P256_BIGINT_DIGITS);
    p256_mod(y, y, 2 * ECC_P256_BIGINT_DIGITS);

    return (bigint_cmp(x, y, ECC_P256_BIGINT_DIGITS) == 0);
}

void p256_function(const bigint_digit* a_x, const p256_curve* c, bigint_digit* res)
{
    bigint_digit x[2 * ECC_P256_BIGINT_DIGITS];
    bigint_digit t[2 * ECC_P256_BIGINT_DIGITS], t2[2 * ECC_P256_BIGINT_DIGITS];
    bigint_digit y[2 * ECC_P256_BIGINT_DIGITS];
    
    // x <- ax^3
    bigint_mult(t, a_x, a_x, ECC_P256_BIGINT_DIGITS);
    p256_mod(t, t, 2 * ECC_P256_BIGINT_DIGITS);
    bigint_mult(x, t, a_x, ECC_P256_BIGINT_DIGITS);
    p256_mod(x, x, 2 * ECC_P256_BIGINT_DIGITS);

    // t <- a4 * ax
    bigint_mult(t, c->a4, a_x, ECC_P256_BIGINT_DIGITS);
    p256_mod(t, t, 2 * ECC_P256_BIGINT_DIGITS);

    // x <- ax^3 - a4 * ax + a6
    bigint_sub_mod(x, x, t, p, ECC_P256_BIGINT_DIGITS);
    bigint_add_mod(x, x, c->a6, p, ECC_P256_BIGINT_DIGITS);

    // Square root when p mod 4 = 3
    // y <- y2^((p + 1) / 4)
    bigint_digit one[ECC_P256_BIGINT_DIGITS] = {
        1, 0, 0, 0,
    };

    bigint_digit four[ECC_P256_BIGINT_DIGITS] = {
        4, 0, 0, 0,
    };

    bigint_add(t, p, one, ECC_P256_BIGINT_DIGITS);
    bigint_div(t, t2, t, ECC_P256_BIGINT_DIGITS, four, ECC_P256_BIGINT_DIGITS);
    bigint_mod(t, t, ECC_P256_BIGINT_DIGITS, p, ECC_P256_BIGINT_DIGITS);
    bigint_mod_exp(y, x, t, ECC_P256_BIGINT_DIGITS, p, ECC_P256_BIGINT_DIGITS);

    // y = min(y',p-y')
    bigint_digit pMinusY[ECC_P256_BIGINT_DIGITS];
    bigint_sub_mod(pMinusY, p, y, p, ECC_P256_BIGINT_DIGITS);

    bigint_min(res, y, pMinusY, ECC_P256_BIGINT_DIGITS);
}

/*************** TEST *********************/

/*
static void test_mod(bigint_digit* t, int digits)
{
    bigint_digit res1[ECC_P256_BIGINT_DIGITS];
    bigint_digit res2[ECC_P256_BIGINT_DIGITS];

    p256_mod(res1, t, digits);
    bigint_mod(res2, t, digits, p, ECC_P256_BIGINT_DIGITS);
    if (bigint_cmp(res1, res2, ECC_P256_BIGINT_DIGITS) == 0)
    {
        printf ("MOD -> PASS\n");
    }
    else
    {
        printf ("MOD -> FAIL\n");
    }
}

static void bigint_test_random(bigint_digit *r, int digits)
{
    int i;
    for (i = 0; i < digits; i++)
        r[i] = rand();
}

void test_ecc_p256_mod()
{
    //test 0 and p^2 - 1
    int i;
    bigint_digit x[2 * ECC_P256_BIGINT_DIGITS] = {0};
    bigint_digit one[2 * ECC_P256_BIGINT_DIGITS] = {1};
    bigint_digit random[2 * ECC_P256_BIGINT_DIGITS] = {0};
    test_mod(x, 16);
    test_mod(x, 3);

    bigint_mult(x, p, p, ECC_P256_BIGINT_DIGITS);
    bigint_sub(x, x, one, 2 * ECC_P256_BIGINT_DIGITS);
    test_mod(x, 2 * ECC_P256_BIGINT_DIGITS);

    for (i = 0; i < 100; i++)
    {
        // test random modulos
        bigint_test_random(random, 2 * ECC_P256_BIGINT_DIGITS);
        bigint_mod(random, random, 2 * ECC_P256_BIGINT_DIGITS, x, 2 * ECC_P256_BIGINT_DIGITS);
        test_mod(random, 2 * ECC_P256_BIGINT_DIGITS);
    }
}

static void test_validate(p256_point* p)
{
    if (p256_validate(p, &(p256_named_parameter.par_curve)))
    {
        printf("VALIDATE -> PASS\n");
    }
    else
    {
        printf("VALIDATE -> FAIL\n");
    }
}

void test_ecc_p256_points_in_curve()
{
    p256_point temp;
    bigint_digit r;
    int i;

    test_validate(&(p256_named_parameter.par_point));

    for (i = 0; i < 5; i++)
    {
        r = rand();
        p256_mul(&temp, &r, 1, &(p256_named_parameter.par_point), &(p256_named_parameter.par_curve));
        test_validate(&temp);
    }
}

void print_point(p256_point *p)
{
    int i;
    printf("x -> ");
    for (i = ECC_P256_BIGINT_DIGITS - 1; i >= 0; i--)
        printf("%x ", p->x[i]);
    printf("\ny -> ");
    for (i = ECC_P256_BIGINT_DIGITS - 1; i >= 0; i--)
        printf("%x ", p->y[i]);
    printf("\n");
}

void test_eq(const char *s, p256_point *p1, p256_point *p2)
{
    if (bigint_cmp(p1->x, p2->x, ECC_P256_BIGINT_DIGITS) == 0 &&
        bigint_cmp(p1->y, p2->y, ECC_P256_BIGINT_DIGITS) == 0)
    {
        printf("%s -> PASS\n", s);
    }
    else
    {
        printf("%s -> FAIL\n", s);
        print_point(p1);
        print_point(p2);
    }
}

void test_group()
{
    p256_point temp;
    p256_point temp2;
    bigint_digit zero = 0;
    bigint_digit one = 1;
    bigint_digit two = 2;
    bigint_digit fortytwo = 42;
    bigint_digit i;

    bigint_zero(temp2.x, ECC_P256_BIGINT_DIGITS);
    bigint_zero(temp2.y, ECC_P256_BIGINT_DIGITS);

    p256_mul(&temp, &zero, 1, &(p256_named_parameter.par_point), &(p256_named_parameter.par_curve));
    test_eq("MUL0", &temp, &temp2);

    p256_mul(&temp, &one, 1, &(p256_named_parameter.par_point), &(p256_named_parameter.par_curve));
    test_eq("MUL1", &temp, &(p256_named_parameter.par_point));

    p256_mul(&temp, &two, 1, &(p256_named_parameter.par_point), &(p256_named_parameter.par_curve));
    p256_add(&temp2, &(p256_named_parameter.par_point), &(p256_named_parameter.par_point), &(p256_named_parameter.par_curve));
    test_eq("MUL2", &temp, &temp2);

    p256_mul(&temp, &fortytwo, 1, &(p256_named_parameter.par_point), &(p256_named_parameter.par_curve));
    bigint_zero(temp2.x, ECC_P256_BIGINT_DIGITS);
    bigint_zero(temp2.y, ECC_P256_BIGINT_DIGITS);
    for (i = 0; i < fortytwo; ++i)
    {
        p256_add(&temp2, &temp2, &(p256_named_parameter.par_point), &(p256_named_parameter.par_curve));
    }
    test_eq("MUL42", &temp, &temp2);

    p256_mul(&temp, p256_named_parameter.point_order, ECC_P256_BIGINT_DIGITS, &(p256_named_parameter.par_point), &(p256_named_parameter.par_curve));

    bigint_zero(temp2.x, ECC_P256_BIGINT_DIGITS);
    bigint_zero(temp2.y, ECC_P256_BIGINT_DIGITS);

    test_eq("GROUP", &temp, &temp2);
}
*/

}}} // namespace nn::crypto0::detail
