From 10ee2acdd26a7f1298c6f6d6b7af9b469fe29b87 Mon Sep 17 00:00:00 2001 From: Daniel Baumann Date: Sat, 4 May 2024 14:41:41 +0200 Subject: Merging upstream version 1.70.0+dfsg2. Signed-off-by: Daniel Baumann --- vendor/crypto-bigint/src/uint/add.rs | 189 ++++++++++ vendor/crypto-bigint/src/uint/add_mod.rs | 139 ++++++++ vendor/crypto-bigint/src/uint/array.rs | 189 ++++++++++ vendor/crypto-bigint/src/uint/bit_and.rs | 145 ++++++++ vendor/crypto-bigint/src/uint/bit_not.rs | 48 +++ vendor/crypto-bigint/src/uint/bit_or.rs | 141 ++++++++ vendor/crypto-bigint/src/uint/bit_xor.rs | 141 ++++++++ vendor/crypto-bigint/src/uint/bits.rs | 55 +++ vendor/crypto-bigint/src/uint/cmp.rs | 196 ++++++++++ vendor/crypto-bigint/src/uint/concat.rs | 60 ++++ vendor/crypto-bigint/src/uint/div.rs | 496 ++++++++++++++++++++++++++ vendor/crypto-bigint/src/uint/encoding.rs | 278 +++++++++++++++ vendor/crypto-bigint/src/uint/encoding/der.rs | 69 ++++ vendor/crypto-bigint/src/uint/encoding/rlp.rs | 79 ++++ vendor/crypto-bigint/src/uint/from.rs | 238 ++++++++++++ vendor/crypto-bigint/src/uint/inv_mod.rs | 62 ++++ vendor/crypto-bigint/src/uint/mul.rs | 246 +++++++++++++ vendor/crypto-bigint/src/uint/mul_mod.rs | 131 +++++++ vendor/crypto-bigint/src/uint/neg_mod.rs | 68 ++++ vendor/crypto-bigint/src/uint/rand.rs | 92 +++++ vendor/crypto-bigint/src/uint/resize.rs | 37 ++ vendor/crypto-bigint/src/uint/shl.rs | 134 +++++++ vendor/crypto-bigint/src/uint/shr.rs | 93 +++++ vendor/crypto-bigint/src/uint/split.rs | 58 +++ vendor/crypto-bigint/src/uint/sqrt.rs | 145 ++++++++ vendor/crypto-bigint/src/uint/sub.rs | 192 ++++++++++ vendor/crypto-bigint/src/uint/sub_mod.rs | 182 ++++++++++ 27 files changed, 3903 insertions(+) create mode 100644 vendor/crypto-bigint/src/uint/add.rs create mode 100644 vendor/crypto-bigint/src/uint/add_mod.rs create mode 100644 vendor/crypto-bigint/src/uint/array.rs create mode 100644 vendor/crypto-bigint/src/uint/bit_and.rs create mode 100644 vendor/crypto-bigint/src/uint/bit_not.rs create mode 100644 vendor/crypto-bigint/src/uint/bit_or.rs create mode 100644 vendor/crypto-bigint/src/uint/bit_xor.rs create mode 100644 vendor/crypto-bigint/src/uint/bits.rs create mode 100644 vendor/crypto-bigint/src/uint/cmp.rs create mode 100644 vendor/crypto-bigint/src/uint/concat.rs create mode 100644 vendor/crypto-bigint/src/uint/div.rs create mode 100644 vendor/crypto-bigint/src/uint/encoding.rs create mode 100644 vendor/crypto-bigint/src/uint/encoding/der.rs create mode 100644 vendor/crypto-bigint/src/uint/encoding/rlp.rs create mode 100644 vendor/crypto-bigint/src/uint/from.rs create mode 100644 vendor/crypto-bigint/src/uint/inv_mod.rs create mode 100644 vendor/crypto-bigint/src/uint/mul.rs create mode 100644 vendor/crypto-bigint/src/uint/mul_mod.rs create mode 100644 vendor/crypto-bigint/src/uint/neg_mod.rs create mode 100644 vendor/crypto-bigint/src/uint/rand.rs create mode 100644 vendor/crypto-bigint/src/uint/resize.rs create mode 100644 vendor/crypto-bigint/src/uint/shl.rs create mode 100644 vendor/crypto-bigint/src/uint/shr.rs create mode 100644 vendor/crypto-bigint/src/uint/split.rs create mode 100644 vendor/crypto-bigint/src/uint/sqrt.rs create mode 100644 vendor/crypto-bigint/src/uint/sub.rs create mode 100644 vendor/crypto-bigint/src/uint/sub_mod.rs (limited to 'vendor/crypto-bigint/src/uint') diff --git a/vendor/crypto-bigint/src/uint/add.rs b/vendor/crypto-bigint/src/uint/add.rs new file mode 100644 index 000000000..2822e9e67 --- /dev/null +++ b/vendor/crypto-bigint/src/uint/add.rs @@ -0,0 +1,189 @@ +//! [`UInt`] addition operations. + +use crate::{Checked, CheckedAdd, Limb, UInt, Wrapping, Zero}; +use core::ops::{Add, AddAssign}; +use subtle::CtOption; + +impl UInt { + /// Computes `a + b + carry`, returning the result along with the new carry. + #[inline(always)] + pub const fn adc(&self, rhs: &Self, mut carry: Limb) -> (Self, Limb) { + let mut limbs = [Limb::ZERO; LIMBS]; + let mut i = 0; + + while i < LIMBS { + let (w, c) = self.limbs[i].adc(rhs.limbs[i], carry); + limbs[i] = w; + carry = c; + i += 1; + } + + (Self { limbs }, carry) + } + + /// Perform saturating addition, returning `MAX` on overflow. + pub const fn saturating_add(&self, rhs: &Self) -> Self { + let (res, overflow) = self.adc(rhs, Limb::ZERO); + + if overflow.0 == 0 { + res + } else { + Self::MAX + } + } + + /// Perform wrapping addition, discarding overflow. + pub const fn wrapping_add(&self, rhs: &Self) -> Self { + self.adc(rhs, Limb::ZERO).0 + } +} + +impl CheckedAdd<&UInt> for UInt { + type Output = Self; + + fn checked_add(&self, rhs: &Self) -> CtOption { + let (result, carry) = self.adc(rhs, Limb::ZERO); + CtOption::new(result, carry.is_zero()) + } +} + +impl Add for Wrapping> { + type Output = Self; + + fn add(self, rhs: Self) -> Wrapping> { + Wrapping(self.0.wrapping_add(&rhs.0)) + } +} + +impl Add<&Wrapping>> for Wrapping> { + type Output = Wrapping>; + + fn add(self, rhs: &Wrapping>) -> Wrapping> { + Wrapping(self.0.wrapping_add(&rhs.0)) + } +} + +impl Add>> for &Wrapping> { + type Output = Wrapping>; + + fn add(self, rhs: Wrapping>) -> Wrapping> { + Wrapping(self.0.wrapping_add(&rhs.0)) + } +} + +impl Add<&Wrapping>> for &Wrapping> { + type Output = Wrapping>; + + fn add(self, rhs: &Wrapping>) -> Wrapping> { + Wrapping(self.0.wrapping_add(&rhs.0)) + } +} + +impl AddAssign for Wrapping> { + fn add_assign(&mut self, other: Self) { + *self = *self + other; + } +} + +impl AddAssign<&Wrapping>> for Wrapping> { + fn add_assign(&mut self, other: &Self) { + *self = *self + other; + } +} + +impl Add for Checked> { + type Output = Self; + + fn add(self, rhs: Self) -> Checked> { + Checked( + self.0 + .and_then(|lhs| rhs.0.and_then(|rhs| lhs.checked_add(&rhs))), + ) + } +} + +impl Add<&Checked>> for Checked> { + type Output = Checked>; + + fn add(self, rhs: &Checked>) -> Checked> { + Checked( + self.0 + .and_then(|lhs| rhs.0.and_then(|rhs| lhs.checked_add(&rhs))), + ) + } +} + +impl Add>> for &Checked> { + type Output = Checked>; + + fn add(self, rhs: Checked>) -> Checked> { + Checked( + self.0 + .and_then(|lhs| rhs.0.and_then(|rhs| lhs.checked_add(&rhs))), + ) + } +} + +impl Add<&Checked>> for &Checked> { + type Output = Checked>; + + fn add(self, rhs: &Checked>) -> Checked> { + Checked( + self.0 + .and_then(|lhs| rhs.0.and_then(|rhs| lhs.checked_add(&rhs))), + ) + } +} + +impl AddAssign for Checked> { + fn add_assign(&mut self, other: Self) { + *self = *self + other; + } +} + +impl AddAssign<&Checked>> for Checked> { + fn add_assign(&mut self, other: &Self) { + *self = *self + other; + } +} + +#[cfg(test)] +mod tests { + use crate::{CheckedAdd, Limb, U128}; + + #[test] + fn adc_no_carry() { + let (res, carry) = U128::ZERO.adc(&U128::ONE, Limb::ZERO); + assert_eq!(res, U128::ONE); + assert_eq!(carry, Limb::ZERO); + } + + #[test] + fn adc_with_carry() { + let (res, carry) = U128::MAX.adc(&U128::ONE, Limb::ZERO); + assert_eq!(res, U128::ZERO); + assert_eq!(carry, Limb::ONE); + } + + #[test] + fn wrapping_add_no_carry() { + assert_eq!(U128::ZERO.wrapping_add(&U128::ONE), U128::ONE); + } + + #[test] + fn wrapping_add_with_carry() { + assert_eq!(U128::MAX.wrapping_add(&U128::ONE), U128::ZERO); + } + + #[test] + fn checked_add_ok() { + let result = U128::ZERO.checked_add(&U128::ONE); + assert_eq!(result.unwrap(), U128::ONE); + } + + #[test] + fn checked_add_overflow() { + let result = U128::MAX.checked_add(&U128::ONE); + assert!(!bool::from(result.is_some())); + } +} diff --git a/vendor/crypto-bigint/src/uint/add_mod.rs b/vendor/crypto-bigint/src/uint/add_mod.rs new file mode 100644 index 000000000..3486a0a57 --- /dev/null +++ b/vendor/crypto-bigint/src/uint/add_mod.rs @@ -0,0 +1,139 @@ +//! [`UInt`] addition modulus operations. + +use crate::{AddMod, Limb, UInt}; + +impl UInt { + /// Computes `self + rhs mod p` in constant time. + /// + /// Assumes `self + rhs` as unbounded integer is `< 2p`. + pub const fn add_mod(&self, rhs: &UInt, p: &UInt) -> UInt { + let (w, carry) = self.adc(rhs, Limb::ZERO); + + // Attempt to subtract the modulus, to ensure the result is in the field. + let (w, borrow) = w.sbb(p, Limb::ZERO); + let (_, borrow) = carry.sbb(Limb::ZERO, borrow); + + // If underflow occurred on the final limb, borrow = 0xfff...fff, otherwise + // borrow = 0x000...000. Thus, we use it as a mask to conditionally add the + // modulus. + let mut i = 0; + let mut res = Self::ZERO; + let mut carry = Limb::ZERO; + + while i < LIMBS { + let rhs = p.limbs[i].bitand(borrow); + let (limb, c) = w.limbs[i].adc(rhs, carry); + res.limbs[i] = limb; + carry = c; + i += 1; + } + + res + } + + /// Computes `self + rhs mod p` in constant time for the special modulus + /// `p = MAX+1-c` where `c` is small enough to fit in a single [`Limb`]. + /// + /// Assumes `self + rhs` as unbounded integer is `< 2p`. + pub const fn add_mod_special(&self, rhs: &Self, c: Limb) -> Self { + // `UInt::adc` also works with a carry greater than 1. + let (out, carry) = self.adc(rhs, c); + + // If overflow occurred, then above addition of `c` already accounts + // for the overflow. Otherwise, we need to subtract `c` again, which + // in that case cannot underflow. + let l = carry.0.wrapping_sub(1) & c.0; + let (out, _) = out.sbb(&UInt::from_word(l), Limb::ZERO); + out + } +} + +impl AddMod for UInt { + type Output = Self; + + fn add_mod(&self, rhs: &Self, p: &Self) -> Self { + debug_assert!(self < p); + debug_assert!(rhs < p); + self.add_mod(rhs, p) + } +} + +#[cfg(all(test, feature = "rand"))] +mod tests { + use crate::{Limb, NonZero, Random, RandomMod, UInt, U256}; + use rand_core::SeedableRng; + + // TODO(tarcieri): additional tests + proptests + + #[test] + fn add_mod_nist_p256() { + let a = + U256::from_be_hex("44acf6b7e36c1342c2c5897204fe09504e1e2efb1a900377dbc4e7a6a133ec56"); + let b = + U256::from_be_hex("d5777c45019673125ad240f83094d4252d829516fac8601ed01979ec1ec1a251"); + let n = + U256::from_be_hex("ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"); + + let actual = a.add_mod(&b, &n); + let expected = + U256::from_be_hex("1a2472fde50286541d97ca6a3592dd75beb9c9646e40c511b82496cfc3926956"); + + assert_eq!(expected, actual); + } + + macro_rules! test_add_mod_special { + ($size:expr, $test_name:ident) => { + #[test] + fn $test_name() { + let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(1); + let moduli = [ + NonZero::::random(&mut rng), + NonZero::::random(&mut rng), + ]; + + for special in &moduli { + let p = &NonZero::new(UInt::ZERO.wrapping_sub(&UInt::from_word(special.0))) + .unwrap(); + + let minus_one = p.wrapping_sub(&UInt::ONE); + + let base_cases = [ + (UInt::ZERO, UInt::ZERO, UInt::ZERO), + (UInt::ONE, UInt::ZERO, UInt::ONE), + (UInt::ZERO, UInt::ONE, UInt::ONE), + (minus_one, UInt::ONE, UInt::ZERO), + (UInt::ONE, minus_one, UInt::ZERO), + ]; + for (a, b, c) in &base_cases { + let x = a.add_mod_special(b, *special.as_ref()); + assert_eq!(*c, x, "{} + {} mod {} = {} != {}", a, b, p, x, c); + } + + for _i in 0..100 { + let a = UInt::<$size>::random_mod(&mut rng, p); + let b = UInt::<$size>::random_mod(&mut rng, p); + + let c = a.add_mod_special(&b, *special.as_ref()); + assert!(c < **p, "not reduced: {} >= {} ", c, p); + + let expected = a.add_mod(&b, p); + assert_eq!(c, expected, "incorrect result"); + } + } + } + }; + } + + test_add_mod_special!(1, add_mod_special_1); + test_add_mod_special!(2, add_mod_special_2); + test_add_mod_special!(3, add_mod_special_3); + test_add_mod_special!(4, add_mod_special_4); + test_add_mod_special!(5, add_mod_special_5); + test_add_mod_special!(6, add_mod_special_6); + test_add_mod_special!(7, add_mod_special_7); + test_add_mod_special!(8, add_mod_special_8); + test_add_mod_special!(9, add_mod_special_9); + test_add_mod_special!(10, add_mod_special_10); + test_add_mod_special!(11, add_mod_special_11); + test_add_mod_special!(12, add_mod_special_12); +} diff --git a/vendor/crypto-bigint/src/uint/array.rs b/vendor/crypto-bigint/src/uint/array.rs new file mode 100644 index 000000000..cba2b3716 --- /dev/null +++ b/vendor/crypto-bigint/src/uint/array.rs @@ -0,0 +1,189 @@ +//! `generic-array` integration with `UInt`. +// TODO(tarcieri): completely phase out `generic-array` when const generics are powerful enough + +use crate::{ArrayDecoding, ArrayEncoding, ByteArray}; +use generic_array::{typenum, GenericArray}; + +macro_rules! impl_uint_array_encoding { + ($(($uint:ident, $bytes:path)),+) => { + $( + #[cfg_attr(docsrs, doc(cfg(feature = "generic-array")))] + impl ArrayEncoding for super::$uint { + type ByteSize = $bytes; + + #[inline] + fn from_be_byte_array(bytes: ByteArray) -> Self { + Self::from_be_slice(&bytes) + } + + #[inline] + fn from_le_byte_array(bytes: ByteArray) -> Self { + Self::from_le_slice(&bytes) + } + + #[inline] + fn to_be_byte_array(&self) -> ByteArray { + let mut result = GenericArray::default(); + self.write_be_bytes(&mut result); + result + } + + #[inline] + fn to_le_byte_array(&self) -> ByteArray { + let mut result = GenericArray::default(); + self.write_le_bytes(&mut result); + result + } + } + + #[cfg_attr(docsrs, doc(cfg(feature = "generic-array")))] + impl ArrayDecoding for GenericArray { + type Output = super::$uint; + + fn into_uint_be(self) -> Self::Output { + Self::Output::from_be_byte_array(self) + } + + fn into_uint_le(self) -> Self::Output { + Self::Output::from_le_byte_array(self) + } + } + )+ + }; +} + +// TODO(tarcieri): use `const_evaluatable_checked` when stable to make generic around bits. +impl_uint_array_encoding! { + (U64, typenum::U8), + (U128, typenum::U16), + (U192, typenum::U24), + (U256, typenum::U32), + (U384, typenum::U48), + (U448, typenum::U56), + (U512, typenum::U64), + (U576, typenum::U72), + (U768, typenum::U96), + (U896, typenum::U112), + (U1024, typenum::U128), + (U1536, typenum::U192), + (U1792, typenum::U224), + (U2048, typenum::U256), + (U3072, typenum::U384), + (U3584, typenum::U448), + (U4096, typenum::U512), + (U6144, typenum::U768), + (U8192, typenum::U1024) +} + +#[cfg(test)] +mod tests { + use crate::{ArrayDecoding, ArrayEncoding, Limb}; + use hex_literal::hex; + + #[cfg(target_pointer_width = "32")] + use crate::U64 as UIntEx; + + #[cfg(target_pointer_width = "64")] + use crate::U128 as UIntEx; + + /// Byte array that corresponds to `UIntEx` + type ByteArray = crate::ByteArray; + + #[test] + #[cfg(target_pointer_width = "32")] + fn from_be_byte_array() { + let n = UIntEx::from_be_byte_array(hex!("0011223344556677").into()); + assert_eq!(n.limbs(), &[Limb(0x44556677), Limb(0x00112233)]); + } + + #[test] + #[cfg(target_pointer_width = "64")] + fn from_be_byte_array() { + let n = UIntEx::from_be_byte_array(hex!("00112233445566778899aabbccddeeff").into()); + assert_eq!( + n.limbs(), + &[Limb(0x8899aabbccddeeff), Limb(0x0011223344556677)] + ); + } + + #[test] + #[cfg(target_pointer_width = "32")] + fn from_le_byte_array() { + let n = UIntEx::from_le_byte_array(hex!("7766554433221100").into()); + assert_eq!(n.limbs(), &[Limb(0x44556677), Limb(0x00112233)]); + } + + #[test] + #[cfg(target_pointer_width = "64")] + fn from_le_byte_array() { + let n = UIntEx::from_le_byte_array(hex!("ffeeddccbbaa99887766554433221100").into()); + assert_eq!( + n.limbs(), + &[Limb(0x8899aabbccddeeff), Limb(0x0011223344556677)] + ); + } + + #[test] + #[cfg(target_pointer_width = "32")] + fn to_be_byte_array() { + let expected_bytes = ByteArray::from(hex!("0011223344556677")); + let actual_bytes = UIntEx::from_be_byte_array(expected_bytes).to_be_byte_array(); + assert_eq!(expected_bytes, actual_bytes); + } + + #[test] + #[cfg(target_pointer_width = "64")] + fn to_be_byte_array() { + let expected_bytes = ByteArray::from(hex!("00112233445566778899aabbccddeeff")); + let actual_bytes = UIntEx::from_be_byte_array(expected_bytes).to_be_byte_array(); + assert_eq!(expected_bytes, actual_bytes); + } + + #[test] + #[cfg(target_pointer_width = "32")] + fn to_le_byte_array() { + let expected_bytes = ByteArray::from(hex!("7766554433221100")); + let actual_bytes = UIntEx::from_le_byte_array(expected_bytes).to_le_byte_array(); + assert_eq!(expected_bytes, actual_bytes); + } + + #[test] + #[cfg(target_pointer_width = "64")] + fn to_le_byte_array() { + let expected_bytes = ByteArray::from(hex!("ffeeddccbbaa99887766554433221100")); + let actual_bytes = UIntEx::from_le_byte_array(expected_bytes).to_le_byte_array(); + assert_eq!(expected_bytes, actual_bytes); + } + + #[test] + #[cfg(target_pointer_width = "32")] + fn into_uint_be() { + let expected_bytes = ByteArray::from(hex!("0011223344556677")); + let actual_bytes = expected_bytes.into_uint_be().to_be_byte_array(); + assert_eq!(expected_bytes, actual_bytes); + } + + #[test] + #[cfg(target_pointer_width = "64")] + fn into_uint_be() { + let expected_bytes = ByteArray::from(hex!("00112233445566778899aabbccddeeff")); + let actual_bytes = expected_bytes.into_uint_be().to_be_byte_array(); + assert_eq!(expected_bytes, actual_bytes); + } + + #[test] + #[cfg(target_pointer_width = "32")] + fn into_uint_le() { + let expected_bytes = ByteArray::from(hex!("7766554433221100")); + let actual_bytes = expected_bytes.into_uint_le().to_le_byte_array(); + assert_eq!(expected_bytes, actual_bytes); + } + + #[test] + #[cfg(target_pointer_width = "64")] + fn into_uint_le() { + let expected_bytes = ByteArray::from(hex!("ffeeddccbbaa99887766554433221100")); + let actual_bytes = expected_bytes.into_uint_le().to_le_byte_array(); + assert_eq!(expected_bytes, actual_bytes); + } +} diff --git a/vendor/crypto-bigint/src/uint/bit_and.rs b/vendor/crypto-bigint/src/uint/bit_and.rs new file mode 100644 index 000000000..cab89a429 --- /dev/null +++ b/vendor/crypto-bigint/src/uint/bit_and.rs @@ -0,0 +1,145 @@ +//! [`UInt`] bitwise and operations. + +use super::UInt; +use crate::{Limb, Wrapping}; +use core::ops::{BitAnd, BitAndAssign}; +use subtle::{Choice, CtOption}; + +impl UInt { + /// Computes bitwise `a & b`. + #[inline(always)] + pub const fn bitand(&self, rhs: &Self) -> Self { + let mut limbs = [Limb::ZERO; LIMBS]; + let mut i = 0; + + while i < LIMBS { + limbs[i] = self.limbs[i].bitand(rhs.limbs[i]); + i += 1; + } + + Self { limbs } + } + + /// Perform wrapping bitwise `AND`. + /// + /// There's no way wrapping could ever happen. + /// This function exists so that all operations are accounted for in the wrapping operations + pub const fn wrapping_and(&self, rhs: &Self) -> Self { + self.bitand(rhs) + } + + /// Perform checked bitwise `AND`, returning a [`CtOption`] which `is_some` always + pub fn checked_and(&self, rhs: &Self) -> CtOption { + let result = self.bitand(rhs); + CtOption::new(result, Choice::from(1)) + } +} + +impl BitAnd for UInt { + type Output = Self; + + fn bitand(self, rhs: Self) -> UInt { + self.bitand(&rhs) + } +} + +impl BitAnd<&UInt> for UInt { + type Output = UInt; + + fn bitand(self, rhs: &UInt) -> UInt { + (&self).bitand(rhs) + } +} + +impl BitAnd> for &UInt { + type Output = UInt; + + fn bitand(self, rhs: UInt) -> UInt { + self.bitand(&rhs) + } +} + +impl BitAnd<&UInt> for &UInt { + type Output = UInt; + + fn bitand(self, rhs: &UInt) -> UInt { + self.bitand(rhs) + } +} + +impl BitAndAssign for UInt { + #[allow(clippy::assign_op_pattern)] + fn bitand_assign(&mut self, other: Self) { + *self = *self & other; + } +} + +impl BitAndAssign<&UInt> for UInt { + #[allow(clippy::assign_op_pattern)] + fn bitand_assign(&mut self, other: &Self) { + *self = *self & other; + } +} + +impl BitAnd for Wrapping> { + type Output = Self; + + fn bitand(self, rhs: Self) -> Wrapping> { + Wrapping(self.0.bitand(&rhs.0)) + } +} + +impl BitAnd<&Wrapping>> for Wrapping> { + type Output = Wrapping>; + + fn bitand(self, rhs: &Wrapping>) -> Wrapping> { + Wrapping(self.0.bitand(&rhs.0)) + } +} + +impl BitAnd>> for &Wrapping> { + type Output = Wrapping>; + + fn bitand(self, rhs: Wrapping>) -> Wrapping> { + Wrapping(self.0.bitand(&rhs.0)) + } +} + +impl BitAnd<&Wrapping>> for &Wrapping> { + type Output = Wrapping>; + + fn bitand(self, rhs: &Wrapping>) -> Wrapping> { + Wrapping(self.0.bitand(&rhs.0)) + } +} + +impl BitAndAssign for Wrapping> { + #[allow(clippy::assign_op_pattern)] + fn bitand_assign(&mut self, other: Self) { + *self = *self & other; + } +} + +impl BitAndAssign<&Wrapping>> for Wrapping> { + #[allow(clippy::assign_op_pattern)] + fn bitand_assign(&mut self, other: &Self) { + *self = *self & other; + } +} + +#[cfg(test)] +mod tests { + use crate::U128; + + #[test] + fn checked_and_ok() { + let result = U128::ZERO.checked_and(&U128::ONE); + assert_eq!(result.unwrap(), U128::ZERO); + } + + #[test] + fn overlapping_and_ok() { + let result = U128::MAX.wrapping_and(&U128::ONE); + assert_eq!(result, U128::ONE); + } +} diff --git a/vendor/crypto-bigint/src/uint/bit_not.rs b/vendor/crypto-bigint/src/uint/bit_not.rs new file mode 100644 index 000000000..747d3b49e --- /dev/null +++ b/vendor/crypto-bigint/src/uint/bit_not.rs @@ -0,0 +1,48 @@ +//! [`UInt`] bitwise not operations. + +use super::UInt; +use crate::{Limb, Wrapping}; +use core::ops::Not; + +impl UInt { + /// Computes bitwise `!a`. + #[inline(always)] + pub const fn not(&self) -> Self { + let mut limbs = [Limb::ZERO; LIMBS]; + let mut i = 0; + + while i < LIMBS { + limbs[i] = self.limbs[i].not(); + i += 1; + } + + Self { limbs } + } +} + +impl Not for UInt { + type Output = Self; + + fn not(self) -> ::Output { + (&self).not() + } +} + +impl Not for Wrapping> { + type Output = Self; + + fn not(self) -> ::Output { + Wrapping(self.0.not()) + } +} + +#[cfg(test)] +mod tests { + use crate::U128; + + #[test] + fn bitnot_ok() { + assert_eq!(U128::ZERO.not(), U128::MAX); + assert_eq!(U128::MAX.not(), U128::ZERO); + } +} diff --git a/vendor/crypto-bigint/src/uint/bit_or.rs b/vendor/crypto-bigint/src/uint/bit_or.rs new file mode 100644 index 000000000..4a01a8343 --- /dev/null +++ b/vendor/crypto-bigint/src/uint/bit_or.rs @@ -0,0 +1,141 @@ +//! [`UInt`] bitwise or operations. + +use super::UInt; +use crate::{Limb, Wrapping}; +use core::ops::{BitOr, BitOrAssign}; +use subtle::{Choice, CtOption}; + +impl UInt { + /// Computes bitwise `a & b`. + #[inline(always)] + pub const fn bitor(&self, rhs: &Self) -> Self { + let mut limbs = [Limb::ZERO; LIMBS]; + let mut i = 0; + + while i < LIMBS { + limbs[i] = self.limbs[i].bitor(rhs.limbs[i]); + i += 1; + } + + Self { limbs } + } + + /// Perform wrapping bitwise `OR`. + /// + /// There's no way wrapping could ever happen. + /// This function exists so that all operations are accounted for in the wrapping operations + pub const fn wrapping_or(&self, rhs: &Self) -> Self { + self.bitor(rhs) + } + + /// Perform checked bitwise `OR`, returning a [`CtOption`] which `is_some` always + pub fn checked_or(&self, rhs: &Self) -> CtOption { + let result = self.bitor(rhs); + CtOption::new(result, Choice::from(1)) + } +} + +impl BitOr for UInt { + type Output = Self; + + fn bitor(self, rhs: Self) -> UInt { + self.bitor(&rhs) + } +} + +impl BitOr<&UInt> for UInt { + type Output = UInt; + + fn bitor(self, rhs: &UInt) -> UInt { + (&self).bitor(rhs) + } +} + +impl BitOr> for &UInt { + type Output = UInt; + + fn bitor(self, rhs: UInt) -> UInt { + self.bitor(&rhs) + } +} + +impl BitOr<&UInt> for &UInt { + type Output = UInt; + + fn bitor(self, rhs: &UInt) -> UInt { + self.bitor(rhs) + } +} + +impl BitOrAssign for UInt { + fn bitor_assign(&mut self, other: Self) { + *self = *self | other; + } +} + +impl BitOrAssign<&UInt> for UInt { + fn bitor_assign(&mut self, other: &Self) { + *self = *self | other; + } +} + +impl BitOr for Wrapping> { + type Output = Self; + + fn bitor(self, rhs: Self) -> Wrapping> { + Wrapping(self.0.bitor(&rhs.0)) + } +} + +impl BitOr<&Wrapping>> for Wrapping> { + type Output = Wrapping>; + + fn bitor(self, rhs: &Wrapping>) -> Wrapping> { + Wrapping(self.0.bitor(&rhs.0)) + } +} + +impl BitOr>> for &Wrapping> { + type Output = Wrapping>; + + fn bitor(self, rhs: Wrapping>) -> Wrapping> { + Wrapping(self.0.bitor(&rhs.0)) + } +} + +impl BitOr<&Wrapping>> for &Wrapping> { + type Output = Wrapping>; + + fn bitor(self, rhs: &Wrapping>) -> Wrapping> { + Wrapping(self.0.bitor(&rhs.0)) + } +} + +impl BitOrAssign for Wrapping> { + fn bitor_assign(&mut self, other: Self) { + *self = *self | other; + } +} + +impl BitOrAssign<&Wrapping>> for Wrapping> { + fn bitor_assign(&mut self, other: &Self) { + *self = *self | other; + } +} + +#[cfg(test)] +mod tests { + use crate::U128; + + #[test] + fn checked_or_ok() { + let result = U128::ZERO.checked_or(&U128::ONE); + assert_eq!(result.unwrap(), U128::ONE); + } + + #[test] + fn overlapping_or_ok() { + let result = U128::MAX.wrapping_or(&U128::ONE); + assert_eq!(result, U128::MAX); + } +} diff --git a/vendor/crypto-bigint/src/uint/bit_xor.rs b/vendor/crypto-bigint/src/uint/bit_xor.rs new file mode 100644 index 000000000..16d78ad3a --- /dev/null +++ b/vendor/crypto-bigint/src/uint/bit_xor.rs @@ -0,0 +1,141 @@ +//! [`UInt`] bitwise xor operations. + +use super::UInt; +use crate::{Limb, Wrapping}; +use core::ops::{BitXor, BitXorAssign}; +use subtle::{Choice, CtOption}; + +impl UInt { + /// Computes bitwise `a ^ b`. + #[inline(always)] + pub const fn bitxor(&self, rhs: &Self) -> Self { + let mut limbs = [Limb::ZERO; LIMBS]; + let mut i = 0; + + while i < LIMBS { + limbs[i] = self.limbs[i].bitxor(rhs.limbs[i]); + i += 1; + } + + Self { limbs } + } + + /// Perform wrapping bitwise `XOR``. + /// + /// There's no way wrapping could ever happen. + /// This function exists so that all operations are accounted for in the wrapping operations + pub const fn wrapping_xor(&self, rhs: &Self) -> Self { + self.bitxor(rhs) + } + + /// Perform checked bitwise `XOR`, returning a [`CtOption`] which `is_some` always + pub fn checked_xor(&self, rhs: &Self) -> CtOption { + let result = self.bitxor(rhs); + CtOption::new(result, Choice::from(1)) + } +} + +impl BitXor for UInt { + type Output = Self; + + fn bitxor(self, rhs: Self) -> UInt { + self.bitxor(&rhs) + } +} + +impl BitXor<&UInt> for UInt { + type Output = UInt; + + fn bitxor(self, rhs: &UInt) -> UInt { + (&self).bitxor(rhs) + } +} + +impl BitXor> for &UInt { + type Output = UInt; + + fn bitxor(self, rhs: UInt) -> UInt { + self.bitxor(&rhs) + } +} + +impl BitXor<&UInt> for &UInt { + type Output = UInt; + + fn bitxor(self, rhs: &UInt) -> UInt { + self.bitxor(rhs) + } +} + +impl BitXorAssign for UInt { + fn bitxor_assign(&mut self, other: Self) { + *self = *self ^ other; + } +} + +impl BitXorAssign<&UInt> for UInt { + fn bitxor_assign(&mut self, other: &Self) { + *self = *self ^ other; + } +} + +impl BitXor for Wrapping> { + type Output = Self; + + fn bitxor(self, rhs: Self) -> Wrapping> { + Wrapping(self.0.bitxor(&rhs.0)) + } +} + +impl BitXor<&Wrapping>> for Wrapping> { + type Output = Wrapping>; + + fn bitxor(self, rhs: &Wrapping>) -> Wrapping> { + Wrapping(self.0.bitxor(&rhs.0)) + } +} + +impl BitXor>> for &Wrapping> { + type Output = Wrapping>; + + fn bitxor(self, rhs: Wrapping>) -> Wrapping> { + Wrapping(self.0.bitxor(&rhs.0)) + } +} + +impl BitXor<&Wrapping>> for &Wrapping> { + type Output = Wrapping>; + + fn bitxor(self, rhs: &Wrapping>) -> Wrapping> { + Wrapping(self.0.bitxor(&rhs.0)) + } +} + +impl BitXorAssign for Wrapping> { + fn bitxor_assign(&mut self, other: Self) { + *self = *self ^ other; + } +} + +impl BitXorAssign<&Wrapping>> for Wrapping> { + fn bitxor_assign(&mut self, other: &Self) { + *self = *self ^ other; + } +} + +#[cfg(test)] +mod tests { + use crate::U128; + + #[test] + fn checked_xor_ok() { + let result = U128::ZERO.checked_xor(&U128::ONE); + assert_eq!(result.unwrap(), U128::ONE); + } + + #[test] + fn overlapping_xor_ok() { + let result = U128::ZERO.wrapping_xor(&U128::ONE); + assert_eq!(result, U128::ONE); + } +} diff --git a/vendor/crypto-bigint/src/uint/bits.rs b/vendor/crypto-bigint/src/uint/bits.rs new file mode 100644 index 000000000..b76d89fa5 --- /dev/null +++ b/vendor/crypto-bigint/src/uint/bits.rs @@ -0,0 +1,55 @@ +use crate::{Limb, UInt, Word}; + +impl UInt { + /// Get the value of the bit at position `index`, as a 0- or 1-valued Word. + /// Returns 0 for indices out of range. + #[inline(always)] + pub const fn bit_vartime(self, index: usize) -> Word { + if index >= LIMBS * Limb::BIT_SIZE { + 0 + } else { + (self.limbs[index / Limb::BIT_SIZE].0 >> (index % Limb::BIT_SIZE)) & 1 + } + } + + /// Calculate the number of bits needed to represent this number. + #[deprecated(note = "please use `bits_vartime` instead")] + #[inline(always)] + pub const fn bits(self) -> usize { + self.bits_vartime() + } + + /// Calculate the number of bits needed to represent this number. + #[allow(trivial_numeric_casts)] + pub const fn bits_vartime(self) -> usize { + let mut i = LIMBS - 1; + while i > 0 && self.limbs[i].0 == 0 { + i -= 1; + } + + let limb = self.limbs[i].0; + let bits = (Limb::BIT_SIZE * (i + 1)) as Word - limb.leading_zeros() as Word; + + Limb::ct_select( + Limb(bits), + Limb::ZERO, + !self.limbs[0].is_nonzero() & !Limb(i as Word).is_nonzero(), + ) + .0 as usize + } +} + +#[cfg(test)] +mod tests { + use crate::U128; + + #[test] + fn bit_vartime_ok() { + let u = U128::from_be_hex("f0010000000000000001000000010000"); + assert_eq!(u.bit_vartime(0), 0); + assert_eq!(u.bit_vartime(1), 0); + assert_eq!(u.bit_vartime(16), 1); + assert_eq!(u.bit_vartime(127), 1); + assert_eq!(u.bit_vartime(130), 0); + } +} diff --git a/vendor/crypto-bigint/src/uint/cmp.rs b/vendor/crypto-bigint/src/uint/cmp.rs new file mode 100644 index 000000000..19046df9b --- /dev/null +++ b/vendor/crypto-bigint/src/uint/cmp.rs @@ -0,0 +1,196 @@ +//! [`UInt`] comparisons. +//! +//! By default these are all constant-time and use the `subtle` crate. + +use super::UInt; +use crate::{limb::HI_BIT, Limb, SignedWord, WideSignedWord, Word, Zero}; +use core::cmp::Ordering; +use subtle::{Choice, ConstantTimeEq, ConstantTimeGreater, ConstantTimeLess}; + +impl UInt { + /// Return `a` if `c`==0 or `b` if `c`==`Word::MAX`. + /// + /// Const-friendly: we can't yet use `subtle` in `const fn` contexts. + #[inline] + pub(crate) const fn ct_select(a: UInt, b: UInt, c: Word) -> Self { + let mut limbs = [Limb::ZERO; LIMBS]; + + let mut i = 0; + while i < LIMBS { + limbs[i] = Limb::ct_select(a.limbs[i], b.limbs[i], c); + i += 1; + } + + UInt { limbs } + } + + /// Returns all 1's if `self`!=0 or 0 if `self`==0. + /// + /// Const-friendly: we can't yet use `subtle` in `const fn` contexts. + #[inline] + pub(crate) const fn ct_is_nonzero(&self) -> Word { + let mut b = 0; + let mut i = 0; + while i < LIMBS { + b |= self.limbs[i].0; + i += 1; + } + Limb::is_nonzero(Limb(b)) + } + + /// Returns -1 if self < rhs + /// 0 if self == rhs + /// 1 if self > rhs + /// + /// Const-friendly: we can't yet use `subtle` in `const fn` contexts. + #[inline] + pub(crate) const fn ct_cmp(&self, rhs: &Self) -> SignedWord { + let mut gt = 0; + let mut lt = 0; + let mut i = LIMBS; + + while i > 0 { + let a = self.limbs[i - 1].0 as WideSignedWord; + let b = rhs.limbs[i - 1].0 as WideSignedWord; + gt |= ((b - a) >> Limb::BIT_SIZE) & 1 & !lt; + lt |= ((a - b) >> Limb::BIT_SIZE) & 1 & !gt; + i -= 1; + } + (gt as SignedWord) - (lt as SignedWord) + } + + /// Returns 0 if self == rhs or Word::MAX if self != rhs. + /// Const-friendly: we can't yet use `subtle` in `const fn` contexts. + #[inline] + pub(crate) const fn ct_not_eq(&self, rhs: &Self) -> Word { + let mut acc = 0; + let mut i = 0; + + while i < LIMBS { + acc |= self.limbs[i].0 ^ rhs.limbs[i].0; + i += 1; + } + let acc = acc as SignedWord; + ((acc | acc.wrapping_neg()) >> HI_BIT) as Word + } +} + +impl ConstantTimeEq for UInt { + #[inline] + fn ct_eq(&self, other: &Self) -> Choice { + Choice::from((!self.ct_not_eq(other) as u8) & 1) + } +} + +impl ConstantTimeGreater for UInt { + #[inline] + fn ct_gt(&self, other: &Self) -> Choice { + let underflow = other.sbb(self, Limb::ZERO).1; + !underflow.is_zero() + } +} + +impl ConstantTimeLess for UInt { + #[inline] + fn ct_lt(&self, other: &Self) -> Choice { + let underflow = self.sbb(other, Limb::ZERO).1; + !underflow.is_zero() + } +} + +impl Eq for UInt {} + +impl Ord for UInt { + fn cmp(&self, other: &Self) -> Ordering { + match self.ct_cmp(other) { + -1 => Ordering::Less, + 1 => Ordering::Greater, + n => { + debug_assert_eq!(n, 0); + debug_assert!(bool::from(self.ct_eq(other))); + Ordering::Equal + } + } + } +} + +impl PartialOrd for UInt { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + +impl PartialEq for UInt { + fn eq(&self, other: &Self) -> bool { + self.ct_eq(other).into() + } +} + +#[cfg(test)] +mod tests { + use crate::{Integer, Zero, U128}; + use subtle::{ConstantTimeEq, ConstantTimeGreater, ConstantTimeLess}; + + #[test] + fn is_zero() { + assert!(bool::from(U128::ZERO.is_zero())); + assert!(!bool::from(U128::ONE.is_zero())); + assert!(!bool::from(U128::MAX.is_zero())); + } + + #[test] + fn is_odd() { + assert!(!bool::from(U128::ZERO.is_odd())); + assert!(bool::from(U128::ONE.is_odd())); + assert!(bool::from(U128::MAX.is_odd())); + } + + #[test] + fn ct_eq() { + let a = U128::ZERO; + let b = U128::MAX; + + assert!(bool::from(a.ct_eq(&a))); + assert!(!bool::from(a.ct_eq(&b))); + assert!(!bool::from(b.ct_eq(&a))); + assert!(bool::from(b.ct_eq(&b))); + } + + #[test] + fn ct_gt() { + let a = U128::ZERO; + let b = U128::ONE; + let c = U128::MAX; + + assert!(bool::from(b.ct_gt(&a))); + assert!(bool::from(c.ct_gt(&a))); + assert!(bool::from(c.ct_gt(&b))); + + assert!(!bool::from(a.ct_gt(&a))); + assert!(!bool::from(b.ct_gt(&b))); + assert!(!bool::from(c.ct_gt(&c))); + + assert!(!bool::from(a.ct_gt(&b))); + assert!(!bool::from(a.ct_gt(&c))); + assert!(!bool::from(b.ct_gt(&c))); + } + + #[test] + fn ct_lt() { + let a = U128::ZERO; + let b = U128::ONE; + let c = U128::MAX; + + assert!(bool::from(a.ct_lt(&b))); + assert!(bool::from(a.ct_lt(&c))); + assert!(bool::from(b.ct_lt(&c))); + + assert!(!bool::from(a.ct_lt(&a))); + assert!(!bool::from(b.ct_lt(&b))); + assert!(!bool::from(c.ct_lt(&c))); + + assert!(!bool::from(b.ct_lt(&a))); + assert!(!bool::from(c.ct_lt(&a))); + assert!(!bool::from(c.ct_lt(&b))); + } +} diff --git a/vendor/crypto-bigint/src/uint/concat.rs b/vendor/crypto-bigint/src/uint/concat.rs new file mode 100644 index 000000000..e92960da7 --- /dev/null +++ b/vendor/crypto-bigint/src/uint/concat.rs @@ -0,0 +1,60 @@ +// TODO(tarcieri): use `const_evaluatable_checked` when stable to make generic around bits. +macro_rules! impl_concat { + ($(($name:ident, $bits:expr)),+) => { + $( + impl $name { + /// Concatenate the two values, with `self` as most significant and `rhs` + /// as the least significant. + pub const fn concat(&self, rhs: &Self) -> UInt<{nlimbs!($bits) * 2}> { + let mut limbs = [Limb::ZERO; nlimbs!($bits) * 2]; + let mut i = 0; + let mut j = 0; + + while j < nlimbs!($bits) { + limbs[i] = rhs.limbs[j]; + i += 1; + j += 1; + } + + j = 0; + while j < nlimbs!($bits) { + limbs[i] = self.limbs[j]; + i += 1; + j += 1; + } + + UInt { limbs } + } + } + + impl Concat for $name { + type Output = UInt<{nlimbs!($bits) * 2}>; + + fn concat(&self, rhs: &Self) -> Self::Output { + self.concat(rhs) + } + } + + impl From<($name, $name)> for UInt<{nlimbs!($bits) * 2}> { + fn from(nums: ($name, $name)) -> UInt<{nlimbs!($bits) * 2}> { + nums.0.concat(&nums.1) + } + } + )+ + }; +} + +#[cfg(test)] +mod tests { + use crate::{U128, U64}; + + #[test] + fn concat() { + let hi = U64::from_u64(0x0011223344556677); + let lo = U64::from_u64(0x8899aabbccddeeff); + assert_eq!( + hi.concat(&lo), + U128::from_be_hex("00112233445566778899aabbccddeeff") + ); + } +} diff --git a/vendor/crypto-bigint/src/uint/div.rs b/vendor/crypto-bigint/src/uint/div.rs new file mode 100644 index 000000000..f7d9d6bf3 --- /dev/null +++ b/vendor/crypto-bigint/src/uint/div.rs @@ -0,0 +1,496 @@ +//! [`UInt`] division operations. + +use super::UInt; +use crate::limb::Word; +use crate::{Integer, Limb, NonZero, Wrapping}; +use core::ops::{Div, DivAssign, Rem, RemAssign}; +use subtle::{Choice, CtOption}; + +impl UInt { + /// Computes `self` / `rhs`, returns the quotient (q), remainder (r) + /// and 1 for is_some or 0 for is_none. The results can be wrapped in [`CtOption`]. + /// NOTE: Use only if you need to access const fn. Otherwise use `div_rem` because + /// the value for is_some needs to be checked before using `q` and `r`. + /// + /// This is variable only with respect to `rhs`. + /// + /// When used with a fixed `rhs`, this function is constant-time with respect + /// to `self`. + pub(crate) const fn ct_div_rem(&self, rhs: &Self) -> (Self, Self, u8) { + let mb = rhs.bits_vartime(); + let mut bd = (LIMBS * Limb::BIT_SIZE) - mb; + let mut rem = *self; + let mut quo = Self::ZERO; + let mut c = rhs.shl_vartime(bd); + + loop { + let (mut r, borrow) = rem.sbb(&c, Limb::ZERO); + rem = Self::ct_select(r, rem, borrow.0); + r = quo.bitor(&Self::ONE); + quo = Self::ct_select(r, quo, borrow.0); + if bd == 0 { + break; + } + bd -= 1; + c = c.shr_vartime(1); + quo = quo.shl_vartime(1); + } + + let is_some = Limb(mb as Word).is_nonzero(); + quo = Self::ct_select(Self::ZERO, quo, is_some); + (quo, rem, (is_some & 1) as u8) + } + + /// Computes `self` % `rhs`, returns the remainder and + /// and 1 for is_some or 0 for is_none. The results can be wrapped in [`CtOption`]. + /// NOTE: Use only if you need to access const fn. Otherwise use `reduce` + /// This is variable only with respect to `rhs`. + /// + /// When used with a fixed `rhs`, this function is constant-time with respect + /// to `self`. + pub(crate) const fn ct_reduce(&self, rhs: &Self) -> (Self, u8) { + let mb = rhs.bits_vartime(); + let mut bd = (LIMBS * Limb::BIT_SIZE) - mb; + let mut rem = *self; + let mut c = rhs.shl_vartime(bd); + + loop { + let (r, borrow) = rem.sbb(&c, Limb::ZERO); + rem = Self::ct_select(r, rem, borrow.0); + if bd == 0 { + break; + } + bd -= 1; + c = c.shr_vartime(1); + } + + let is_some = Limb(mb as Word).is_nonzero(); + (rem, (is_some & 1) as u8) + } + + /// Computes `self` % 2^k. Faster than reduce since its a power of 2. + /// Limited to 2^16-1 since UInt doesn't support higher. + pub const fn reduce2k(&self, k: usize) -> Self { + let highest = (LIMBS - 1) as u32; + let index = k as u32 / (Limb::BIT_SIZE as u32); + let res = Limb::ct_cmp(Limb::from_u32(index), Limb::from_u32(highest)) - 1; + let le = Limb::is_nonzero(Limb(res as Word)); + let word = Limb::ct_select(Limb::from_u32(highest), Limb::from_u32(index), le).0 as usize; + + let base = k % Limb::BIT_SIZE; + let mask = (1 << base) - 1; + let mut out = *self; + + let outmask = Limb(out.limbs[word].0 & mask); + + out.limbs[word] = Limb::ct_select(out.limbs[word], outmask, le); + + let mut i = word + 1; + while i < LIMBS { + out.limbs[i] = Limb::ZERO; + i += 1; + } + + out + } + + /// Computes self / rhs, returns the quotient, remainder + /// if rhs != 0 + pub fn div_rem(&self, rhs: &Self) -> CtOption<(Self, Self)> { + let (q, r, c) = self.ct_div_rem(rhs); + CtOption::new((q, r), Choice::from(c)) + } + + /// Computes self % rhs, returns the remainder + /// if rhs != 0 + pub fn reduce(&self, rhs: &Self) -> CtOption { + let (r, c) = self.ct_reduce(rhs); + CtOption::new(r, Choice::from(c)) + } + + /// Wrapped division is just normal division i.e. `self` / `rhs` + /// There’s no way wrapping could ever happen. + /// This function exists, so that all operations are accounted for in the wrapping operations. + pub const fn wrapping_div(&self, rhs: &Self) -> Self { + let (q, _, c) = self.ct_div_rem(rhs); + assert!(c == 1, "divide by zero"); + q + } + + /// Perform checked division, returning a [`CtOption`] which `is_some` + /// only if the rhs != 0 + pub fn checked_div(&self, rhs: &Self) -> CtOption { + let (q, _, c) = self.ct_div_rem(rhs); + CtOption::new(q, Choice::from(c)) + } + + /// Wrapped (modular) remainder calculation is just `self` % `rhs`. + /// There’s no way wrapping could ever happen. + /// This function exists, so that all operations are accounted for in the wrapping operations. + pub const fn wrapping_rem(&self, rhs: &Self) -> Self { + let (r, c) = self.ct_reduce(rhs); + assert!(c == 1, "modulo zero"); + r + } + + /// Perform checked reduction, returning a [`CtOption`] which `is_some` + /// only if the rhs != 0 + pub fn checked_rem(&self, rhs: &Self) -> CtOption { + let (r, c) = self.ct_reduce(rhs); + CtOption::new(r, Choice::from(c)) + } +} + +impl Div<&NonZero>> for &UInt +where + UInt: Integer, +{ + type Output = UInt; + + fn div(self, rhs: &NonZero>) -> Self::Output { + *self / *rhs + } +} + +impl Div<&NonZero>> for UInt +where + UInt: Integer, +{ + type Output = UInt; + + fn div(self, rhs: &NonZero>) -> Self::Output { + self / *rhs + } +} + +impl Div>> for &UInt +where + UInt: Integer, +{ + type Output = UInt; + + fn div(self, rhs: NonZero>) -> Self::Output { + *self / rhs + } +} + +impl Div>> for UInt +where + UInt: Integer, +{ + type Output = UInt; + + fn div(self, rhs: NonZero>) -> Self::Output { + let (q, _, _) = self.ct_div_rem(&rhs); + q + } +} + +impl DivAssign<&NonZero>> for UInt +where + UInt: Integer, +{ + fn div_assign(&mut self, rhs: &NonZero>) { + let (q, _, _) = self.ct_div_rem(rhs); + *self = q + } +} + +impl DivAssign>> for UInt +where + UInt: Integer, +{ + fn div_assign(&mut self, rhs: NonZero>) { + *self /= &rhs; + } +} + +impl Div>> for Wrapping> { + type Output = Wrapping>; + + fn div(self, rhs: NonZero>) -> Self::Output { + Wrapping(self.0.wrapping_div(rhs.as_ref())) + } +} + +impl Div>> for &Wrapping> { + type Output = Wrapping>; + + fn div(self, rhs: NonZero>) -> Self::Output { + *self / rhs + } +} + +impl Div<&NonZero>> for &Wrapping> { + type Output = Wrapping>; + + fn div(self, rhs: &NonZero>) -> Self::Output { + *self / *rhs + } +} + +impl Div<&NonZero>> for Wrapping> { + type Output = Wrapping>; + + fn div(self, rhs: &NonZero>) -> Self::Output { + self / *rhs + } +} + +impl DivAssign<&NonZero>> for Wrapping> { + fn div_assign(&mut self, rhs: &NonZero>) { + *self = Wrapping(self.0.wrapping_div(rhs.as_ref())) + } +} + +impl DivAssign>> for Wrapping> { + fn div_assign(&mut self, rhs: NonZero>) { + *self /= &rhs; + } +} + +impl Rem<&NonZero>> for &UInt +where + UInt: Integer, +{ + type Output = UInt; + + fn rem(self, rhs: &NonZero>) -> Self::Output { + *self % *rhs + } +} + +impl Rem<&NonZero>> for UInt +where + UInt: Integer, +{ + type Output = UInt; + + fn rem(self, rhs: &NonZero>) -> Self::Output { + self % *rhs + } +} + +impl Rem>> for &UInt +where + UInt: Integer, +{ + type Output = UInt; + + fn rem(self, rhs: NonZero>) -> Self::Output { + *self % rhs + } +} + +impl Rem>> for UInt +where + UInt: Integer, +{ + type Output = UInt; + + fn rem(self, rhs: NonZero>) -> Self::Output { + let (r, _) = self.ct_reduce(&rhs); + r + } +} + +impl RemAssign<&NonZero>> for UInt +where + UInt: Integer, +{ + fn rem_assign(&mut self, rhs: &NonZero>) { + let (r, _) = self.ct_reduce(rhs); + *self = r + } +} + +impl RemAssign>> for UInt +where + UInt: Integer, +{ + fn rem_assign(&mut self, rhs: NonZero>) { + *self %= &rhs; + } +} + +impl Rem>> for Wrapping> { + type Output = Wrapping>; + + fn rem(self, rhs: NonZero>) -> Self::Output { + Wrapping(self.0.wrapping_rem(rhs.as_ref())) + } +} + +impl Rem>> for &Wrapping> { + type Output = Wrapping>; + + fn rem(self, rhs: NonZero>) -> Self::Output { + *self % rhs + } +} + +impl Rem<&NonZero>> for &Wrapping> { + type Output = Wrapping>; + + fn rem(self, rhs: &NonZero>) -> Self::Output { + *self % *rhs + } +} + +impl Rem<&NonZero>> for Wrapping> { + type Output = Wrapping>; + + fn rem(self, rhs: &NonZero>) -> Self::Output { + self % *rhs + } +} + +impl RemAssign>> for Wrapping> { + fn rem_assign(&mut self, rhs: NonZero>) { + *self %= &rhs; + } +} + +impl RemAssign<&NonZero>> for Wrapping> { + fn rem_assign(&mut self, rhs: &NonZero>) { + *self = Wrapping(self.0.wrapping_rem(rhs.as_ref())) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{limb::HI_BIT, Limb, U256}; + + #[cfg(feature = "rand")] + use { + crate::{CheckedMul, Random}, + rand_chacha::ChaChaRng, + rand_core::RngCore, + rand_core::SeedableRng, + }; + + #[test] + fn div_word() { + for (n, d, e, ee) in &[ + (200u64, 2u64, 100u64, 0), + (100u64, 25u64, 4u64, 0), + (100u64, 10u64, 10u64, 0), + (1024u64, 8u64, 128u64, 0), + (27u64, 13u64, 2u64, 1u64), + (26u64, 13u64, 2u64, 0u64), + (14u64, 13u64, 1u64, 1u64), + (13u64, 13u64, 1u64, 0u64), + (12u64, 13u64, 0u64, 12u64), + (1u64, 13u64, 0u64, 1u64), + ] { + let lhs = U256::from(*n); + let rhs = U256::from(*d); + let (q, r, is_some) = lhs.ct_div_rem(&rhs); + assert_eq!(is_some, 1); + assert_eq!(U256::from(*e), q); + assert_eq!(U256::from(*ee), r); + } + } + + #[cfg(feature = "rand")] + #[test] + fn div() { + let mut rng = ChaChaRng::from_seed([7u8; 32]); + for _ in 0..25 { + let num = U256::random(&mut rng).shr_vartime(128); + let den = U256::random(&mut rng).shr_vartime(128); + let n = num.checked_mul(&den); + if n.is_some().unwrap_u8() == 1 { + let (q, _, is_some) = n.unwrap().ct_div_rem(&den); + assert_eq!(is_some, 1); + assert_eq!(q, num); + } + } + } + + #[test] + fn div_max() { + let mut a = U256::ZERO; + let mut b = U256::ZERO; + b.limbs[b.limbs.len() - 1] = Limb(Word::MAX); + let q = a.wrapping_div(&b); + assert_eq!(q, UInt::ZERO); + a.limbs[a.limbs.len() - 1] = Limb(1 << (HI_BIT - 7)); + b.limbs[b.limbs.len() - 1] = Limb(0x82 << (HI_BIT - 7)); + let q = a.wrapping_div(&b); + assert_eq!(q, UInt::ZERO); + } + + #[test] + fn div_zero() { + let (q, r, is_some) = U256::ONE.ct_div_rem(&U256::ZERO); + assert_eq!(is_some, 0); + assert_eq!(q, U256::ZERO); + assert_eq!(r, U256::ONE); + } + + #[test] + fn div_one() { + let (q, r, is_some) = U256::from(10u8).ct_div_rem(&U256::ONE); + assert_eq!(is_some, 1); + assert_eq!(q, U256::from(10u8)); + assert_eq!(r, U256::ZERO); + } + + #[test] + fn reduce_one() { + let (r, is_some) = U256::from(10u8).ct_reduce(&U256::ONE); + assert_eq!(is_some, 1); + assert_eq!(r, U256::ZERO); + } + + #[test] + fn reduce_zero() { + let u = U256::from(10u8); + let (r, is_some) = u.ct_reduce(&U256::ZERO); + assert_eq!(is_some, 0); + assert_eq!(r, u); + } + + #[test] + fn reduce_tests() { + let (r, is_some) = U256::from(10u8).ct_reduce(&U256::from(2u8)); + assert_eq!(is_some, 1); + assert_eq!(r, U256::ZERO); + let (r, is_some) = U256::from(10u8).ct_reduce(&U256::from(3u8)); + assert_eq!(is_some, 1); + assert_eq!(r, U256::ONE); + let (r, is_some) = U256::from(10u8).ct_reduce(&U256::from(7u8)); + assert_eq!(is_some, 1); + assert_eq!(r, U256::from(3u8)); + } + + #[test] + fn reduce_max() { + let mut a = U256::ZERO; + let mut b = U256::ZERO; + b.limbs[b.limbs.len() - 1] = Limb(Word::MAX); + let r = a.wrapping_rem(&b); + assert_eq!(r, UInt::ZERO); + a.limbs[a.limbs.len() - 1] = Limb(1 << (HI_BIT - 7)); + b.limbs[b.limbs.len() - 1] = Limb(0x82 << (HI_BIT - 7)); + let r = a.wrapping_rem(&b); + assert_eq!(r, a); + } + + #[cfg(feature = "rand")] + #[test] + fn reduce2krand() { + let mut rng = ChaChaRng::from_seed([7u8; 32]); + for _ in 0..25 { + let num = U256::random(&mut rng); + let k = (rng.next_u32() % 256) as usize; + let den = U256::ONE.shl_vartime(k); + + let a = num.reduce2k(k); + let e = num.wrapping_rem(&den); + assert_eq!(a, e); + } + } +} diff --git a/vendor/crypto-bigint/src/uint/encoding.rs b/vendor/crypto-bigint/src/uint/encoding.rs new file mode 100644 index 000000000..a83976238 --- /dev/null +++ b/vendor/crypto-bigint/src/uint/encoding.rs @@ -0,0 +1,278 @@ +//! Const-friendly decoding operations for [`UInt`] + +#[cfg(all(feature = "der", feature = "generic-array"))] +mod der; + +#[cfg(feature = "rlp")] +mod rlp; + +use super::UInt; +use crate::{Encoding, Limb, Word}; + +impl UInt { + /// Create a new [`UInt`] from the provided big endian bytes. + pub const fn from_be_slice(bytes: &[u8]) -> Self { + assert!( + bytes.len() == Limb::BYTE_SIZE * LIMBS, + "bytes are not the expected size" + ); + + let mut res = [Limb::ZERO; LIMBS]; + let mut buf = [0u8; Limb::BYTE_SIZE]; + let mut i = 0; + + while i < LIMBS { + let mut j = 0; + while j < Limb::BYTE_SIZE { + buf[j] = bytes[i * Limb::BYTE_SIZE + j]; + j += 1; + } + res[LIMBS - i - 1] = Limb(Word::from_be_bytes(buf)); + i += 1; + } + + UInt::new(res) + } + + /// Create a new [`UInt`] from the provided big endian hex string. + pub const fn from_be_hex(hex: &str) -> Self { + let bytes = hex.as_bytes(); + + assert!( + bytes.len() == Limb::BYTE_SIZE * LIMBS * 2, + "hex string is not the expected size" + ); + + let mut res = [Limb::ZERO; LIMBS]; + let mut buf = [0u8; Limb::BYTE_SIZE]; + let mut i = 0; + + while i < LIMBS { + let mut j = 0; + while j < Limb::BYTE_SIZE { + let offset = (i * Limb::BYTE_SIZE + j) * 2; + buf[j] = decode_hex_byte([bytes[offset], bytes[offset + 1]]); + j += 1; + } + res[LIMBS - i - 1] = Limb(Word::from_be_bytes(buf)); + i += 1; + } + + UInt::new(res) + } + + /// Create a new [`UInt`] from the provided little endian bytes. + pub const fn from_le_slice(bytes: &[u8]) -> Self { + assert!( + bytes.len() == Limb::BYTE_SIZE * LIMBS, + "bytes are not the expected size" + ); + + let mut res = [Limb::ZERO; LIMBS]; + let mut buf = [0u8; Limb::BYTE_SIZE]; + let mut i = 0; + + while i < LIMBS { + let mut j = 0; + while j < Limb::BYTE_SIZE { + buf[j] = bytes[i * Limb::BYTE_SIZE + j]; + j += 1; + } + res[i] = Limb(Word::from_le_bytes(buf)); + i += 1; + } + + UInt::new(res) + } + + /// Create a new [`UInt`] from the provided little endian hex string. + pub const fn from_le_hex(hex: &str) -> Self { + let bytes = hex.as_bytes(); + + assert!( + bytes.len() == Limb::BYTE_SIZE * LIMBS * 2, + "bytes are not the expected size" + ); + + let mut res = [Limb::ZERO; LIMBS]; + let mut buf = [0u8; Limb::BYTE_SIZE]; + let mut i = 0; + + while i < LIMBS { + let mut j = 0; + while j < Limb::BYTE_SIZE { + let offset = (i * Limb::BYTE_SIZE + j) * 2; + buf[j] = decode_hex_byte([bytes[offset], bytes[offset + 1]]); + j += 1; + } + res[i] = Limb(Word::from_le_bytes(buf)); + i += 1; + } + + UInt::new(res) + } + + /// Serialize this [`UInt`] as big-endian, writing it into the provided + /// byte slice. + #[inline] + #[cfg_attr(docsrs, doc(cfg(feature = "generic-array")))] + pub(crate) fn write_be_bytes(&self, out: &mut [u8]) { + debug_assert_eq!(out.len(), Limb::BYTE_SIZE * LIMBS); + + for (src, dst) in self + .limbs + .iter() + .rev() + .cloned() + .zip(out.chunks_exact_mut(Limb::BYTE_SIZE)) + { + dst.copy_from_slice(&src.to_be_bytes()); + } + } + + /// Serialize this [`UInt`] as little-endian, writing it into the provided + /// byte slice. + #[inline] + #[cfg_attr(docsrs, doc(cfg(feature = "generic-array")))] + pub(crate) fn write_le_bytes(&self, out: &mut [u8]) { + debug_assert_eq!(out.len(), Limb::BYTE_SIZE * LIMBS); + + for (src, dst) in self + .limbs + .iter() + .cloned() + .zip(out.chunks_exact_mut(Limb::BYTE_SIZE)) + { + dst.copy_from_slice(&src.to_le_bytes()); + } + } +} + +/// Decode a single byte encoded as two hexadecimal characters. +const fn decode_hex_byte(bytes: [u8; 2]) -> u8 { + let mut i = 0; + let mut result = 0u8; + + while i < 2 { + result <<= 4; + result |= match bytes[i] { + b @ b'0'..=b'9' => b - b'0', + b @ b'a'..=b'f' => 10 + b - b'a', + b @ b'A'..=b'F' => 10 + b - b'A', + b => { + assert!( + matches!(b, b'0'..=b'9' | b'a' ..= b'f' | b'A'..=b'F'), + "invalid hex byte" + ); + 0 + } + }; + + i += 1; + } + + result +} + +#[cfg(test)] +mod tests { + use crate::Limb; + use hex_literal::hex; + + #[cfg(feature = "alloc")] + use {crate::U128, alloc::format}; + + #[cfg(target_pointer_width = "32")] + use crate::U64 as UIntEx; + + #[cfg(target_pointer_width = "64")] + use crate::U128 as UIntEx; + + #[test] + #[cfg(target_pointer_width = "32")] + fn from_be_slice() { + let bytes = hex!("0011223344556677"); + let n = UIntEx::from_be_slice(&bytes); + assert_eq!(n.limbs(), &[Limb(0x44556677), Limb(0x00112233)]); + } + + #[test] + #[cfg(target_pointer_width = "64")] + fn from_be_slice() { + let bytes = hex!("00112233445566778899aabbccddeeff"); + let n = UIntEx::from_be_slice(&bytes); + assert_eq!( + n.limbs(), + &[Limb(0x8899aabbccddeeff), Limb(0x0011223344556677)] + ); + } + + #[test] + #[cfg(target_pointer_width = "32")] + fn from_le_slice() { + let bytes = hex!("7766554433221100"); + let n = UIntEx::from_le_slice(&bytes); + assert_eq!(n.limbs(), &[Limb(0x44556677), Limb(0x00112233)]); + } + + #[test] + #[cfg(target_pointer_width = "64")] + fn from_le_slice() { + let bytes = hex!("ffeeddccbbaa99887766554433221100"); + let n = UIntEx::from_le_slice(&bytes); + assert_eq!( + n.limbs(), + &[Limb(0x8899aabbccddeeff), Limb(0x0011223344556677)] + ); + } + + #[test] + #[cfg(target_pointer_width = "32")] + fn from_be_hex() { + let n = UIntEx::from_be_hex("0011223344556677"); + assert_eq!(n.limbs(), &[Limb(0x44556677), Limb(0x00112233)]); + } + + #[test] + #[cfg(target_pointer_width = "64")] + fn from_be_hex() { + let n = UIntEx::from_be_hex("00112233445566778899aabbccddeeff"); + assert_eq!( + n.limbs(), + &[Limb(0x8899aabbccddeeff), Limb(0x0011223344556677)] + ); + } + + #[test] + #[cfg(target_pointer_width = "32")] + fn from_le_hex() { + let n = UIntEx::from_le_hex("7766554433221100"); + assert_eq!(n.limbs(), &[Limb(0x44556677), Limb(0x00112233)]); + } + + #[test] + #[cfg(target_pointer_width = "64")] + fn from_le_hex() { + let n = UIntEx::from_le_hex("ffeeddccbbaa99887766554433221100"); + assert_eq!( + n.limbs(), + &[Limb(0x8899aabbccddeeff), Limb(0x0011223344556677)] + ); + } + + #[cfg(feature = "alloc")] + #[test] + fn hex_upper() { + let hex = "AAAAAAAABBBBBBBBCCCCCCCCDDDDDDDD"; + let n = U128::from_be_hex(hex); + assert_eq!(hex, format!("{:X}", n)); + } + + #[cfg(feature = "alloc")] + #[test] + fn hex_lower() { + let hex = "aaaaaaaabbbbbbbbccccccccdddddddd"; + let n = U128::from_be_hex(hex); + assert_eq!(hex, format!("{:x}", n)); + } +} diff --git a/vendor/crypto-bigint/src/uint/encoding/der.rs b/vendor/crypto-bigint/src/uint/encoding/der.rs new file mode 100644 index 000000000..cf1b9c31e --- /dev/null +++ b/vendor/crypto-bigint/src/uint/encoding/der.rs @@ -0,0 +1,69 @@ +//! Support for decoding/encoding [`UInt`] as an ASN.1 DER `INTEGER`. + +use crate::{generic_array::GenericArray, ArrayEncoding, UInt}; +use ::der::{ + asn1::{AnyRef, UIntRef}, + DecodeValue, EncodeValue, FixedTag, Length, Tag, +}; + +#[cfg_attr(docsrs, doc(cfg(feature = "der")))] +impl<'a, const LIMBS: usize> TryFrom> for UInt +where + UInt: ArrayEncoding, +{ + type Error = der::Error; + + fn try_from(any: AnyRef<'a>) -> der::Result> { + UIntRef::try_from(any)?.try_into() + } +} + +#[cfg_attr(docsrs, doc(cfg(feature = "der")))] +impl<'a, const LIMBS: usize> TryFrom> for UInt +where + UInt: ArrayEncoding, +{ + type Error = der::Error; + + fn try_from(bytes: UIntRef<'a>) -> der::Result> { + let mut array = GenericArray::default(); + let offset = array.len().saturating_sub(bytes.len().try_into()?); + array[offset..].copy_from_slice(bytes.as_bytes()); + Ok(UInt::from_be_byte_array(array)) + } +} + +#[cfg_attr(docsrs, doc(cfg(feature = "der")))] +impl<'a, const LIMBS: usize> DecodeValue<'a> for UInt +where + UInt: ArrayEncoding, +{ + fn decode_value>(reader: &mut R, header: der::Header) -> der::Result { + UIntRef::decode_value(reader, header)?.try_into() + } +} + +#[cfg_attr(docsrs, doc(cfg(feature = "der")))] +impl EncodeValue for UInt +where + UInt: ArrayEncoding, +{ + fn value_len(&self) -> der::Result { + // TODO(tarcieri): more efficient length calculation + let array = self.to_be_byte_array(); + UIntRef::new(&array)?.value_len() + } + + fn encode_value(&self, encoder: &mut dyn der::Writer) -> der::Result<()> { + let array = self.to_be_byte_array(); + UIntRef::new(&array)?.encode_value(encoder) + } +} + +#[cfg_attr(docsrs, doc(cfg(feature = "der")))] +impl FixedTag for UInt +where + UInt: ArrayEncoding, +{ + const TAG: Tag = Tag::Integer; +} diff --git a/vendor/crypto-bigint/src/uint/encoding/rlp.rs b/vendor/crypto-bigint/src/uint/encoding/rlp.rs new file mode 100644 index 000000000..8a10170d5 --- /dev/null +++ b/vendor/crypto-bigint/src/uint/encoding/rlp.rs @@ -0,0 +1,79 @@ +//! Recursive Length Prefix (RLP) encoding support. + +use crate::{Encoding, UInt}; +use rlp::{DecoderError, Rlp, RlpStream}; + +#[cfg_attr(docsrs, doc(cfg(feature = "rlp")))] +impl rlp::Encodable for UInt +where + Self: Encoding, +{ + fn rlp_append(&self, stream: &mut RlpStream) { + let bytes = self.to_be_bytes(); + let mut bytes_stripped = bytes.as_ref(); + + while bytes_stripped.first().cloned() == Some(0) { + bytes_stripped = &bytes_stripped[1..]; + } + + stream.encoder().encode_value(bytes_stripped); + } +} + +#[cfg_attr(docsrs, doc(cfg(feature = "rlp")))] +impl rlp::Decodable for UInt +where + Self: Encoding, + ::Repr: Default, +{ + fn decode(rlp: &Rlp<'_>) -> Result { + rlp.decoder().decode_value(|bytes| { + if bytes.first().cloned() == Some(0) { + Err(rlp::DecoderError::RlpInvalidIndirection) + } else { + let mut repr = ::Repr::default(); + let offset = repr + .as_ref() + .len() + .checked_sub(bytes.len()) + .ok_or(DecoderError::RlpIsTooBig)?; + + repr.as_mut()[offset..].copy_from_slice(bytes); + Ok(Self::from_be_bytes(repr)) + } + }) + } +} + +#[cfg(test)] +mod tests { + use crate::U256; + use hex_literal::hex; + + /// U256 test vectors from the `rlp` crate. + /// + /// + const U256_VECTORS: &[(U256, &[u8])] = &[ + (U256::ZERO, &hex!("80")), + ( + U256::from_be_hex("0000000000000000000000000000000000000000000000000000000001000000"), + &hex!("8401000000"), + ), + ( + U256::from_be_hex("00000000000000000000000000000000000000000000000000000000ffffffff"), + &hex!("84ffffffff"), + ), + ( + U256::from_be_hex("8090a0b0c0d0e0f00910203040506077000000000000000100000000000012f0"), + &hex!("a08090a0b0c0d0e0f00910203040506077000000000000000100000000000012f0"), + ), + ]; + + #[test] + fn round_trip() { + for &(uint, expected_bytes) in U256_VECTORS { + assert_eq!(rlp::encode(&uint), expected_bytes); + assert_eq!(rlp::decode::(expected_bytes).unwrap(), uint); + } + } +} diff --git a/vendor/crypto-bigint/src/uint/from.rs b/vendor/crypto-bigint/src/uint/from.rs new file mode 100644 index 000000000..daa5b7092 --- /dev/null +++ b/vendor/crypto-bigint/src/uint/from.rs @@ -0,0 +1,238 @@ +//! `From`-like conversions for [`UInt`]. + +use crate::{Limb, UInt, WideWord, Word, U128, U64}; + +impl UInt { + /// Create a [`UInt`] from a `u8` (const-friendly) + // TODO(tarcieri): replace with `const impl From` when stable + pub const fn from_u8(n: u8) -> Self { + assert!(LIMBS >= 1, "number of limbs must be greater than zero"); + let mut limbs = [Limb::ZERO; LIMBS]; + limbs[0].0 = n as Word; + Self { limbs } + } + + /// Create a [`UInt`] from a `u16` (const-friendly) + // TODO(tarcieri): replace with `const impl From` when stable + pub const fn from_u16(n: u16) -> Self { + assert!(LIMBS >= 1, "number of limbs must be greater than zero"); + let mut limbs = [Limb::ZERO; LIMBS]; + limbs[0].0 = n as Word; + Self { limbs } + } + + /// Create a [`UInt`] from a `u32` (const-friendly) + // TODO(tarcieri): replace with `const impl From` when stable + #[allow(trivial_numeric_casts)] + pub const fn from_u32(n: u32) -> Self { + assert!(LIMBS >= 1, "number of limbs must be greater than zero"); + let mut limbs = [Limb::ZERO; LIMBS]; + limbs[0].0 = n as Word; + Self { limbs } + } + + /// Create a [`UInt`] from a `u64` (const-friendly) + // TODO(tarcieri): replace with `const impl From` when stable + #[cfg(target_pointer_width = "32")] + pub const fn from_u64(n: u64) -> Self { + assert!(LIMBS >= 2, "number of limbs must be two or greater"); + let mut limbs = [Limb::ZERO; LIMBS]; + limbs[0].0 = (n & 0xFFFFFFFF) as u32; + limbs[1].0 = (n >> 32) as u32; + Self { limbs } + } + + /// Create a [`UInt`] from a `u64` (const-friendly) + // TODO(tarcieri): replace with `const impl From` when stable + #[cfg(target_pointer_width = "64")] + pub const fn from_u64(n: u64) -> Self { + assert!(LIMBS >= 1, "number of limbs must be greater than zero"); + let mut limbs = [Limb::ZERO; LIMBS]; + limbs[0].0 = n; + Self { limbs } + } + + /// Create a [`UInt`] from a `u128` (const-friendly) + // TODO(tarcieri): replace with `const impl From` when stable + pub const fn from_u128(n: u128) -> Self { + assert!( + LIMBS >= (128 / Limb::BIT_SIZE), + "number of limbs must be greater than zero" + ); + + let lo = U64::from_u64((n & 0xffff_ffff_ffff_ffff) as u64); + let hi = U64::from_u64((n >> 64) as u64); + + let mut limbs = [Limb::ZERO; LIMBS]; + + let mut i = 0; + while i < lo.limbs.len() { + limbs[i] = lo.limbs[i]; + i += 1; + } + + let mut j = 0; + while j < hi.limbs.len() { + limbs[i + j] = hi.limbs[j]; + j += 1; + } + + Self { limbs } + } + + /// Create a [`UInt`] from a `Word` (const-friendly) + // TODO(tarcieri): replace with `const impl From` when stable + pub const fn from_word(n: Word) -> Self { + assert!(LIMBS >= 1, "number of limbs must be greater than zero"); + let mut limbs = [Limb::ZERO; LIMBS]; + limbs[0].0 = n; + Self { limbs } + } + + /// Create a [`UInt`] from a `WideWord` (const-friendly) + // TODO(tarcieri): replace with `const impl From` when stable + pub const fn from_wide_word(n: WideWord) -> Self { + assert!(LIMBS >= 2, "number of limbs must be two or greater"); + let mut limbs = [Limb::ZERO; LIMBS]; + limbs[0].0 = n as Word; + limbs[1].0 = (n >> Limb::BIT_SIZE) as Word; + Self { limbs } + } +} + +impl From for UInt { + fn from(n: u8) -> Self { + // TODO(tarcieri): const where clause when possible + debug_assert!(LIMBS > 0, "limbs must be non-zero"); + Self::from_u8(n) + } +} + +impl From for UInt { + fn from(n: u16) -> Self { + // TODO(tarcieri): const where clause when possible + debug_assert!(LIMBS > 0, "limbs must be non-zero"); + Self::from_u16(n) + } +} + +impl From for UInt { + fn from(n: u32) -> Self { + // TODO(tarcieri): const where clause when possible + debug_assert!(LIMBS > 0, "limbs must be non-zero"); + Self::from_u32(n) + } +} + +impl From for UInt { + fn from(n: u64) -> Self { + // TODO(tarcieri): const where clause when possible + debug_assert!(LIMBS >= (64 / Limb::BIT_SIZE), "not enough limbs"); + Self::from_u64(n) + } +} + +impl From for UInt { + fn from(n: u128) -> Self { + // TODO(tarcieri): const where clause when possible + debug_assert!(LIMBS >= (128 / Limb::BIT_SIZE), "not enough limbs"); + Self::from_u128(n) + } +} + +#[cfg(target_pointer_width = "32")] +#[cfg_attr(docsrs, doc(cfg(target_pointer_width = "32")))] +impl From for u64 { + fn from(n: U64) -> u64 { + (n.limbs[0].0 as u64) | ((n.limbs[1].0 as u64) << 32) + } +} + +#[cfg(target_pointer_width = "64")] +#[cfg_attr(docsrs, doc(cfg(target_pointer_width = "64")))] +impl From for u64 { + fn from(n: U64) -> u64 { + n.limbs[0].into() + } +} + +impl From for u128 { + fn from(n: U128) -> u128 { + let (hi, lo) = n.split(); + (u64::from(hi) as u128) << 64 | (u64::from(lo) as u128) + } +} + +impl From<[Word; LIMBS]> for UInt { + fn from(arr: [Word; LIMBS]) -> Self { + Self::from_words(arr) + } +} + +impl From> for [Word; LIMBS] { + fn from(n: UInt) -> [Word; LIMBS] { + *n.as_ref() + } +} + +impl From<[Limb; LIMBS]> for UInt { + fn from(limbs: [Limb; LIMBS]) -> Self { + Self { limbs } + } +} + +impl From> for [Limb; LIMBS] { + fn from(n: UInt) -> [Limb; LIMBS] { + n.limbs + } +} + +impl From for UInt { + fn from(limb: Limb) -> Self { + limb.0.into() + } +} + +#[cfg(test)] +mod tests { + use crate::{Limb, Word, U128}; + + #[cfg(target_pointer_width = "32")] + use crate::U64 as UIntEx; + + #[cfg(target_pointer_width = "64")] + use crate::U128 as UIntEx; + + #[test] + fn from_u8() { + let n = UIntEx::from(42u8); + assert_eq!(n.limbs(), &[Limb(42), Limb(0)]); + } + + #[test] + fn from_u16() { + let n = UIntEx::from(42u16); + assert_eq!(n.limbs(), &[Limb(42), Limb(0)]); + } + + #[test] + fn from_u64() { + let n = UIntEx::from(42u64); + assert_eq!(n.limbs(), &[Limb(42), Limb(0)]); + } + + #[test] + fn from_u128() { + let n = U128::from(42u128); + assert_eq!(&n.limbs()[..2], &[Limb(42), Limb(0)]); + assert_eq!(u128::from(n), 42u128); + } + + #[test] + fn array_round_trip() { + let arr1 = [1, 2]; + let n = UIntEx::from(arr1); + let arr2: [Word; 2] = n.into(); + assert_eq!(arr1, arr2); + } +} diff --git a/vendor/crypto-bigint/src/uint/inv_mod.rs b/vendor/crypto-bigint/src/uint/inv_mod.rs new file mode 100644 index 000000000..a11408564 --- /dev/null +++ b/vendor/crypto-bigint/src/uint/inv_mod.rs @@ -0,0 +1,62 @@ +use super::UInt; +use crate::Limb; + +impl UInt { + /// Computes 1/`self` mod 2^k as specified in Algorithm 4 from + /// A Secure Algorithm for Inversion Modulo 2k by + /// Sadiel de la Fe and Carles Ferrer. See + /// . + /// + /// Conditions: `self` < 2^k and `self` must be odd + pub const fn inv_mod2k(&self, k: usize) -> Self { + let mut x = Self::ZERO; + let mut b = Self::ONE; + let mut i = 0; + + while i < k { + let mut x_i = Self::ZERO; + let j = b.limbs[0].0 & 1; + x_i.limbs[0] = Limb(j); + x = x.bitor(&x_i.shl_vartime(i)); + + let t = b.wrapping_sub(self); + b = Self::ct_select(b, t, j.wrapping_neg()).shr_vartime(1); + i += 1; + } + x + } +} + +#[cfg(test)] +mod tests { + use crate::U256; + + #[test] + fn inv_mod2k() { + let v = U256::from_be_slice(&[ + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, + 0xff, 0xff, 0xfc, 0x2f, + ]); + let e = U256::from_be_slice(&[ + 0x36, 0x42, 0xe6, 0xfa, 0xea, 0xac, 0x7c, 0x66, 0x63, 0xb9, 0x3d, 0x3d, 0x6a, 0x0d, + 0x48, 0x9e, 0x43, 0x4d, 0xdc, 0x01, 0x23, 0xdb, 0x5f, 0xa6, 0x27, 0xc7, 0xf6, 0xe2, + 0x2d, 0xda, 0xca, 0xcf, + ]); + let a = v.inv_mod2k(256); + assert_eq!(e, a); + + let v = U256::from_be_slice(&[ + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xfe, 0xba, 0xae, 0xdc, 0xe6, 0xaf, 0x48, 0xa0, 0x3b, 0xbf, 0xd2, 0x5e, 0x8c, + 0xd0, 0x36, 0x41, 0x41, + ]); + let e = U256::from_be_slice(&[ + 0x26, 0x17, 0x76, 0xf2, 0x9b, 0x6b, 0x10, 0x6c, 0x76, 0x80, 0xcf, 0x3e, 0xd8, 0x30, + 0x54, 0xa1, 0xaf, 0x5a, 0xe5, 0x37, 0xcb, 0x46, 0x13, 0xdb, 0xb4, 0xf2, 0x00, 0x99, + 0xaa, 0x77, 0x4e, 0xc1, + ]); + let a = v.inv_mod2k(256); + assert_eq!(e, a); + } +} diff --git a/vendor/crypto-bigint/src/uint/mul.rs b/vendor/crypto-bigint/src/uint/mul.rs new file mode 100644 index 000000000..ecb32fd10 --- /dev/null +++ b/vendor/crypto-bigint/src/uint/mul.rs @@ -0,0 +1,246 @@ +//! [`UInt`] addition operations. + +use crate::{Checked, CheckedMul, Concat, Limb, UInt, Wrapping, Zero}; +use core::ops::{Mul, MulAssign}; +use subtle::CtOption; + +impl UInt { + /// Compute "wide" multiplication, with a product twice the size of the input. + /// + /// Returns a tuple containing the `(lo, hi)` components of the product. + /// + /// # Ordering note + /// + /// Releases of `crypto-bigint` prior to v0.3 used `(hi, lo)` ordering + /// instead. This has been changed for better consistency with the rest of + /// the APIs in this crate. + /// + /// For more info see: + // TODO(tarcieri): use `concat` to construct a wide output + pub const fn mul_wide(&self, rhs: &Self) -> (Self, Self) { + let mut i = 0; + let mut lo = Self::ZERO; + let mut hi = Self::ZERO; + + // Schoolbook multiplication. + // TODO(tarcieri): use Karatsuba for better performance? + while i < LIMBS { + let mut j = 0; + let mut carry = Limb::ZERO; + + while j < LIMBS { + let k = i + j; + + if k >= LIMBS { + let (n, c) = hi.limbs[k - LIMBS].mac(self.limbs[i], rhs.limbs[j], carry); + hi.limbs[k - LIMBS] = n; + carry = c; + } else { + let (n, c) = lo.limbs[k].mac(self.limbs[i], rhs.limbs[j], carry); + lo.limbs[k] = n; + carry = c; + } + + j += 1; + } + + hi.limbs[i + j - LIMBS] = carry; + i += 1; + } + + (lo, hi) + } + + /// Perform saturating multiplication, returning `MAX` on overflow. + pub const fn saturating_mul(&self, rhs: &Self) -> Self { + let (res, overflow) = self.mul_wide(rhs); + + let mut i = 0; + let mut accumulator = 0; + + while i < LIMBS { + accumulator |= overflow.limbs[i].0; + i += 1; + } + + if accumulator == 0 { + res + } else { + Self::MAX + } + } + + /// Perform wrapping multiplication, discarding overflow. + pub const fn wrapping_mul(&self, rhs: &Self) -> Self { + self.mul_wide(rhs).0 + } + + /// Square self, returning a "wide" result. + pub fn square(&self) -> ::Output + where + Self: Concat, + { + let (lo, hi) = self.mul_wide(self); + hi.concat(&lo) + } +} + +impl CheckedMul<&UInt> for UInt { + type Output = Self; + + fn checked_mul(&self, rhs: &Self) -> CtOption { + let (lo, hi) = self.mul_wide(rhs); + CtOption::new(lo, hi.is_zero()) + } +} + +impl Mul for Wrapping> { + type Output = Self; + + fn mul(self, rhs: Self) -> Wrapping> { + Wrapping(self.0.wrapping_mul(&rhs.0)) + } +} + +impl Mul<&Wrapping>> for Wrapping> { + type Output = Wrapping>; + + fn mul(self, rhs: &Wrapping>) -> Wrapping> { + Wrapping(self.0.wrapping_mul(&rhs.0)) + } +} + +impl Mul>> for &Wrapping> { + type Output = Wrapping>; + + fn mul(self, rhs: Wrapping>) -> Wrapping> { + Wrapping(self.0.wrapping_mul(&rhs.0)) + } +} + +impl Mul<&Wrapping>> for &Wrapping> { + type Output = Wrapping>; + + fn mul(self, rhs: &Wrapping>) -> Wrapping> { + Wrapping(self.0.wrapping_mul(&rhs.0)) + } +} + +impl MulAssign for Wrapping> { + fn mul_assign(&mut self, other: Self) { + *self = *self * other; + } +} + +impl MulAssign<&Wrapping>> for Wrapping> { + fn mul_assign(&mut self, other: &Self) { + *self = *self * other; + } +} + +impl Mul for Checked> { + type Output = Self; + + fn mul(self, rhs: Self) -> Checked> { + Checked(self.0.and_then(|a| rhs.0.and_then(|b| a.checked_mul(&b)))) + } +} + +impl Mul<&Checked>> for Checked> { + type Output = Checked>; + + fn mul(self, rhs: &Checked>) -> Checked> { + Checked(self.0.and_then(|a| rhs.0.and_then(|b| a.checked_mul(&b)))) + } +} + +impl Mul>> for &Checked> { + type Output = Checked>; + + fn mul(self, rhs: Checked>) -> Checked> { + Checked(self.0.and_then(|a| rhs.0.and_then(|b| a.checked_mul(&b)))) + } +} + +impl Mul<&Checked>> for &Checked> { + type Output = Checked>; + + fn mul(self, rhs: &Checked>) -> Checked> { + Checked(self.0.and_then(|a| rhs.0.and_then(|b| a.checked_mul(&b)))) + } +} + +impl MulAssign for Checked> { + fn mul_assign(&mut self, other: Self) { + *self = *self * other; + } +} + +impl MulAssign<&Checked>> for Checked> { + fn mul_assign(&mut self, other: &Self) { + *self = *self * other; + } +} + +#[cfg(test)] +mod tests { + use crate::{CheckedMul, Zero, U64}; + + #[test] + fn mul_wide_zero_and_one() { + assert_eq!(U64::ZERO.mul_wide(&U64::ZERO), (U64::ZERO, U64::ZERO)); + assert_eq!(U64::ZERO.mul_wide(&U64::ONE), (U64::ZERO, U64::ZERO)); + assert_eq!(U64::ONE.mul_wide(&U64::ZERO), (U64::ZERO, U64::ZERO)); + assert_eq!(U64::ONE.mul_wide(&U64::ONE), (U64::ONE, U64::ZERO)); + } + + #[test] + fn mul_wide_lo_only() { + let primes: &[u32] = &[3, 5, 17, 256, 65537]; + + for &a_int in primes { + for &b_int in primes { + let (lo, hi) = U64::from_u32(a_int).mul_wide(&U64::from_u32(b_int)); + let expected = U64::from_u64(a_int as u64 * b_int as u64); + assert_eq!(lo, expected); + assert!(bool::from(hi.is_zero())); + } + } + } + + #[test] + fn checked_mul_ok() { + let n = U64::from_u32(0xffff_ffff); + assert_eq!( + n.checked_mul(&n).unwrap(), + U64::from_u64(0xffff_fffe_0000_0001) + ); + } + + #[test] + fn checked_mul_overflow() { + let n = U64::from_u64(0xffff_ffff_ffff_ffff); + assert!(bool::from(n.checked_mul(&n).is_none())); + } + + #[test] + fn saturating_mul_no_overflow() { + let n = U64::from_u8(8); + assert_eq!(n.saturating_mul(&n), U64::from_u8(64)); + } + + #[test] + fn saturating_mul_overflow() { + let a = U64::from(0xffff_ffff_ffff_ffffu64); + let b = U64::from(2u8); + assert_eq!(a.saturating_mul(&b), U64::MAX); + } + + #[test] + fn square() { + let n = U64::from_u64(0xffff_ffff_ffff_ffff); + let (hi, lo) = n.square().split(); + assert_eq!(lo, U64::from_u64(1)); + assert_eq!(hi, U64::from_u64(0xffff_ffff_ffff_fffe)); + } +} diff --git a/vendor/crypto-bigint/src/uint/mul_mod.rs b/vendor/crypto-bigint/src/uint/mul_mod.rs new file mode 100644 index 000000000..1e9c053ea --- /dev/null +++ b/vendor/crypto-bigint/src/uint/mul_mod.rs @@ -0,0 +1,131 @@ +//! [`UInt`] multiplication modulus operations. + +use crate::{Limb, UInt, WideWord, Word}; + +impl UInt { + /// Computes `self * rhs mod p` in constant time for the special modulus + /// `p = MAX+1-c` where `c` is small enough to fit in a single [`Limb`]. + /// For the modulus reduction, this function implements Algorithm 14.47 from + /// the "Handbook of Applied Cryptography", by A. Menezes, P. van Oorschot, + /// and S. Vanstone, CRC Press, 1996. + pub const fn mul_mod_special(&self, rhs: &Self, c: Limb) -> Self { + // We implicitly assume `LIMBS > 0`, because `UInt<0>` doesn't compile. + // Still the case `LIMBS == 1` needs special handling. + if LIMBS == 1 { + let prod = self.limbs[0].0 as WideWord * rhs.limbs[0].0 as WideWord; + let reduced = prod % Word::MIN.wrapping_sub(c.0) as WideWord; + return Self::from_word(reduced as Word); + } + + let (lo, hi) = self.mul_wide(rhs); + + // Now use Algorithm 14.47 for the reduction + let (lo, carry) = mac_by_limb(lo, hi, c, Limb::ZERO); + + let (lo, carry) = { + let rhs = (carry.0 + 1) as WideWord * c.0 as WideWord; + lo.adc(&Self::from_wide_word(rhs), Limb::ZERO) + }; + + let (lo, _) = { + let rhs = carry.0.wrapping_sub(1) & c.0; + lo.sbb(&Self::from_word(rhs), Limb::ZERO) + }; + + lo + } +} + +/// Computes `a + (b * c) + carry`, returning the result along with the new carry. +const fn mac_by_limb( + mut a: UInt, + b: UInt, + c: Limb, + mut carry: Limb, +) -> (UInt, Limb) { + let mut i = 0; + + while i < LIMBS { + let (n, c) = a.limbs[i].mac(b.limbs[i], c, carry); + a.limbs[i] = n; + carry = c; + i += 1; + } + + (a, carry) +} + +#[cfg(all(test, feature = "rand"))] +mod tests { + use crate::{Limb, NonZero, Random, RandomMod, UInt}; + use rand_core::SeedableRng; + + macro_rules! test_mul_mod_special { + ($size:expr, $test_name:ident) => { + #[test] + fn $test_name() { + let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(1); + let moduli = [ + NonZero::::random(&mut rng), + NonZero::::random(&mut rng), + ]; + + for special in &moduli { + let p = &NonZero::new(UInt::ZERO.wrapping_sub(&UInt::from_word(special.0))) + .unwrap(); + + let minus_one = p.wrapping_sub(&UInt::ONE); + + let base_cases = [ + (UInt::ZERO, UInt::ZERO, UInt::ZERO), + (UInt::ONE, UInt::ZERO, UInt::ZERO), + (UInt::ZERO, UInt::ONE, UInt::ZERO), + (UInt::ONE, UInt::ONE, UInt::ONE), + (minus_one, minus_one, UInt::ONE), + (minus_one, UInt::ONE, minus_one), + (UInt::ONE, minus_one, minus_one), + ]; + for (a, b, c) in &base_cases { + let x = a.mul_mod_special(&b, *special.as_ref()); + assert_eq!(*c, x, "{} * {} mod {} = {} != {}", a, b, p, x, c); + } + + for _i in 0..100 { + let a = UInt::<$size>::random_mod(&mut rng, p); + let b = UInt::<$size>::random_mod(&mut rng, p); + + let c = a.mul_mod_special(&b, *special.as_ref()); + assert!(c < **p, "not reduced: {} >= {} ", c, p); + + let expected = { + let (lo, hi) = a.mul_wide(&b); + let mut prod = UInt::<{ 2 * $size }>::ZERO; + prod.limbs[..$size].clone_from_slice(&lo.limbs); + prod.limbs[$size..].clone_from_slice(&hi.limbs); + let mut modulus = UInt::ZERO; + modulus.limbs[..$size].clone_from_slice(&p.as_ref().limbs); + let reduced = prod.reduce(&modulus).unwrap(); + let mut expected = UInt::ZERO; + expected.limbs[..].clone_from_slice(&reduced.limbs[..$size]); + expected + }; + assert_eq!(c, expected, "incorrect result"); + } + } + } + }; + } + + test_mul_mod_special!(1, mul_mod_special_1); + test_mul_mod_special!(2, mul_mod_special_2); + test_mul_mod_special!(3, mul_mod_special_3); + test_mul_mod_special!(4, mul_mod_special_4); + test_mul_mod_special!(5, mul_mod_special_5); + test_mul_mod_special!(6, mul_mod_special_6); + test_mul_mod_special!(7, mul_mod_special_7); + test_mul_mod_special!(8, mul_mod_special_8); + test_mul_mod_special!(9, mul_mod_special_9); + test_mul_mod_special!(10, mul_mod_special_10); + test_mul_mod_special!(11, mul_mod_special_11); + test_mul_mod_special!(12, mul_mod_special_12); +} diff --git a/vendor/crypto-bigint/src/uint/neg_mod.rs b/vendor/crypto-bigint/src/uint/neg_mod.rs new file mode 100644 index 000000000..0a1dc033a --- /dev/null +++ b/vendor/crypto-bigint/src/uint/neg_mod.rs @@ -0,0 +1,68 @@ +//! [`UInt`] negation modulus operations. + +use crate::{Limb, NegMod, UInt}; + +impl UInt { + /// Computes `-a mod p` in constant time. + /// Assumes `self` is in `[0, p)`. + pub const fn neg_mod(&self, p: &Self) -> Self { + let z = self.ct_is_nonzero(); + let mut ret = p.sbb(self, Limb::ZERO).0; + let mut i = 0; + while i < LIMBS { + // Set ret to 0 if the original value was 0, in which + // case ret would be p. + ret.limbs[i].0 &= z; + i += 1; + } + ret + } + + /// Computes `-a mod p` in constant time for the special modulus + /// `p = MAX+1-c` where `c` is small enough to fit in a single [`Limb`]. + pub const fn neg_mod_special(&self, c: Limb) -> Self { + Self::ZERO.sub_mod_special(self, c) + } +} + +impl NegMod for UInt { + type Output = Self; + + fn neg_mod(&self, p: &Self) -> Self { + debug_assert!(self < p); + self.neg_mod(p) + } +} + +#[cfg(test)] +mod tests { + use crate::U256; + + #[test] + fn neg_mod_random() { + let x = + U256::from_be_hex("8d16e171674b4e6d8529edba4593802bf30b8cb161dd30aa8e550d41380007c2"); + let p = + U256::from_be_hex("928334a4e4be0843ec225a4c9c61df34bdc7a81513e4b6f76f2bfa3148e2e1b5"); + + let actual = x.neg_mod(&p); + let expected = + U256::from_be_hex("056c53337d72b9d666f86c9256ce5f08cabc1b63b207864ce0d6ecf010e2d9f3"); + + assert_eq!(expected, actual); + } + + #[test] + fn neg_mod_zero() { + let x = + U256::from_be_hex("0000000000000000000000000000000000000000000000000000000000000000"); + let p = + U256::from_be_hex("928334a4e4be0843ec225a4c9c61df34bdc7a81513e4b6f76f2bfa3148e2e1b5"); + + let actual = x.neg_mod(&p); + let expected = + U256::from_be_hex("0000000000000000000000000000000000000000000000000000000000000000"); + + assert_eq!(expected, actual); + } +} diff --git a/vendor/crypto-bigint/src/uint/rand.rs b/vendor/crypto-bigint/src/uint/rand.rs new file mode 100644 index 000000000..df551c71b --- /dev/null +++ b/vendor/crypto-bigint/src/uint/rand.rs @@ -0,0 +1,92 @@ +//! Random number generator support + +use super::UInt; +use crate::{Limb, NonZero, Random, RandomMod}; +use rand_core::{CryptoRng, RngCore}; +use subtle::ConstantTimeLess; + +#[cfg_attr(docsrs, doc(cfg(feature = "rand_core")))] +impl Random for UInt { + /// Generate a cryptographically secure random [`UInt`]. + fn random(mut rng: impl CryptoRng + RngCore) -> Self { + let mut limbs = [Limb::ZERO; LIMBS]; + + for limb in &mut limbs { + *limb = Limb::random(&mut rng) + } + + limbs.into() + } +} + +#[cfg_attr(docsrs, doc(cfg(feature = "rand_core")))] +impl RandomMod for UInt { + /// Generate a cryptographically secure random [`UInt`] which is less than + /// a given `modulus`. + /// + /// This function uses rejection sampling, a method which produces an + /// unbiased distribution of in-range values provided the underlying + /// [`CryptoRng`] is unbiased, but runs in variable-time. + /// + /// The variable-time nature of the algorithm should not pose a security + /// issue so long as the underlying random number generator is truly a + /// [`CryptoRng`], where previous outputs are unrelated to subsequent + /// outputs and do not reveal information about the RNG's internal state. + fn random_mod(mut rng: impl CryptoRng + RngCore, modulus: &NonZero) -> Self { + let mut n = Self::ZERO; + + // TODO(tarcieri): use `div_ceil` when available + // See: https://github.com/rust-lang/rust/issues/88581 + let mut n_limbs = modulus.bits_vartime() / Limb::BIT_SIZE; + if n_limbs < LIMBS { + n_limbs += 1; + } + + // Compute the highest limb of `modulus` as a `NonZero`. + // Add one to ensure `Limb::random_mod` returns values inclusive of this limb. + let modulus_hi = + NonZero::new(modulus.limbs[n_limbs.saturating_sub(1)].saturating_add(Limb::ONE)) + .unwrap(); // Always at least one due to `saturating_add` + + loop { + for i in 0..n_limbs { + n.limbs[i] = if (i + 1 == n_limbs) && (*modulus_hi != Limb::MAX) { + // Highest limb + Limb::random_mod(&mut rng, &modulus_hi) + } else { + Limb::random(&mut rng) + } + } + + if n.ct_lt(modulus).into() { + return n; + } + } + } +} + +#[cfg(test)] +mod tests { + use crate::{NonZero, RandomMod, U256}; + use rand_core::SeedableRng; + + #[test] + fn random_mod() { + let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(1); + + // Ensure `random_mod` runs in a reasonable amount of time + let modulus = NonZero::new(U256::from(42u8)).unwrap(); + let res = U256::random_mod(&mut rng, &modulus); + + // Sanity check that the return value isn't zero + assert_ne!(res, U256::ZERO); + + // Ensure `random_mod` runs in a reasonable amount of time + // when the modulus is larger than 1 limb + let modulus = NonZero::new(U256::from(0x10000000000000001u128)).unwrap(); + let res = U256::random_mod(&mut rng, &modulus); + + // Sanity check that the return value isn't zero + assert_ne!(res, U256::ZERO); + } +} diff --git a/vendor/crypto-bigint/src/uint/resize.rs b/vendor/crypto-bigint/src/uint/resize.rs new file mode 100644 index 000000000..5a5ec7eef --- /dev/null +++ b/vendor/crypto-bigint/src/uint/resize.rs @@ -0,0 +1,37 @@ +use super::UInt; + +impl UInt { + /// Construct a `UInt` from the unsigned integer value, + /// truncating the upper bits if the value is too large to be + /// represented. + #[inline(always)] + pub const fn resize(&self) -> UInt { + let mut res = UInt::ZERO; + let mut i = 0; + let dim = if T < LIMBS { T } else { LIMBS }; + while i < dim { + res.limbs[i] = self.limbs[i]; + i += 1; + } + res + } +} + +#[cfg(test)] +mod tests { + use crate::{U128, U64}; + + #[test] + fn resize_larger() { + let u = U64::from_be_hex("AAAAAAAABBBBBBBB"); + let u2: U128 = u.resize(); + assert_eq!(u2, U128::from_be_hex("0000000000000000AAAAAAAABBBBBBBB")); + } + + #[test] + fn resize_smaller() { + let u = U128::from_be_hex("AAAAAAAABBBBBBBBCCCCCCCCDDDDDDDD"); + let u2: U64 = u.resize(); + assert_eq!(u2, U64::from_be_hex("CCCCCCCCDDDDDDDD")); + } +} diff --git a/vendor/crypto-bigint/src/uint/shl.rs b/vendor/crypto-bigint/src/uint/shl.rs new file mode 100644 index 000000000..9d4669130 --- /dev/null +++ b/vendor/crypto-bigint/src/uint/shl.rs @@ -0,0 +1,134 @@ +//! [`UInt`] bitwise left shift operations. + +use crate::{Limb, UInt, Word}; +use core::ops::{Shl, ShlAssign}; + +impl UInt { + /// Computes `self << shift`. + /// + /// NOTE: this operation is variable time with respect to `n` *ONLY*. + /// + /// When used with a fixed `n`, this function is constant-time with respect + /// to `self`. + #[inline(always)] + pub const fn shl_vartime(&self, n: usize) -> Self { + let mut limbs = [Limb::ZERO; LIMBS]; + + if n >= Limb::BIT_SIZE * LIMBS { + return Self { limbs }; + } + + let shift_num = n / Limb::BIT_SIZE; + let rem = n % Limb::BIT_SIZE; + let nz = Limb(rem as Word).is_nonzero(); + let lshift_rem = rem as Word; + let rshift_rem = Limb::ct_select(Limb::ZERO, Limb((Limb::BIT_SIZE - rem) as Word), nz).0; + + let mut i = LIMBS - 1; + while i > shift_num { + let mut limb = self.limbs[i - shift_num].0 << lshift_rem; + let hi = self.limbs[i - shift_num - 1].0 >> rshift_rem; + limb |= hi & nz; + limbs[i] = Limb(limb); + i -= 1 + } + limbs[shift_num] = Limb(self.limbs[0].0 << lshift_rem); + + Self { limbs } + } +} + +impl Shl for UInt { + type Output = UInt; + + /// NOTE: this operation is variable time with respect to `rhs` *ONLY*. + /// + /// When used with a fixed `rhs`, this function is constant-time with respect + /// to `self`. + fn shl(self, rhs: usize) -> UInt { + self.shl_vartime(rhs) + } +} + +impl Shl for &UInt { + type Output = UInt; + + /// NOTE: this operation is variable time with respect to `rhs` *ONLY*. + /// + /// When used with a fixed `rhs`, this function is constant-time with respect + /// to `self`. + fn shl(self, rhs: usize) -> UInt { + self.shl_vartime(rhs) + } +} + +impl ShlAssign for UInt { + /// NOTE: this operation is variable time with respect to `rhs` *ONLY*. + /// + /// When used with a fixed `rhs`, this function is constant-time with respect + /// to `self`. + fn shl_assign(&mut self, rhs: usize) { + *self = self.shl_vartime(rhs) + } +} + +#[cfg(test)] +mod tests { + use crate::U256; + + const N: U256 = + U256::from_be_hex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141"); + + const TWO_N: U256 = + U256::from_be_hex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFD755DB9CD5E9140777FA4BD19A06C8282"); + + const FOUR_N: U256 = + U256::from_be_hex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFAEABB739ABD2280EEFF497A3340D90504"); + + const SIXTY_FIVE: U256 = + U256::from_be_hex("FFFFFFFFFFFFFFFD755DB9CD5E9140777FA4BD19A06C82820000000000000000"); + + const EIGHTY_EIGHT: U256 = + U256::from_be_hex("FFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD03641410000000000000000000000"); + + const SIXTY_FOUR: U256 = + U256::from_be_hex("FFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD03641410000000000000000"); + + #[test] + fn shl_simple() { + let mut t = U256::from(1u8); + assert_eq!(t << 1, U256::from(2u8)); + t = U256::from(3u8); + assert_eq!(t << 8, U256::from(0x300u16)); + } + + #[test] + fn shl1() { + assert_eq!(N << 1, TWO_N); + } + + #[test] + fn shl2() { + assert_eq!(N << 2, FOUR_N); + } + + #[test] + fn shl65() { + assert_eq!(N << 65, SIXTY_FIVE); + } + + #[test] + fn shl88() { + assert_eq!(N << 88, EIGHTY_EIGHT); + } + + #[test] + fn shl256() { + assert_eq!(N << 256, U256::default()); + } + + #[test] + fn shl64() { + assert_eq!(N << 64, SIXTY_FOUR); + } +} diff --git a/vendor/crypto-bigint/src/uint/shr.rs b/vendor/crypto-bigint/src/uint/shr.rs new file mode 100644 index 000000000..54375ae72 --- /dev/null +++ b/vendor/crypto-bigint/src/uint/shr.rs @@ -0,0 +1,93 @@ +//! [`UInt`] bitwise right shift operations. + +use super::UInt; +use crate::Limb; +use core::ops::{Shr, ShrAssign}; + +impl UInt { + /// Computes `self >> n`. + /// + /// NOTE: this operation is variable time with respect to `n` *ONLY*. + /// + /// When used with a fixed `n`, this function is constant-time with respect + /// to `self`. + #[inline(always)] + pub const fn shr_vartime(&self, shift: usize) -> Self { + let full_shifts = shift / Limb::BIT_SIZE; + let small_shift = shift & (Limb::BIT_SIZE - 1); + let mut limbs = [Limb::ZERO; LIMBS]; + + if shift > Limb::BIT_SIZE * LIMBS { + return Self { limbs }; + } + + let n = LIMBS - full_shifts; + let mut i = 0; + + if small_shift == 0 { + while i < n { + limbs[i] = Limb(self.limbs[i + full_shifts].0); + i += 1; + } + } else { + while i < n { + let mut lo = self.limbs[i + full_shifts].0 >> small_shift; + + if i < (LIMBS - 1) - full_shifts { + lo |= self.limbs[i + full_shifts + 1].0 << (Limb::BIT_SIZE - small_shift); + } + + limbs[i] = Limb(lo); + i += 1; + } + } + + Self { limbs } + } +} + +impl Shr for UInt { + type Output = UInt; + + /// NOTE: this operation is variable time with respect to `rhs` *ONLY*. + /// + /// When used with a fixed `rhs`, this function is constant-time with respect + /// to `self`. + fn shr(self, rhs: usize) -> UInt { + self.shr_vartime(rhs) + } +} + +impl Shr for &UInt { + type Output = UInt; + + /// NOTE: this operation is variable time with respect to `rhs` *ONLY*. + /// + /// When used with a fixed `rhs`, this function is constant-time with respect + /// to `self`. + fn shr(self, rhs: usize) -> UInt { + self.shr_vartime(rhs) + } +} + +impl ShrAssign for UInt { + fn shr_assign(&mut self, rhs: usize) { + *self = self.shr_vartime(rhs); + } +} + +#[cfg(test)] +mod tests { + use crate::U256; + + const N: U256 = + U256::from_be_hex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141"); + + const N_2: U256 = + U256::from_be_hex("7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0"); + + #[test] + fn shr1() { + assert_eq!(N >> 1, N_2); + } +} diff --git a/vendor/crypto-bigint/src/uint/split.rs b/vendor/crypto-bigint/src/uint/split.rs new file mode 100644 index 000000000..ecff9d6d8 --- /dev/null +++ b/vendor/crypto-bigint/src/uint/split.rs @@ -0,0 +1,58 @@ +// TODO(tarcieri): use `const_evaluatable_checked` when stable to make generic around bits. +macro_rules! impl_split { + ($(($name:ident, $bits:expr)),+) => { + $( + impl $name { + /// Split this number in half, returning its high and low components + /// respectively. + pub const fn split(&self) -> (UInt<{nlimbs!($bits) / 2}>, UInt<{nlimbs!($bits) / 2}>) { + let mut lo = [Limb::ZERO; nlimbs!($bits) / 2]; + let mut hi = [Limb::ZERO; nlimbs!($bits) / 2]; + let mut i = 0; + let mut j = 0; + + while j < (nlimbs!($bits) / 2) { + lo[j] = self.limbs[i]; + i += 1; + j += 1; + } + + j = 0; + while j < (nlimbs!($bits) / 2) { + hi[j] = self.limbs[i]; + i += 1; + j += 1; + } + + (UInt { limbs: hi }, UInt { limbs: lo }) + } + } + + impl Split for $name { + type Output = UInt<{nlimbs!($bits) / 2}>; + + fn split(&self) -> (Self::Output, Self::Output) { + self.split() + } + } + + impl From<$name> for (UInt<{nlimbs!($bits) / 2}>, UInt<{nlimbs!($bits) / 2}>) { + fn from(num: $name) -> (UInt<{nlimbs!($bits) / 2}>, UInt<{nlimbs!($bits) / 2}>) { + num.split() + } + } + )+ + }; +} + +#[cfg(test)] +mod tests { + use crate::{U128, U64}; + + #[test] + fn split() { + let (hi, lo) = U128::from_be_hex("00112233445566778899aabbccddeeff").split(); + assert_eq!(hi, U64::from_u64(0x0011223344556677)); + assert_eq!(lo, U64::from_u64(0x8899aabbccddeeff)); + } +} diff --git a/vendor/crypto-bigint/src/uint/sqrt.rs b/vendor/crypto-bigint/src/uint/sqrt.rs new file mode 100644 index 000000000..4a9f26a61 --- /dev/null +++ b/vendor/crypto-bigint/src/uint/sqrt.rs @@ -0,0 +1,145 @@ +//! [`UInt`] square root operations. + +use super::UInt; +use crate::{Limb, Word}; +use subtle::{ConstantTimeEq, CtOption}; + +impl UInt { + /// Computes √(`self`) + /// Uses Brent & Zimmermann, Modern Computer Arithmetic, v0.5.9, Algorithm 1.13 + /// + /// Callers can check if `self` is a square by squaring the result + pub const fn sqrt(&self) -> Self { + let max_bits = (self.bits_vartime() + 1) >> 1; + let cap = Self::ONE.shl_vartime(max_bits); + let mut guess = cap; // ≥ √(`self`) + let mut xn = { + let q = self.wrapping_div(&guess); + let t = guess.wrapping_add(&q); + t.shr_vartime(1) + }; + + // If guess increased, the initial guess was low. + // Repeat until reverse course. + while guess.ct_cmp(&xn) == -1 { + // Sometimes an increase is too far, especially with large + // powers, and then takes a long time to walk back. The upper + // bound is based on bit size, so saturate on that. + let res = Limb::ct_cmp(Limb(xn.bits_vartime() as Word), Limb(max_bits as Word)) - 1; + let le = Limb::is_nonzero(Limb(res as Word)); + guess = Self::ct_select(cap, xn, le); + xn = { + let q = self.wrapping_div(&guess); + let t = guess.wrapping_add(&q); + t.shr_vartime(1) + }; + } + + // Repeat while guess decreases. + while guess.ct_cmp(&xn) == 1 && xn.ct_is_nonzero() == Word::MAX { + guess = xn; + xn = { + let q = self.wrapping_div(&guess); + let t = guess.wrapping_add(&q); + t.shr_vartime(1) + }; + } + + Self::ct_select(Self::ZERO, guess, self.ct_is_nonzero()) + } + + /// Wrapped sqrt is just normal √(`self`) + /// There’s no way wrapping could ever happen. + /// This function exists, so that all operations are accounted for in the wrapping operations. + pub const fn wrapping_sqrt(&self) -> Self { + self.sqrt() + } + + /// Perform checked sqrt, returning a [`CtOption`] which `is_some` + /// only if the √(`self`)² == self + pub fn checked_sqrt(&self) -> CtOption { + let r = self.sqrt(); + let s = r.wrapping_mul(&r); + CtOption::new(r, self.ct_eq(&s)) + } +} + +#[cfg(test)] +mod tests { + use crate::{Limb, U256}; + + #[cfg(feature = "rand")] + use { + crate::{CheckedMul, Random, U512}, + rand_chacha::ChaChaRng, + rand_core::{RngCore, SeedableRng}, + }; + + #[test] + fn edge() { + assert_eq!(U256::ZERO.sqrt(), U256::ZERO); + assert_eq!(U256::ONE.sqrt(), U256::ONE); + let mut half = U256::ZERO; + for i in 0..half.limbs.len() / 2 { + half.limbs[i] = Limb::MAX; + } + assert_eq!(U256::MAX.sqrt(), half,); + } + + #[test] + fn simple() { + let tests = [ + (4u8, 2u8), + (9, 3), + (16, 4), + (25, 5), + (36, 6), + (49, 7), + (64, 8), + (81, 9), + (100, 10), + (121, 11), + (144, 12), + (169, 13), + ]; + for (a, e) in &tests { + let l = U256::from(*a); + let r = U256::from(*e); + assert_eq!(l.sqrt(), r); + assert_eq!(l.checked_sqrt().is_some().unwrap_u8(), 1u8); + } + } + + #[test] + fn nonsquares() { + assert_eq!(U256::from(2u8).sqrt(), U256::from(1u8)); + assert_eq!(U256::from(2u8).checked_sqrt().is_some().unwrap_u8(), 0); + assert_eq!(U256::from(3u8).sqrt(), U256::from(1u8)); + assert_eq!(U256::from(3u8).checked_sqrt().is_some().unwrap_u8(), 0); + assert_eq!(U256::from(5u8).sqrt(), U256::from(2u8)); + assert_eq!(U256::from(6u8).sqrt(), U256::from(2u8)); + assert_eq!(U256::from(7u8).sqrt(), U256::from(2u8)); + assert_eq!(U256::from(8u8).sqrt(), U256::from(2u8)); + assert_eq!(U256::from(10u8).sqrt(), U256::from(3u8)); + } + + #[cfg(feature = "rand")] + #[test] + fn fuzz() { + let mut rng = ChaChaRng::from_seed([7u8; 32]); + for _ in 0..50 { + let t = rng.next_u32() as u64; + let s = U256::from(t); + let s2 = s.checked_mul(&s).unwrap(); + assert_eq!(s2.sqrt(), s); + assert_eq!(s2.checked_sqrt().is_some().unwrap_u8(), 1); + } + + for _ in 0..50 { + let s = U256::random(&mut rng); + let mut s2 = U512::ZERO; + s2.limbs[..s.limbs.len()].copy_from_slice(&s.limbs); + assert_eq!(s.square().sqrt(), s2); + } + } +} diff --git a/vendor/crypto-bigint/src/uint/sub.rs b/vendor/crypto-bigint/src/uint/sub.rs new file mode 100644 index 000000000..102f6b978 --- /dev/null +++ b/vendor/crypto-bigint/src/uint/sub.rs @@ -0,0 +1,192 @@ +//! [`UInt`] addition operations. + +use super::UInt; +use crate::{Checked, CheckedSub, Limb, Wrapping, Zero}; +use core::ops::{Sub, SubAssign}; +use subtle::CtOption; + +impl UInt { + /// Computes `a - (b + borrow)`, returning the result along with the new borrow. + #[inline(always)] + pub const fn sbb(&self, rhs: &Self, mut borrow: Limb) -> (Self, Limb) { + let mut limbs = [Limb::ZERO; LIMBS]; + let mut i = 0; + + while i < LIMBS { + let (w, b) = self.limbs[i].sbb(rhs.limbs[i], borrow); + limbs[i] = w; + borrow = b; + i += 1; + } + + (Self { limbs }, borrow) + } + + /// Perform saturating subtraction, returning `ZERO` on underflow. + pub const fn saturating_sub(&self, rhs: &Self) -> Self { + let (res, underflow) = self.sbb(rhs, Limb::ZERO); + + if underflow.0 == 0 { + res + } else { + Self::ZERO + } + } + + /// Perform wrapping subtraction, discarding underflow and wrapping around + /// the boundary of the type. + pub const fn wrapping_sub(&self, rhs: &Self) -> Self { + self.sbb(rhs, Limb::ZERO).0 + } +} + +impl CheckedSub<&UInt> for UInt { + type Output = Self; + + fn checked_sub(&self, rhs: &Self) -> CtOption { + let (result, underflow) = self.sbb(rhs, Limb::ZERO); + CtOption::new(result, underflow.is_zero()) + } +} + +impl Sub for Wrapping> { + type Output = Self; + + fn sub(self, rhs: Self) -> Wrapping> { + Wrapping(self.0.wrapping_sub(&rhs.0)) + } +} + +impl Sub<&Wrapping>> for Wrapping> { + type Output = Wrapping>; + + fn sub(self, rhs: &Wrapping>) -> Wrapping> { + Wrapping(self.0.wrapping_sub(&rhs.0)) + } +} + +impl Sub>> for &Wrapping> { + type Output = Wrapping>; + + fn sub(self, rhs: Wrapping>) -> Wrapping> { + Wrapping(self.0.wrapping_sub(&rhs.0)) + } +} + +impl Sub<&Wrapping>> for &Wrapping> { + type Output = Wrapping>; + + fn sub(self, rhs: &Wrapping>) -> Wrapping> { + Wrapping(self.0.wrapping_sub(&rhs.0)) + } +} + +impl SubAssign for Wrapping> { + fn sub_assign(&mut self, other: Self) { + *self = *self - other; + } +} + +impl SubAssign<&Wrapping>> for Wrapping> { + fn sub_assign(&mut self, other: &Self) { + *self = *self - other; + } +} + +impl Sub for Checked> { + type Output = Self; + + fn sub(self, rhs: Self) -> Checked> { + Checked( + self.0 + .and_then(|lhs| rhs.0.and_then(|rhs| lhs.checked_sub(&rhs))), + ) + } +} + +impl Sub<&Checked>> for Checked> { + type Output = Checked>; + + fn sub(self, rhs: &Checked>) -> Checked> { + Checked( + self.0 + .and_then(|lhs| rhs.0.and_then(|rhs| lhs.checked_sub(&rhs))), + ) + } +} + +impl Sub>> for &Checked> { + type Output = Checked>; + + fn sub(self, rhs: Checked>) -> Checked> { + Checked( + self.0 + .and_then(|lhs| rhs.0.and_then(|rhs| lhs.checked_sub(&rhs))), + ) + } +} + +impl Sub<&Checked>> for &Checked> { + type Output = Checked>; + + fn sub(self, rhs: &Checked>) -> Checked> { + Checked( + self.0 + .and_then(|lhs| rhs.0.and_then(|rhs| lhs.checked_sub(&rhs))), + ) + } +} + +impl SubAssign for Checked> { + fn sub_assign(&mut self, other: Self) { + *self = *self - other; + } +} + +impl SubAssign<&Checked>> for Checked> { + fn sub_assign(&mut self, other: &Self) { + *self = *self - other; + } +} + +#[cfg(test)] +mod tests { + use crate::{CheckedSub, Limb, U128}; + + #[test] + fn sbb_no_borrow() { + let (res, borrow) = U128::ONE.sbb(&U128::ONE, Limb::ZERO); + assert_eq!(res, U128::ZERO); + assert_eq!(borrow, Limb::ZERO); + } + + #[test] + fn sbb_with_borrow() { + let (res, borrow) = U128::ZERO.sbb(&U128::ONE, Limb::ZERO); + + assert_eq!(res, U128::MAX); + assert_eq!(borrow, Limb::MAX); + } + + #[test] + fn wrapping_sub_no_borrow() { + assert_eq!(U128::ONE.wrapping_sub(&U128::ONE), U128::ZERO); + } + + #[test] + fn wrapping_sub_with_borrow() { + assert_eq!(U128::ZERO.wrapping_sub(&U128::ONE), U128::MAX); + } + + #[test] + fn checked_sub_ok() { + let result = U128::ONE.checked_sub(&U128::ONE); + assert_eq!(result.unwrap(), U128::ZERO); + } + + #[test] + fn checked_sub_overflow() { + let result = U128::ZERO.checked_sub(&U128::ONE); + assert!(!bool::from(result.is_some())); + } +} diff --git a/vendor/crypto-bigint/src/uint/sub_mod.rs b/vendor/crypto-bigint/src/uint/sub_mod.rs new file mode 100644 index 000000000..f699f66eb --- /dev/null +++ b/vendor/crypto-bigint/src/uint/sub_mod.rs @@ -0,0 +1,182 @@ +//! [`UInt`] subtraction modulus operations. + +use crate::{Limb, SubMod, UInt}; + +impl UInt { + /// Computes `self - rhs mod p` in constant time. + /// + /// Assumes `self - rhs` as unbounded signed integer is in `[-p, p)`. + pub const fn sub_mod(&self, rhs: &UInt, p: &UInt) -> UInt { + let (mut out, borrow) = self.sbb(rhs, Limb::ZERO); + + // If underflow occurred on the final limb, borrow = 0xfff...fff, otherwise + // borrow = 0x000...000. Thus, we use it as a mask to conditionally add the modulus. + let mut carry = Limb::ZERO; + let mut i = 0; + + while i < LIMBS { + let (l, c) = out.limbs[i].adc(p.limbs[i].bitand(borrow), carry); + out.limbs[i] = l; + carry = c; + i += 1; + } + + out + } + + /// Computes `self - rhs mod p` in constant time for the special modulus + /// `p = MAX+1-c` where `c` is small enough to fit in a single [`Limb`]. + /// + /// Assumes `self - rhs` as unbounded signed integer is in `[-p, p)`. + pub const fn sub_mod_special(&self, rhs: &Self, c: Limb) -> Self { + let (out, borrow) = self.sbb(rhs, Limb::ZERO); + + // If underflow occurred, then we need to subtract `c` to account for + // the underflow. This cannot underflow due to the assumption + // `self - rhs >= -p`. + let l = borrow.0 & c.0; + let (out, _) = out.sbb(&UInt::from_word(l), Limb::ZERO); + out + } +} + +impl SubMod for UInt { + type Output = Self; + + fn sub_mod(&self, rhs: &Self, p: &Self) -> Self { + debug_assert!(self < p); + debug_assert!(rhs < p); + self.sub_mod(rhs, p) + } +} + +#[cfg(all(test, feature = "rand"))] +mod tests { + use crate::{Limb, NonZero, Random, RandomMod, UInt}; + use rand_core::SeedableRng; + + macro_rules! test_sub_mod { + ($size:expr, $test_name:ident) => { + #[test] + fn $test_name() { + let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(1); + let moduli = [ + NonZero::>::random(&mut rng), + NonZero::>::random(&mut rng), + ]; + + for p in &moduli { + let base_cases = [ + (1u64, 0u64, 1u64.into()), + (0, 1, p.wrapping_sub(&1u64.into())), + (0, 0, 0u64.into()), + ]; + for (a, b, c) in &base_cases { + let a: UInt<$size> = (*a).into(); + let b: UInt<$size> = (*b).into(); + + let x = a.sub_mod(&b, p); + assert_eq!(*c, x, "{} - {} mod {} = {} != {}", a, b, p, x, c); + } + + if $size > 1 { + for _i in 0..100 { + let a: UInt<$size> = Limb::random(&mut rng).into(); + let b: UInt<$size> = Limb::random(&mut rng).into(); + let (a, b) = if a < b { (b, a) } else { (a, b) }; + + let c = a.sub_mod(&b, p); + assert!(c < **p, "not reduced"); + assert_eq!(c, a.wrapping_sub(&b), "result incorrect"); + } + } + + for _i in 0..100 { + let a = UInt::<$size>::random_mod(&mut rng, p); + let b = UInt::<$size>::random_mod(&mut rng, p); + + let c = a.sub_mod(&b, p); + assert!(c < **p, "not reduced: {} >= {} ", c, p); + + let x = a.wrapping_sub(&b); + if a >= b && x < **p { + assert_eq!(c, x, "incorrect result"); + } + } + } + } + }; + } + + macro_rules! test_sub_mod_special { + ($size:expr, $test_name:ident) => { + #[test] + fn $test_name() { + let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(1); + let moduli = [ + NonZero::::random(&mut rng), + NonZero::::random(&mut rng), + ]; + + for special in &moduli { + let p = &NonZero::new(UInt::ZERO.wrapping_sub(&UInt::from_word(special.0))) + .unwrap(); + + let minus_one = p.wrapping_sub(&UInt::ONE); + + let base_cases = [ + (UInt::ZERO, UInt::ZERO, UInt::ZERO), + (UInt::ONE, UInt::ZERO, UInt::ONE), + (UInt::ZERO, UInt::ONE, minus_one), + (minus_one, minus_one, UInt::ZERO), + (UInt::ZERO, minus_one, UInt::ONE), + ]; + for (a, b, c) in &base_cases { + let x = a.sub_mod_special(&b, *special.as_ref()); + assert_eq!(*c, x, "{} - {} mod {} = {} != {}", a, b, p, x, c); + } + + for _i in 0..100 { + let a = UInt::<$size>::random_mod(&mut rng, p); + let b = UInt::<$size>::random_mod(&mut rng, p); + + let c = a.sub_mod_special(&b, *special.as_ref()); + assert!(c < **p, "not reduced: {} >= {} ", c, p); + + let expected = a.sub_mod(&b, p); + assert_eq!(c, expected, "incorrect result"); + } + } + } + }; + } + + // Test requires 1-limb is capable of representing a 64-bit integer + #[cfg(target_pointer_width = "64")] + test_sub_mod!(1, sub1); + + test_sub_mod!(2, sub2); + test_sub_mod!(3, sub3); + test_sub_mod!(4, sub4); + test_sub_mod!(5, sub5); + test_sub_mod!(6, sub6); + test_sub_mod!(7, sub7); + test_sub_mod!(8, sub8); + test_sub_mod!(9, sub9); + test_sub_mod!(10, sub10); + test_sub_mod!(11, sub11); + test_sub_mod!(12, sub12); + + test_sub_mod_special!(1, sub_mod_special_1); + test_sub_mod_special!(2, sub_mod_special_2); + test_sub_mod_special!(3, sub_mod_special_3); + test_sub_mod_special!(4, sub_mod_special_4); + test_sub_mod_special!(5, sub_mod_special_5); + test_sub_mod_special!(6, sub_mod_special_6); + test_sub_mod_special!(7, sub_mod_special_7); + test_sub_mod_special!(8, sub_mod_special_8); + test_sub_mod_special!(9, sub_mod_special_9); + test_sub_mod_special!(10, sub_mod_special_10); + test_sub_mod_special!(11, sub_mod_special_11); + test_sub_mod_special!(12, sub_mod_special_12); +} -- cgit v1.2.3