From 32da4c7d5044381dd468dcd2c40a6c7ebd4232c6 Mon Sep 17 00:00:00 2001 From: Isis Lovecruft Date: Fri, 6 Jan 2017 17:08:37 +0000 Subject: [PATCH] Implement Neg for Scalar. --- src/constants.rs | 15 +++++++++++++++ src/scalar.rs | 20 ++++++++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/src/constants.rs b/src/constants.rs index 0b927d3..71417d8 100644 --- a/src/constants.rs +++ b/src/constants.rs @@ -21,6 +21,7 @@ use field::FieldElement; use curve::PreComputedPoint; use curve::CompressedEdwardsY; +use scalar::Scalar; pub const d: FieldElement = FieldElement([ -10913610, 13857413, -15372611, 6949391, 114729, @@ -66,6 +67,20 @@ pub const BASE_CMPRSSD: CompressedEdwardsY = 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66]); +/// `l` is the order of base point, i.e. 2^252 + +/// 27742317777372353535851937790883648493, in little-endian form +pub const l: Scalar = Scalar([ 0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, + 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10 ]); + +/// `lminus1` is the order of base point minus one, i.e. 2^252 + +/// 27742317777372353535851937790883648493 - 1, in little-endian form +pub const lminus1: Scalar = Scalar([ 0xec, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, + 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10 ]); + pub const bi: [PreComputedPoint; 8] = [ PreComputedPoint{ y_plus_x: FieldElement([25967493, -14356035, 29566456, 3660896, -12694345, 4014787, 27544626, -11754271, -6079156, 2047605]), diff --git a/src/scalar.rs b/src/scalar.rs index 17a4117..565d740 100644 --- a/src/scalar.rs +++ b/src/scalar.rs @@ -30,11 +30,13 @@ //! limbs. use core::ops::{Index, IndexMut}; +use core::ops::{Neg}; #[cfg(feature = "std")] use rand::Rng; // XXX should these be in a utility module ? +use constants; use field::{load3, load4}; use util::CTAssignable; @@ -62,6 +64,15 @@ impl IndexMut for Scalar { } } +impl Neg for Scalar { + type Output = Scalar; + + /// Negate this scalar by computing (l - 1) * self - 0 (mod l). + fn neg(self) -> Scalar { + Scalar::multiply_add(&constants::lminus1, &self, &Scalar::zero()) + } +} + impl CTAssignable for Scalar { /// Conditionally assign another Scalar to this one. /// @@ -627,4 +638,13 @@ mod test { assert!(test_red[i] == reduced[i]); } } + + // Negating a scalar twice should result in the original scalar. + #[test] + fn test_scalar_neg() { + let negative_x: Scalar = -X; + let orig: Scalar = -negative_x; + + assert!(orig == X); + } }