use super::Scalar;
use crate::{CurveArithmetic, ops::Invert};
use common::Generate;
use core::fmt;
use rand_core::{CryptoRng, TryCryptoRng};
use subtle::CtOption;
use zeroize::Zeroize;
#[cfg(feature = "getrandom")]
use common::getrandom::{self, SysRng, rand_core::UnwrapErr};
#[derive(Clone)]
pub struct BlindedScalar<C>
where
C: CurveArithmetic,
{
scalar: Scalar<C>,
mask: Scalar<C>,
}
impl<C: CurveArithmetic> fmt::Debug for BlindedScalar<C> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("BlindedScalar").finish_non_exhaustive()
}
}
impl<C> BlindedScalar<C>
where
C: CurveArithmetic,
{
#[cfg(feature = "getrandom")]
pub fn new(scalar: Scalar<C>) -> Self {
Self::new_from_rng(scalar, &mut UnwrapErr(SysRng))
}
#[cfg(feature = "getrandom")]
pub fn try_new(scalar: Scalar<C>) -> Result<Self, getrandom::Error> {
Self::try_new_from_rng(scalar, &mut SysRng)
}
pub fn new_from_rng<R: CryptoRng + ?Sized>(scalar: Scalar<C>, rng: &mut R) -> Self {
let Ok(ret) = Self::try_new_from_rng(scalar, rng);
ret
}
pub fn try_new_from_rng<R>(scalar: Scalar<C>, rng: &mut R) -> Result<Self, R::Error>
where
R: TryCryptoRng + ?Sized,
{
let mask = Scalar::<C>::try_generate_from_rng(rng)?;
Ok(Self { scalar, mask })
}
}
impl<C> AsRef<Scalar<C>> for BlindedScalar<C>
where
C: CurveArithmetic,
{
fn as_ref(&self) -> &Scalar<C> {
&self.scalar
}
}
impl<C> Invert for BlindedScalar<C>
where
C: CurveArithmetic,
{
type Output = CtOption<Scalar<C>>;
fn invert(&self) -> CtOption<Scalar<C>> {
(self.scalar * self.mask)
.invert_vartime()
.map(|s| s * self.mask)
}
}
impl<C> Drop for BlindedScalar<C>
where
C: CurveArithmetic,
{
fn drop(&mut self) {
self.scalar.zeroize();
self.mask.zeroize();
}
}