diff --git a/src/scalar.rs b/src/scalar.rs index c5f3734..33bf764 100644 --- a/src/scalar.rs +++ b/src/scalar.rs @@ -40,6 +40,7 @@ use rand::Rng; use constants; use field::{load3, load4}; use util::CTAssignable; +use util::CTEq; use util::arrays_equal_ct; /// The `Scalar` struct represents an element in ℤ/lℤ, where @@ -50,18 +51,22 @@ use util::arrays_equal_ct; #[derive(Copy, Clone)] pub struct Scalar(pub [u8; 32]); -// XXX make CTEq traits impl Eq for Scalar{} impl PartialEq for Scalar { - /// Test equality between two `Scalar`s in constant time. + /// Test equality between two `Scalar`s. /// - /// Returns + /// # Warning + /// + /// This function is *not* guaranteed to be constant time and should only be + /// used for debugging purposes. + /// + /// # Returns /// /// True if they are equal, and false otherwise. fn eq(&self, other: &Self) -> bool { let equal: u8 = arrays_equal_ct(&self.0, &other.0); - if equal == 1 { + if equal == 1u8 { return true; } else { return false; @@ -69,6 +74,17 @@ impl PartialEq for Scalar { } } +impl CTEq for Scalar { + /// Test equality between two `Scalar`s in constant time. + /// + /// # Returns + /// + /// `1u8` if they are equal, and `0u8` otherwise. + fn ct_eq(&self, other: &Self) -> u8 { + arrays_equal_ct(&self.0, &other.0) + } +} + impl Index for Scalar { type Output = u8; diff --git a/src/util.rs b/src/util.rs index b0ab17d..a3db551 100644 --- a/src/util.rs +++ b/src/util.rs @@ -21,7 +21,17 @@ pub trait CTAssignable { fn conditional_assign(&mut self, other: &Self, choice: u8); } -/// Trait for items which can be conditionally negated in constant time. +/// Trait for items whose equality to another item may be tested in constant time. +pub trait CTEq { + /// Determine if two items are equal in constant time. + /// + /// # Returns + /// + /// `1u8` if the two items are equal, and `0u8` otherwise. + fn ct_eq(&self, other: &Self) -> u8; +} + +// Trait for items which can be conditionally negated in constant time. /// /// Note: it is not necessary to implement this trait, as a generic /// implementation is provided.