Scalar

Struct Scalar 

Source
pub struct Scalar { /* private fields */ }
Expand description

Represents a non-zero scalar in the range [1, n) where n is the order of the secp256k1 curve. A Scalar can be:

  • added, negated, subtracted, and multiplied with other Scalar instances.
  • added, negated, subtracted, and multiplied with MaybeScalar.
  • multiplied with Point.
  • multiplied with MaybePoint.

…using the normal Rust arithemtic operators +, - and *. Such operations are commutative, i.e. a * b = b * a and a + b = b + a in call cases.

Depending on the types involved in an operation, certain operators will produce different result types which should be handled depending on your use case. For instance, adding two Scalars results in a MaybeScalar, because the two Scalars may be additive inverses of each other and their output would result in MaybeScalar::Zero when taken mod n.

Implementations§

Source§

impl Scalar

Source

pub fn one() -> Scalar

Returns a valid Scalar with a value of 1.

Source

pub fn two() -> Scalar

Returns a valid Scalar with a value of two.

Source

pub fn half_order() -> Scalar

Returns half of the curve order n, specifically n >> 1.

Source

pub fn max() -> Scalar

Returns a valid Scalar with the maximum possible value less than the curve order, n - 1.

Source

pub fn is_high(&self) -> Choice

Returns subtle::Choice::from(1) if this scalar is strictly greater than half the curve order; i.e if self > (n >> 1).

This is used to reduce malleability of ECDSA signatures, whose s values could be considered valid if they are either s or n - s. Converting the s value using Scalar::to_low and checking it using Scalar::is_high upon verification fixes this ambiguity.

Beware that leaking timing information about this bit may expose a bit of information about the scalar.

Source

pub fn to_low(self) -> Scalar

If self.is_high(), this returns -self. Otherwise, returns the scalar unchanged.

This is used to reduce malleability of ECDSA signatures, whose s values could be considered valid if they are either s or n - s. Converting the s value using Scalar::to_low and checking it using Scalar::is_high upon verification fixes this ambiguity.

Source

pub fn random<R: RngCore + CryptoRng>(rng: &mut R) -> Scalar

Generates a new random scalar from the given CSPRNG.

Source

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

Serializes the scalar to a big-endian byte array representation.

§Warning

Use cautiously. Non-constant time operations on these bytes could reveal secret key material.

Source

pub fn from_slice(bytes: &[u8]) -> Result<Self, InvalidScalarBytes>

Parses a non-zero scalar in the range [1, n) from a given byte slice, which must be exactly 32-byte long and must represent the scalar in big-endian format.

Source

pub fn from_hex(hex: &str) -> Result<Self, InvalidScalarString>

Parses a Scalar from a 32-byte hex string representation.

Source

pub fn base_point_mul(&self) -> Point

Multiplies the secp256k1 base point by this scalar. This is how public keys (points) are derived from private keys (scalars). Since this scalar is non-zero, the point derived from base-point multiplication is also guaranteed to be valid.

Source

pub fn negate_if(self, parity: Choice) -> Scalar

Negates the scalar in constant-time if the given parity bit is a 1.

Source

pub fn invert(self) -> Scalar

Inverts a scalar modulo the curve order n in constant time. This outputs a scalar such that self * self.inverse() == Scalar::one() for all non-zero scalars.

Source

pub fn reduce_from(z_bytes: &[u8; 32]) -> Self

Converts a 32-byte array into a Scalar by interpreting it as a big-endian integer z and returning (z % (n-1)) + 1, where n is the secp256k1 curve order. This always returns a valid non-zero scalar in the range [1, n). All operations are constant-time, except if z works out to be zero.

The probability that z_bytes represents an integer z larger than the curve order is only about 1 in 2^128, but nonetheless this function makes a best-effort attempt to parse all inputs in constant time and reduce them to an integer in the range [1, n).

Trait Implementations§

Source§

impl Add<MaybeScalar> for Scalar

Source§

type Output = MaybeScalar

The resulting type after applying the + operator.
Source§

fn add(self, rhs: MaybeScalar) -> Self::Output

