Struct secp256kfun::Scalar

source ·
pub struct Scalar<S = Secret, Z = NonZero>(/* private fields */);
Expand description

A secp256k1 scalar (an integer mod the curve order)

The term scalar comes from interpreting the secp256k1 elliptic curve group as a vector space with a point as a notional single element vector and the field of integers modulo the curve order as its scalars. Specifically, a Scalar represents an integer modulo the curve order q where

q = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141

The thing that makes secp256k1 and other elliptic curves useful for cryptography is that scalar multiplication can be done efficiently:

use secp256kfun::{g, Scalar, G};
let x = Scalar::random(&mut rand::thread_rng());
let X = g!(x * G);

But finding x from (X,G) is hard because there is no known efficient algorithm to divide X by G to get x. This is known as the elliptic curve discrete logarithm problem. Because of this, scalars are often used as a secret keys with the points obtained by multiplying them by G as their corresponding public keys.

§Markers

A Scalar<S,Z> has two markers:

  • S: A Secrecy to determine whether operations on this scalar should be done in constant time or not. By default scalars are Secret so operations run in constant-time.
  • Z: A ZeroChoice to keep track of whether the point might be zero or is guaranteed to non-zero.

Implementations§

source§

impl<Z, S> Scalar<S, Z>

source

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

Serializes the scalar to its 32-byte big-endian representation

source

pub fn from_bytes(bytes: [u8; 32]) -> Option<Self>
where Z: ZeroChoice,

Creates a scalar from 32 big-endian encoded bytes. If the bytes represent an integer greater than or equal to the curve order then it returns None. If the scalar is marked NonZero then it will also return None it it’s the zero scalar.

§Example
use secp256kfun::{marker::*, Scalar};
assert!(Scalar::<Secret, Zero>::from_bytes([0u8; 32]).is_some());
// NonZero scalar's can't be zero
assert!(Scalar::<Secret, NonZero>::from_bytes([0u8; 32]).is_none());
// >= curve order
assert!(Scalar::<Secret, Zero>::from_bytes([255u8; 32]).is_none());
source

pub fn from_slice(slice: &[u8]) -> Option<Self>
where Z: ZeroChoice,

Decode a 32 byte long slice to a scalar.

Essentially from_bytes but checks that the slice is 32 bytes long first.

source

pub fn conditional_negate(&mut self, cond: bool)

Negates the scalar in-place if cond is true.

source

pub fn is_high(&self) -> bool

Returns whether the scalar is greater than the curve_order/2.

source

pub fn is_zero(&self) -> bool

Returns true if the scalar is equal to zero

source

pub fn set_secrecy<SNew>(self) -> Scalar<SNew, Z>

Set the secrecy of the Scalar to the type parameter.

source

pub fn public(self) -> Scalar<Public, Z>

Set the secrecy of the Scalar to Public.

A scalar should be set to public when the adversary is meant to know it as part of the protocol.

source

pub fn secret(self) -> Scalar<Secret, Z>

Set the secrecy of the Scalar to Secret.

A scalar should be set to secret when the adversary is not meant to know about it in the protocol.

source

pub fn mark_zero(self) -> Scalar<S, Zero>

Mark the scalar as possibly being Zero (even though it isn’t).

This is useful in accumulator variables where although the initial value is non-zero, every sum addition after that might make it zero so it’s necessary to start off with Zero marked scalar.

source§

impl<S> Scalar<S, NonZero>

source

pub fn invert(&self) -> Self

Returns the multiplicative inverse of the scalar modulo the curve order.

§Example
use secp256kfun::{marker::*, s, Scalar};
let a = Scalar::random(&mut rand::thread_rng());
let a_inverse = a.invert();
assert_eq!(s!(a * a_inverse), s!(1));
source

pub fn one() -> Self

Returns the integer 1 as a Scalar.

source

pub fn minus_one() -> Self

Returns the integer -1 (modulo the curve order) as a Scalar.

source

pub fn mark_zero_choice<Z: ZeroChoice>(self) -> Scalar<S, Z>

Marks a scalar non-zero scalar as having the zero choice Z (rather than NonZero).

Useful when writing code that preserves the zero choice of the caller.

