/* Edwards curve operations
 * Daniel Beer <dlbeer@gmail.com>, 9 Jan 2014
 *
 * This file is in the public domain.
 */

#ifndef ED25519_H_
#define ED25519_H_

#include "f25519.h"

/* This is not the Ed25519 signature system. Rather, we're implementing
 * basic operations on the twisted Edwards curve over (Z mod 2^255-19):
 *
 *     -x^2 + y^2 = 1 - (121665/121666)x^2y^2
 *
 * With the positive-x base point y = 4/5.
 *
 * These functions will not leak secret data through timing.
 *
 * For more information, see:
 *
 *     Bernstein, D.J. & Lange, T. (2007) "Faster addition and doubling on
 *     elliptic curves". Document ID: 95616567a6ba20f575c5f25e7cebaf83.
 *
 *     Hisil, H. & Wong, K K. & Carter, G. & Dawson, E. (2008) "Twisted
 *     Edwards curves revisited". Advances in Cryptology, ASIACRYPT 2008,
 *     Vol. 5350, pp. 326-343.
 */

/* Projective coordinates */
struct ed25519_pt {
	uint8_t		x[F25519_SIZE];
	uint8_t		y[F25519_SIZE];
	uint8_t		t[F25519_SIZE];
	uint8_t		z[F25519_SIZE];
};

extern const struct ed25519_pt ed25519_base;

/* Convert between projective and affine coordinates (x/y in F25519) */
void ed25519_project(struct ed25519_pt *p,
		     const uint8_t *x, const uint8_t *y);

void ed25519_unproject(uint8_t *x, uint8_t *y,
		       const struct ed25519_pt *p);

/* Compress/uncompress points. try_unpack() will check that the
 * compressed point is on the curve, returning 1 if the unpacked point
 * is valid, and 0 otherwise.
 */
#define ED25519_PACK_SIZE	F25519_SIZE

void ed25519_pack(uint8_t *c, const uint8_t *x, const uint8_t *y);
uint8_t ed25519_try_unpack(uint8_t *x, uint8_t *y, const uint8_t *c);

/* Add, double and scalar multiply */
#define ED25519_EXPONENT_SIZE	32

/* Prepare an exponent by clamping appropriate bits */
static inline void ed25519_prepare(uint8_t *e)
{
	e[0] &= 0xf8;
	e[31] &= 0x7f;
	e[31] |= 0x40;
}

/* Order of the group generated by the base point */
static inline void ed25519_copy(struct ed25519_pt *dst,
				const struct ed25519_pt *src)
{
	memcpy(dst, src, sizeof(*dst));
}

void ed25519_add(struct ed25519_pt *r,
		 const struct ed25519_pt *a, const struct ed25519_pt *b);
void ed25519_smult(struct ed25519_pt *r, const struct ed25519_pt *a,
		   const uint8_t *e);

#endif