Performs the + operation. Read more
Source§

impl Add<Scalar> for MaybeScalar

Source§

type Output = MaybeScalar

The resulting type after applying the + operator.
Source§

fn add(self, rhs: Scalar) -> Self::Output

Performs the + operation. Read more
Source§

impl Add for Scalar

Scalar + Scalar

Source§

type Output = MaybeScalar

The resulting type after applying the + operator.
Source§

fn add(self, other: Scalar) -> Self::Output

Performs the + operation. Read more
Source§

impl AddAssign<Scalar> for MaybeScalar

Source§

fn add_assign(&mut self, rhs: Scalar)

Performs the += operation. Read more
Source§

impl AsRef<[u8]> for Scalar

Source§

fn as_ref(&self) -> &[u8]

Returns a reference to the underlying secret bytes of this scalar.

§Warning

Use cautiously. Non-constant time operations on these bytes could reveal secret key material.

Source§

impl AsRef<[u8; 32]> for Scalar

Source§

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

Returns a reference to the underlying secret bytes of this scalar.

§Warning

Use cautiously. Non-constant time operations on these bytes could reveal secret key material.

Source§

impl AsRef<SecretKey> for Scalar

Source§

fn as_ref(&self) -> &SecretKey

Converts this type into a shared reference of the (usually inferred) input type.
Source§

impl Bounded for Scalar

Source§

fn min_value() -> Self

Returns the smallest finite number this type can represent
Source§

fn max_value() -> Self

Returns the largest finite number this type can represent
Source§

impl Clone for Scalar

Source§

fn clone(&self) -> Scalar

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 ConditionallySelectable for Scalar

Source§

fn conditional_select(a: &Self, b: &Self, choice: Choice) -> Self

Conditionally selects one of two scalars in constant time. No timing information about the value of either scalar will be leaked.

Source§

fn conditional_assign(&mut self, other: &Self, choice: Choice)

Conditionally assign other to self, according to choice. Read more
Source§

fn conditional_swap(a: &mut Self, b: &mut Self, choice: Choice)

Conditionally swap self and other if choice == 1; otherwise, reassign both unto themselves. Read more
Source§

impl ConstantTimeEq for Scalar

Source§

fn ct_eq(&self, other: &Self) -> Choice

Compares this scalar against another in constant time. Returns subtle::Choice::from(1) if and only if the two scalars represent the same integer.

Source§

fn ct_ne(&self, other: &Self) -> Choice

Determine if two items are NOT equal. Read more
Source§

impl ConstantTimeGreater for Scalar

Source§

fn ct_gt(&self, other: &Self) -> Choice

Compares this scalar against another in constant time. Returns subtle::Choice::from(1) if self is strictly lexicographically greater than other.

Source§

impl ConstantTimeLess for Scalar

Source§

fn ct_lt(&self, other: &Self) -> Choice

Determine whether self < other. Read more
Source§

impl Debug for Scalar

This implementation was duplicated from the secp256k1 crate, because k256::NonZeroScalar doesn’t implement Debug.

Source§

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

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

impl<'de> Deserialize<'de> for Scalar

Source§

fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error>

Deserialize this value from the given Serde deserializer. Read more
Source§

impl Div<Scalar> for G

To divide by rhs, we simply multiply by rhs.inverse(), because rhs.inverse() is algebraically the same as 1 / rhs.

Source§

type Output = Point

The resulting type after applying the / operator.
Source§

fn div(self, rhs: Scalar) -> Self::Output

Performs the / operation. Read more
Source§

impl Div<Scalar> for MaybePoint

Source§

type Output = MaybePoint

The resulting type after applying the / operator.
Source§

fn div(self, rhs: Scalar) -> Self::Output

Performs the / operation. Read more
Source§

impl Div<Scalar> for MaybeScalar

Source§

type Output = MaybeScalar

The resulting type after applying the / operator.
Source§

fn div(self, rhs: Scalar) -> Self::Output

Performs the / operation. Read more
Source§

impl Div<Scalar> for Point