§Example
use secp256kfun::{marker::*, s, Scalar};

/// Returns an iterator of 1, x, x², x³ ...
fn powers<S: Secrecy, Z: ZeroChoice>(x: Scalar<S, Z>) -> impl Iterator<Item = Scalar<S, Z>> {
    core::iter::successors(Some(Scalar::one().mark_zero_choice::<Z>()), move |xpow| {
        Some(s!(xpow * x).set_secrecy())
    })
}

assert_eq!(powers(s!(2)).take(4).collect::<Vec<_>>(), vec![
    s!(1),
    s!(2),
    s!(4),
    s!(8)
]);
assert_eq!(powers(s!(0)).take(4).collect::<Vec<_>>(), vec![
    s!(1).mark_zero(),
    s!(0),
    s!(0),
    s!(0)
]);
source§

impl Scalar<Secret, NonZero>

source

pub fn random<R: RngCore>(rng: &mut R) -> Self

Generates a random scalar from randomness taken from a caller provided cryptographically secure random number generator.

§Example
use secp256kfun::{g, Scalar, G};
let secret_scalar = Scalar::random(&mut rand::thread_rng());
let public_point = g!(secret_scalar * G);
source

pub fn from_hash(hash: impl Digest<OutputSize = U32>) -> Self

Converts the output of a 32-byte hash into a scalar by reducing it modulo the curve order.

§Example
use digest::Digest;
use secp256kfun::Scalar;
let mut hash = sha2::Sha256::default();
hash.update(b"Chancellor on brink of second bailout for banks".as_ref());
let scalar = Scalar::from_hash(hash);
source

pub fn from_non_zero_u32(int: NonZeroU32) -> Self

Converts a NonZeroU32 into a Scalar<Secret,NonZero>.

source§

impl<S> Scalar<S, Zero>

source

pub fn non_zero(self) -> Option<Scalar<S, NonZero>>

Converts a scalar marked with Zero to NonZero.

Returns None in the case that the scalar was in fact zero.

source

pub fn zero() -> Self

Returns the zero scalar.

§Example
let x = Scalar::random(&mut rand::thread_rng());
let zero = Scalar::<Secret,_>::zero();
assert_eq!(s!(zero * x), zero);
assert_eq!(s!(x + zero), x);
source

pub fn from_bytes_mod_order(bytes: [u8; 32]) -> Self

Converts 32 bytes into a scalar by reducing it modulo the curve order q.

