From acb69c40cbde0d1bfcee07bf698883202f656b45 Mon Sep 17 00:00:00 2001 From: Tony Arcieri Date: Sat, 18 Jan 2025 15:26:10 -0700 Subject: [PATCH] Modular inversion cleanups (#740) DRYs out some safegcd init by extracting a `const fn` --- src/modular/boxed_monty_form/inv.rs | 6 ++---- src/modular/monty_form/inv.rs | 26 ++++++++++++++++---------- 2 files changed, 18 insertions(+), 14 deletions(-) diff --git a/src/modular/boxed_monty_form/inv.rs b/src/modular/boxed_monty_form/inv.rs index db433056..16536b29 100644 --- a/src/modular/boxed_monty_form/inv.rs +++ b/src/modular/boxed_monty_form/inv.rs @@ -13,8 +13,7 @@ impl BoxedMontyForm { /// Computes `self^-1` representing the multiplicative inverse of `self`, /// i.e. `self * self^-1 = 1`. pub fn invert(&self) -> CtOption { - let inverter = self.params.precompute_inverter(); - inverter.invert(self) + self.params.precompute_inverter().invert(self) } /// Computes `self^-1` representing the multiplicative inverse of `self`, @@ -23,8 +22,7 @@ impl BoxedMontyForm { /// This version is variable-time with respect to the value of `self`, but constant-time with /// respect to `self`'s `params`. pub fn invert_vartime(&self) -> CtOption { - let inverter = self.params.precompute_inverter(); - inverter.invert_vartime(self) + self.params.precompute_inverter().invert_vartime(self) } } diff --git a/src/modular/monty_form/inv.rs b/src/modular/monty_form/inv.rs index 02df3753..96afc18d 100644 --- a/src/modular/monty_form/inv.rs +++ b/src/modular/monty_form/inv.rs @@ -21,11 +21,7 @@ where /// If the number was invertible, the second element of the tuple is the truthy value, /// otherwise it is the falsy value (in which case the first element's value is unspecified). pub const fn inv(&self) -> ConstCtOption { - let inverter = > as PrecomputeInverter>::Inverter::new( - &self.params.modulus, - &self.params.r2, - ); - + let inverter = self.params.inverter(); let maybe_inverse = inverter.inv(&self.montgomery_form); let (inverse, inverse_is_some) = maybe_inverse.components_ref(); @@ -46,11 +42,7 @@ where /// This version is variable-time with respect to the value of `self`, but constant-time with /// respect to `self`'s `params`. pub const fn inv_vartime(&self) -> ConstCtOption { - let inverter = > as PrecomputeInverter>::Inverter::new( - &self.params.modulus, - &self.params.r2, - ); - + let inverter = self.params.inverter(); let maybe_inverse = inverter.inv_vartime(&self.montgomery_form); let (inverse, inverse_is_some) = maybe_inverse.components_ref(); @@ -81,6 +73,20 @@ where } } +impl MontyParams +where + Odd>: PrecomputeInverter< + Inverter = SafeGcdInverter, + Output = Uint, + >, +{ + /// Create a modular inverter for the modulus of these params. + // TODO(tarcieri): make `pub`? + const fn inverter(&self) -> SafeGcdInverter { + SafeGcdInverter::new(&self.modulus, &self.r2) + } +} + impl PrecomputeInverter for MontyParams where Odd>: