Struct Num

Source
pub struct Num(/* private fields */);
Expand description

Number used for modular arithmetic. Internally stored in little-endian (least-significant byte first) format.

Implementations§

Source§

impl Num

Source

pub const ZERO: Num

Source

pub const ONE: Num

Source

pub const TWO: Num

Source

pub const THREE: Num

Source

pub const SEVEN: Num

Source

pub const WIDTH: usize = 4usize

The size of this number in 64-bit words.

Source

pub const BITS: usize = 256usize

The size of this number in bits.

Source

pub const BYTES: usize = 32usize

The size of this number in bytes.

Source

pub const fn from_le_words(n: [u64; 4]) -> Self

Source

pub fn from_le_bytes(b: [u8; 32]) -> Self

Source

pub fn to_le_bytes(&self) -> [u8; 32]

Source

pub fn add(&self, n: Self, p: Self) -> Self

Modular addition with modulus p.

Source

pub fn sub(self, n: Self, p: Self) -> Self

Modular subtraction with modulus p.

Source

pub fn mul(self, n: Self, p: Self) -> Self

Modular multiplication with modulus p.

Source

pub fn eq(self, n: Self, p: Self) -> bool

Modular equality with modulus p.

Source

pub fn reduce(self, p: Self) -> Self

Reduction modulo p.

Source

pub fn inv(&self, p: Self) -> Option<Self>

Get the modular multiplicative inverse of the number by using the extended Euclidean algorithm. Returns None for Num::ZERO, since 0 has no inverse.

The non-extended Euclidean algorithm computes the greatest common divisor $gcd(a, b)$ given $a, b, a \leq b$. It relies on the following fact: $gcd(a, b) = gcd(b - \lfloor \frac{b}{a} \rfloor a, a)$. This fact allows the algorithm to successively reduce the values of $a$ and $b$ until one is eventually equal to zero, and the other is equal to the greatest common divisor. The algorithm operates as follows:

  • Set $u = a, v = b$. The algorithm maintains the invariant that $u \leq v$.
  • Iteratively update $u$ and $v$. First, get the quotient $q = \lfloor \frac{v}{u} \rfloor$, then set the new values $v' = u, u' = v - qu$. Note that $v - qu$ is the remainder from dividing $v$ by $u$. Call this remainder $r$, so that $u = r$.
  • Terminate when $u = 0$. $v$ is the greatest common divisor.

To extend the algorithm above, apply Bezout’s identity. This identity states that, given two integers $a$ and $b$ with greatest common divisor $d$, there exist integers $x$ and $y$ such that $ax + by = d$.

The extended algorithm will represent $u$ and $v$ as

$$ u = x_1a + y_1b \\ v = x_2a + y_2b $$

Since $u$ should be initialized to $a$, and $v$ should be initialized to $b$, the initial values for $x_{1, 2}$ and $y_{1, 2}$ are $x_1 = 1, y_1 = 0, x_2 = 0, y_2 = 1$.

The rest of the algorithm is exactly the same, except that apart from updating $u$ and $v$ like the regular Euclidean algorithm, the extended Euclidean algorithm also updates $x_{1, 2}$ and $y_{1, 2}$. This is done as follows:

$$ x_2' = x_1 \\ x_1' = x_2 - qx_1 \\ y_2' = y_1 \\ y_1' = y_2 - qy_1 $$

Where $q = \lfloor \frac{v}{u} \rfloor$ is the quotient and $r = v - qu$ is the remainder, same as in the non-extended Euclidean algorithm. It is not difficult to verify that the values for $x_{1, 2}'$ and $y_{1, 2}'$ are correct. Namely, it must be true that $v' = u$ and $u' = r$ as in the non-extended Euclidean algorithm. This can be shown with a few substitutions:

$$ v' = x_2'a + y_2'b \\ v' = x_1a + y_1 b \\ v' = u $$

And

$$ u' = x_1'a + y_1'b \\ u' = (x_2 - qx_1)a + (y_2 - qy_1)b \\ u' = ax_2 + by_2 - (ax_1 + by_1)q \\ u' = v - qu $$

So $v' = u, u' = v - qu$ as expected. The algorithm terminates when $u = 0$, at which point $x_2$, $y_2$, and $v$ are the result of the algorithm.

Finally, the above can be used to get a multiplicative inverse. If $b$ (or $a$) is prime, the result of the algorithm will be $v = 1$ because the greatest common divisor between a prime number and any other number is 1.

$$ v = 1 = x_2a + y_2b $$

If the operations are done in a prime field with order $b$, then

$$ y_2b \equiv 0 \pmod b \implies v \equiv x_2a \equiv 1 \pmod b $$

This means that $x_2$ is the multiplicative inverse of $a$ in the prime field with order $b$. Finally, since $y_1$ and $y_2$ are not used, they can be omitted from the algorithm as a small optimization.

Source

pub fn get_bit(&self, i: usize) -> bool

Get the bit at the given index. The rightmost (least significant) bit is at index 0.

Trait Implementations§

Source§

impl Clone for Num

Source§

fn clone(&self) -> Num

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Num

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for Num

Source§

fn default() -> Num

Returns the “default value” for a type. Read more
Source§

impl<C: Curve> Mul<Point<C>> for Num

Multiply the point by a scalar.

This uses the square-and-multiply method. For example, to calculate $x^{19}$, start with $y = x$ and multiply $y$ with itself, resulting in $y = y \cdot y = x^2$. Then, multiply $y$ with itself again, resulting in $y = y \cdot y = x^4$. Repeat this until it can no longer be done, at which point $y = x^{16}$ and there have been four multiplications thus far. Finally, multiply $y$ with $x$ three more times to get the desired result.

With this method, $x^{19}$ was calculated in only seven multiplications, compared to the naive algorithm which would execute 19 multiplications.

In the case of elliptic curve points, the “square” is equivalent to doubling, and “multiply” is equivalent to addition.

Source§

type Output = Point<C>

The resulting type after applying the * operator.
Source§

fn mul(self, rhs: Point<C>) -> Self::Output

Performs the * operation. Read more
Source§

impl Ord for Num

Source§

fn cmp(&self, other: &Self) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 · Source§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 · Source§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 · Source§

fn clamp(self, min: Self, max: Self) -> Self
where Self: Sized,

Restrict a value to a certain interval. Read more
Source§

impl PartialEq for Num

Source§

fn eq(&self, other: &Num) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl PartialOrd for Num

Source§

fn partial_cmp(&self, other: &Self) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · Source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · Source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · Source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl Copy for Num

Source§

impl Eq for Num

Source§

impl StructuralPartialEq for Num

Auto Trait Implementations§

§

impl Freeze for Num

§

impl RefUnwindSafe for Num

§

impl Send for Num

§

impl Sync for Num

§

impl Unpin for Num

§

impl UnwindSafe for Num

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.