§Example
use secp256kfun::{hex, marker::*, s, Scalar};
let scalar = Scalar::<Secret, _>::from_bytes_mod_order(*b"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
assert_eq!(scalar.to_bytes(), *b"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
let scalar_overflowed = Scalar::<Secret, _>::from_bytes_mod_order(
    hex::decode_array("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364142")
        .unwrap(),
);
assert_eq!(scalar_overflowed, s!(1))
source

pub fn from_slice_mod_order(slice: &[u8]) -> Option<Self>

Exactly like from_bytes_mod_order except it operates on a 32-byte slice rather than an array. If the slice is not 32 bytes long then the function returns None.

§Example
use secp256kfun::{marker::*, Scalar};
let bytes = b"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
assert!(Scalar::<Secret, _>::from_slice_mod_order(&bytes[..31]).is_none());
assert_eq!(
    Scalar::<Secret, _>::from_slice_mod_order(&bytes[..]).unwrap(),
    Scalar::<Secret, _>::from_bytes_mod_order(*bytes)
);

Trait Implementations§

source§

impl<SL, SR, ZR> AddAssign<&Scalar<SR, ZR>> for Scalar<SL, Zero>

source§

fn add_assign(&mut self, rhs: &Scalar<SR, ZR>)

Performs the += operation. Read more
source§

impl<SL, SR, ZR> AddAssign<Scalar<SR, ZR>> for Scalar<SL, Zero>

source§

fn add_assign(&mut self, rhs: Scalar<SR, ZR>)

Performs the += operation. Read more
source§

impl<S: Secrecy> Arbitrary for Scalar<S, NonZero>

§

type Parameters = ()

The type of parameters that arbitrary_with accepts for configuration of the generated Strategy. Parameters must implement Default.
§

type Strategy = BoxedStrategy<Scalar<S>>

The type of Strategy used to generate values of type Self.
source§

fn arbitrary_with(_: Self::Parameters) -> Self::Strategy

Generates a Strategy for producing arbitrary values of type the implementing type (Self). The strategy is passed the arguments given in args. Read more
source§

fn arbitrary() -> Self::Strategy

Generates a Strategy for producing arbitrary values of type the implementing type (Self). Read more
source§

impl<S: Secrecy> Arbitrary for Scalar<S, Zero>

§

type Parameters = ()

The type of parameters that arbitrary_with accepts for configuration of the generated Strategy. Parameters must implement Default.
§

type Strategy = BoxedStrategy<Scalar<S, Zero>>

The type of Strategy used to generate values of type Self.
source§

fn arbitrary_with(_: Self::Parameters) -> Self::Strategy

Generates a Strategy for producing arbitrary values of type the implementing type (Self). The strategy is passed the arguments given in args. Read more
source§

fn arbitrary() -> Self::Strategy

Generates a Strategy for producing arbitrary values of type the implementing type (Self). Read more
source§

impl<'de, S, Z: ZeroChoice> BorrowDecode<'de> for Scalar<S, Z>

Available on crate feature bincode only.
source§

fn borrow_decode<D: BorrowDecoder<'de>>( decoder: &mut D ) -> Result<Self, DecodeError>

Attempt to decode this type with the given BorrowDecode.
source§

impl<S, Z> Clone for Scalar<S, Z>

source§

fn clone(&self) -> Self

Returns a copy 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<Z, S> Debug for Scalar<S, Z>

source§

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

Formats the type as hex and any markers on the type.

source§

impl<S, Z: ZeroChoice> Decode for Scalar<S, Z>

Available on crate feature bincode only.
source§

fn decode<D: Decoder>(decoder: &mut D) -> Result<Self, DecodeError>

Attempt to decode this type with the given Decode.
source§

impl<S> Default for Scalar<S, NonZero>
where S: Secrecy,

source§

fn default() -> Self

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

impl<S> Default for Scalar<S, Zero>
where S: Secrecy,

source§

fn default() -> Self

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

impl<'de, S, Z: ZeroChoice> Deserialize<'de> for Scalar<S, Z>

Available on crate feature serde only.
source§

fn deserialize<Deser: Deserializer<'de>>( deserializer: Deser ) -> Result<Scalar<S, Z>, Deser::Error>

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

impl<Z, S> Display for Scalar<S, Z>

source§

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

Displays as hex.

source§

impl<Z, S> Encode for Scalar<S, Z>

Available on crate feature bincode only.
source§

fn encode<E: Encoder>(&self, encoder: &mut E) -> Result<(), EncodeError>

Encode a given type.
source§

impl<Z> From<Scalar<Public, Z>> for Scalar

source§

fn from(value: Scalar<Public, Z>) -> Self

Converts to this type from the input type.
source§

impl<Z> From<Scalar<Public, Z>> for Scalar

source§

fn from(value: Scalar<Public, Z>) -> Self

Converts to this type from the input type.
source§

impl From<Scalar> for Scalar<Public, Zero>

source§

fn from(value: Scalar) -> Self

Converts to this type from the input type.
source§

impl From<Scalar> for Scalar<Public, Zero>

source§

fn from(value: Scalar) -> Self

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

source§

fn from(scalar: Scalar) -> Self

Converts to this type from the input type.
source§

impl From<SecretKey> for Scalar

source§

fn from(sk: SecretKey) -> Self

Converts to this type from the input type.
source§

impl From<SecretKey> for Scalar

source§

fn from(sk: SecretKey) -> Self

Converts to this type from the input type.
source§

impl<S> From<u32> for Scalar<S, Zero>

source§

fn from(int: u32) -> Self

Converts to this type from the input type.
source§

impl<S, Z: ZeroChoice> FromStr for Scalar<S, Z>

source§

fn from_str(hex: &str) -> Result<Scalar<S, Z>, HexError>

Parses the string as hex and interprets tries to convert the resulting byte array into the desired value.

§

type Err = HexError

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

impl<Z> Hash for Scalar<Public, Z>

source§

fn hash<H: Hasher>(&self, state: &mut H)

Feeds this value into the given Hasher. Read more
1.3.0 · source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
source§

impl<S, Z> HashInto for Scalar<S, Z>

source§

fn hash_into(self, hash: &mut impl Digest)

Asks the item to convert itself to bytes and add itself to hash.
source§

impl<SL, SR> MulAssign<&Scalar<SR>> for Scalar<SL, NonZero>

source§

fn mul_assign(&mut self, rhs: &Scalar<SR, NonZero>)

Performs the *= operation. Read more
source§

impl<SL, SR, ZR: ZeroChoice> MulAssign<&Scalar<SR, ZR>> for Scalar<SL, Zero>

source§

fn mul_assign(&mut self, rhs: &Scalar<SR, ZR>)

Performs the *= operation. Read more
source§

impl<SL, SR> MulAssign<Scalar<SR>> for Scalar<SL, NonZero>

source§

fn mul_assign(&mut self, rhs: Scalar<SR, NonZero>)

Performs the *= operation. Read more
source§

impl<SL, SR, ZR: ZeroChoice> MulAssign<Scalar<SR, ZR>> for Scalar<SL, Zero>

source§

fn mul_assign(&mut self, rhs: Scalar<SR, ZR>)

Performs the *= operation. Read more
source§

impl<S, Z> Neg for &Scalar<S, Z>

§

type Output = Scalar<S, Z>

The resulting type after applying the - operator.
source§

fn neg(self) -> Self::Output

Performs the unary - operation. Read more
source§

impl<S, Z> Neg for Scalar<S, Z>

§

type Output = Scalar<S, Z>

The resulting type after applying the - operator.
source§

fn neg(self) -> Self::Output

Performs the unary - operation. Read more
source§

impl<Z> Ord for Scalar<Public, Z>

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 + PartialOrd,

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

impl<Z1, Z2, S1, S2> PartialEq<Scalar<S2, Z2>> for Scalar<S1, Z1>

source§

fn eq(&self, rhs: &Scalar<S2, Z2>) -> bool

This method tests for self and other values to be equal, and is used by ==.
1.0.0 · source§

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

This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
source§

impl<Z1, Z2> PartialOrd<Scalar<Public, Z2>> for Scalar<Public, Z1>

source§

fn partial_cmp(&self, other: &Scalar<Public, Z2>) -> 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

This method 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

This method 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

This method 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

This method tests greater than or equal to (for self and other) and is used by the >= operator. Read more
source§

impl<Z, S> Serialize for Scalar<S, Z>

Available on crate feature serde only.
source§

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

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

impl<SL, SR, ZR> SubAssign<&Scalar<SR, ZR>> for Scalar<SL, Zero>

source§

fn sub_assign(&mut self, rhs: &Scalar<SR, ZR>)

Performs the -= operation. Read more
source§

impl<SL, SR, ZR> SubAssign<Scalar<SR, ZR>> for Scalar<SL, Zero>

source§

fn sub_assign(&mut self, rhs: Scalar<SR, ZR>)

Performs the -= operation. Read more
source§

impl<Z, S> Copy for Scalar<S, Z>

source§

impl<Z, S> Eq for Scalar<Z, S>

Auto Trait Implementations§

§

impl<S, Z> RefUnwindSafe for Scalar<S, Z>

§

impl<S, Z> Send for Scalar<S, Z>
where S: Send, Z: Send,

§

impl<S, Z> Sync for Scalar<S, Z>
where S: Sync, Z: Sync,

§

impl<S, Z> Unpin for Scalar<S, Z>
where S: Unpin, Z: Unpin,

§

impl<S, Z> UnwindSafe for Scalar<S, Z>
where S: UnwindSafe, Z: UnwindSafe,

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> 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> Same for T

§

type Output = T

Should always be Self
source§

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

§

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> ToString for T
where T: Display + ?Sized,

source§

default fn to_string(&self) -> String

Converts the given value to a String. Read more
source§

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

§

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>,

§

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.
§

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

§

fn vzip(self) -> V

source§

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