To divide by rhs, we simply multiply by rhs.inverse(), because rhs.inverse() is algebraically the same as 1 / rhs.

Source§

type Output = Point

The resulting type after applying the / operator.
Source§

fn div(self, rhs: Scalar) -> Self::Output

Performs the / operation. Read more
Source§

impl Div for Scalar

To divide by rhs, we simply multiply by rhs.inverse(), because rhs.inverse() is algebraically the same as 1 / rhs.

Source§

type Output = Scalar

The resulting type after applying the / operator.
Source§

fn div(self, rhs: Scalar) -> Self::Output

Performs the / operation. Read more
Source§

impl DivAssign<Scalar> for MaybePoint

Source§

fn div_assign(&mut self, rhs: Scalar)

Performs the /= operation. Read more
Source§

impl DivAssign<Scalar> for MaybeScalar

Source§

fn div_assign(&mut self, rhs: Scalar)

Performs the /= operation. Read more
Source§

impl DivAssign<Scalar> for Point

Source§

fn div_assign(&mut self, rhs: Scalar)

Performs the /= operation. Read more
Source§

impl DivAssign for Scalar

Source§

fn div_assign(&mut self, rhs: Scalar)

Performs the /= operation. Read more
Source§

impl From<NonZeroScalar<Secp256k1>> for Scalar

Source§

fn from(nz_scalar: NonZeroScalar) -> Self

Converts to this type from the input type.
Source§

impl From<Scalar> for [u8; 32]

Source§

fn from(scalar: Scalar) -> Self

Serializes the scalar to a big-endian byte array representation.

Source§

impl From<Scalar> for MaybeScalar

Source§

fn from(scalar: Scalar) -> Self

Converts the scalar into a MaybeScalar::Valid instance.

Source§

impl From<Scalar> for NonZeroScalar

Source§

fn from(scalar: Scalar) -> Self

Converts to this type from the input type.
Source§

impl From<Scalar> for Scalar

Source§

fn from(scalar: Scalar) -> Self

Converts to this type from the input type.
Source§

impl From<Scalar> for Scalar

Source§

fn from(scalar: Scalar) -> Self

Converts to this type from the input type.
Source§

impl From<Scalar> for Scalar

Source§

fn from(scalar: Scalar) -> Self

Converts to this type from the input type.
Source§

impl From<Scalar> for SecretKey

Source§

fn from(scalar: Scalar) -> SecretKey

Converts to this type from the input type.
Source§

impl From<Scalar> for SecretKey

Source§

fn from(scalar: Scalar) -> Self

Converts to this type from the input type.
Source§

impl From<SecretKey<Secp256k1>> for Scalar

Source§

fn from(seckey: SecretKey) -> Self

Converts to this type from the input type.
Source§

impl From<SecretKey> for Scalar

Source§

fn from(inner: SecretKey) -> Self

Converts to this type from the input type.
Source§

impl FromStr for Scalar

Source§

fn from_str(s: &str) -> Result<Self, Self::Err>

Parses a Scalar from a 32-byte hex string representation.

Source§

type Err = InvalidScalarString

The associated error which can be returned from parsing.
Source§

impl Inv for Scalar

Source§

type Output = Scalar

The result after applying the operator.
Source§

fn inv(self) -> Self::Output

Returns the multiplicative inverse of self. Read more
Source§

impl LowerHex for Scalar

Source§

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

Formats the scalar as a hex string in lower case.

§Warning

This method may expose private data if the scalar represents a secret key.

Source§

impl Mul<G> for Scalar

Scalar * G

Source§

type Output = Point

The resulting type after applying the * operator.
Source§

fn mul(self, _: G) -> Self::Output

Performs the * operation. Read more
Source§

impl Mul<MaybePoint> for Scalar

Source§

type Output = MaybePoint

The resulting type after applying the * operator.
Source§

fn mul(self, rhs: MaybePoint) -> Self::Output

Performs the * operation. Read more
Source§

impl Mul<MaybeScalar> for Scalar

Source§

type Output = MaybeScalar

The resulting type after applying the * operator.
Source§

fn mul(self, rhs: MaybeScalar) -> Self::Output

