Skip to content

Commit

Permalink
feat: RistrettoSecretKey inversion (#173)
Browse files Browse the repository at this point in the history
Adds multiplicative inversion to `RistrettoSecretKey`. Adds a few unit
tests.

Note that the underlying `invert` functionality from `curve25519-dalek`
does not assert that the `Scalar` in question is nonzero, but requires
the caller to check this; inverting zero is undefined. This PR
specifically checks this, and as a result, the inversion returns an
`Option`. This is probably annoying for the caller, but might stop bad
things from happening.
  • Loading branch information
AaronFeickert committed Apr 5, 2023
1 parent f6450fc commit 9b990a3
Showing 1 changed file with 33 additions and 0 deletions.
33 changes: 33 additions & 0 deletions src/ristretto/ristretto_keys.rs
Expand Up @@ -138,6 +138,16 @@ impl RistrettoSecretKey {
pub fn reveal(&self) -> RevealedSecretKey<'_> {
RevealedSecretKey { secret: self }
}

/// Get the multiplicative inverse of a nonzero secret key
/// If zero is passed, returns `None`; annoying, but a useful guardrail
pub fn invert(&self) -> Option<Self> {
if self.0 == Scalar::zero() {
None
} else {
Some(RistrettoSecretKey(self.0.invert()))
}
}
}

impl<'a> fmt::Display for RevealedSecretKey<'a> {
Expand Down Expand Up @@ -991,6 +1001,29 @@ mod test {
assert_eq!(p.compressed.get().unwrap().as_bytes(), &zeros); // check directly for good measure
}

#[test]
fn test_inverse() {
// 0^{-1} is undefined
assert!(RistrettoSecretKey::from(0u64).invert().is_none());

// 1^{-1} == 1
assert_eq!(
RistrettoSecretKey::from(1u64).invert(),
Some(RistrettoSecretKey::from(1u64))
);

// 2^{-1}*2 == 1
assert!(RistrettoSecretKey::from(2u64).invert().is_some());
assert_ne!(
RistrettoSecretKey::from(2u64).invert(),
Some(RistrettoSecretKey::from(2u64))
);
assert_eq!(
RistrettoSecretKey::from(2u64).invert().unwrap() * RistrettoSecretKey::from(2u64),
RistrettoSecretKey::from(1u64)
);
}

#[cfg(feature = "borsh")]
mod borsh {
use borsh::{BorshDeserialize, BorshSerialize};
Expand Down

0 comments on commit 9b990a3

Please sign in to comment.