Performs the * operation. Read more
Source§

impl Mul<Point> for Scalar

Scalar * Point

Source§

type Output = Point

The resulting type after applying the * operator.
Source§

fn mul(self, point: Point) -> Self::Output

Performs the * operation. Read more
Source§

impl Mul<Scalar> for G

G * Scalar

Source§

type Output = Point

The resulting type after applying the * operator.
Source§

fn mul(self, scalar: Scalar) -> Self::Output

Performs the * operation. Read more
Source§

impl Mul<Scalar> for MaybePoint

Source§

type Output = MaybePoint

The resulting type after applying the * operator.
Source§

fn mul(self, rhs: Scalar) -> Self::Output

Performs the * operation. Read more
Source§

impl Mul<Scalar> for MaybeScalar

Source§

type Output = MaybeScalar

The resulting type after applying the * operator.
Source§

fn mul(self, rhs: Scalar) -> Self::Output

Performs the * operation. Read more
Source§

impl Mul<Scalar> for Point

Point * Scalar

Source§

type Output = Point

The resulting type after applying the * operator.
Source§

fn mul(self, scalar: Scalar) -> Self::Output

Performs the * operation. Read more
Source§

impl Mul for Scalar

Note: Scalar * Scalar always outputs a non-zero Scalar.

Source§

type Output = Scalar

The resulting type after applying the * operator.
Source§

fn mul(self, other: Scalar) -> Self::Output

Performs the * operation. Read more
Source§

impl MulAssign<Scalar> for MaybePoint

Source§

fn mul_assign(&mut self, rhs: Scalar)

Performs the *= operation. Read more
Source§

impl MulAssign<Scalar> for MaybeScalar

Source§

fn mul_assign(&mut self, rhs: Scalar)

Performs the *= operation. Read more
Source§

impl MulAssign<Scalar> for Point

Source§

fn mul_assign(&mut self, rhs: Scalar)

Performs the *= operation. Read more
Source§

impl MulAssign for Scalar

Source§

fn mul_assign(&mut self, rhs: Scalar)

Performs the *= operation. Read more
Source§

impl Neg for Scalar

-Scalar

Source§

type Output = Scalar

The resulting type after applying the - operator.
Source§

fn neg(self) -> Self::Output

Performs the unary - operation. Read more
Source§

impl One for Scalar

Source§

fn one() -> Self

Returns the multiplicative identity element of Self, 1. Read more
Source§

fn is_one(&self) -> bool

Returns true if self is equal to the multiplicative identity. Read more
Source§

fn set_one(&mut self)

Sets self to the multiplicative identity element of Self, 1.
Source§

impl PartialEq for Scalar

Source§

fn eq(&self, other: &Scalar) -> 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 Product for Scalar

This implementation allows iterators of Scalar to be multiplied together with Iterator::product.

Since all scalars in the iterator are guaranteed to be non-zero, the resulting product is also guaranteed to be non-zero.

use secp::Scalar;

let scalars = [
  Scalar::two(),
  Scalar::two(),
  Scalar::two(),
];
let expected = "0000000000000000000000000000000000000000000000000000000000000008"
    .parse::<Scalar>()
    .unwrap();

assert_eq!(scalars.into_iter().product::<Scalar>(), expected);

Returns Scalar::one() if the iterator is empty.

Source§

fn product<I: Iterator<Item = Scalar>>(iter: I) -> Self

Takes an iterator and generates Self from the elements by multiplying the items.
Source§

impl Serialize for Scalar

Source§

fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error>

Serialize this value into the given Serde serializer. Read more
Source§

impl Sub<MaybeScalar> for Scalar

Source§

type Output = MaybeScalar

The resulting type after applying the - operator.
Source§

fn sub(self, rhs: MaybeScalar) -> Self::Output

Performs the - operation. Read more
Source§

impl Sub<Scalar> for MaybeScalar

Source§

type Output = MaybeScalar

The resulting type after applying the - operator.
Source§

fn sub(self, rhs: Scalar) -> Self::Output

Performs the - operation. Read more
Source§

impl Sub for Scalar

Source§

type Output = MaybeScalar

The resulting type after applying the - operator.
Source§

fn sub(self, rhs: Scalar) -> Self::Output

Performs the - operation. Read more
Source§

impl SubAssign<Scalar> for MaybeScalar

Source§

fn sub_assign(&mut self, rhs: Scalar)

Performs the -= operation. Read more
Source§

impl TryFrom<&[u8]> for Scalar

Source§

fn try_from(bytes: &[u8]) -> Result<Self, Self::Error>

Attempts to parse a 32-byte slice as a scalar in the range [1, n) in constant time, where n is the curve order.

Returns InvalidScalarBytes if the integer represented by the bytes is greater than or equal to the curve order, or if the bytes are all zero.

Fails if bytes.len() != 32.

Source§

type Error = InvalidScalarBytes

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

impl TryFrom<&[u8; 32]> for Scalar

Source§

fn try_from(bytes: &[u8; 32]) -> Result<Self, Self::Error>

Attempts to parse a 32-byte array as a scalar in the range [1, n) in constant time, where n is the curve order.

Returns InvalidScalarBytes if the integer represented by the bytes is greater than or equal to the curve order, or if the bytes are all zero.

Source§

type Error = InvalidScalarBytes

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

impl TryFrom<[u8; 32]> for Scalar

Source§

fn try_from(bytes: [u8; 32]) -> Result<Self, Self::Error>

Attempts to parse a 32-byte array as a scalar in the range [1, n) in constant time, where n is the curve order.

Returns InvalidScalarBytes if the integer represented by the bytes is greater than or equal to the curve order, or if the bytes are all zero.

Source§

type Error = InvalidScalarBytes

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

impl TryFrom<GenericArray<u8, <Secp256k1 as Curve>::FieldBytesSize>> for Scalar

Source§

fn try_from(bytes: FieldBytes) -> Result<Self, Self::Error>

Attempts to parse a 32-byte array as a scalar in the range [1, n) in constant time, where n is the curve order.

Returns InvalidScalarBytes if the integer represented by the bytes is greater than or equal to the curve order.

Source§

type Error = InvalidScalarBytes

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

impl TryFrom<MaybeScalar> for Scalar

Source§

fn try_from(maybe_scalar: MaybeScalar) -> Result<Self, Self::Error>

Converts the MaybeScalar into a Result<Scalar, ZeroScalarError>, returning Ok(Scalar) if the scalar is a valid non-zero number, or Err(ZeroScalarError) if maybe_scalar == MaybeScalar::Zero.

Source§

type Error = ZeroScalarError

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

impl TryFrom<Scalar> for Scalar

Source§

type Error = ZeroScalarError

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

fn try_from(scalar: Scalar) -> Result<Self, Self::Error>

Performs the conversion.
Source§

impl TryFrom<u128> for Scalar

Converts any unsigned integer number into a Scalar. Returns ZeroScalarError if the integer is zero.

Source§

type Error = ZeroScalarError

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

fn try_from(value: u128) -> Result<Self, Self::Error>

Performs the conversion.
Source§

impl UpperHex for Scalar

Source§

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

Formats the scalar as a hex string in upper case.

§Warning

This method may expose private data if the scalar represents a secret key.

Source§

impl Copy for Scalar

Source§

impl Eq for Scalar

Source§

impl StructuralPartialEq for Scalar

Auto Trait Implementations§

§

impl Freeze for Scalar

§

impl RefUnwindSafe for Scalar

§

impl Send for Scalar

§

impl Sync for Scalar

§

impl Unpin for Scalar

§

impl UnwindSafe for Scalar

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> LowerBounded for T
where T: Bounded,

Source§

fn min_value() -> T

Returns the smallest finite number this type can represent
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
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.
Source§

impl<T> UpperBounded for T
where T: Bounded,

Source§

fn max_value() -> T

Returns the largest finite number this type can represent
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

Source§

impl<T, Rhs, Output> ScalarMul<Rhs, Output> for T
where T: Mul<Rhs, Output = Output> + MulAssign<Rhs>,