k256/
scalar.rs

1use alloc::vec::Vec;
2use core::{cmp::Ordering, ops::ShrAssign};
3
4use elliptic_curve::{
5    bigint::{ArrayEncoding, Encoding, U256},
6    ops::{Invert, Reduce},
7    rand_core::RngCore,
8    scalar::{FromUintUnchecked, IsHigh},
9    subtle::{Choice, ConditionallySelectable, ConstantTimeEq, CtOption},
10    zeroize::DefaultIsZeroes,
11    Field, PrimeField, ScalarPrimitive,
12};
13use hex_literal::hex;
14use openvm_algebra_guest::IntMod;
15
16use crate::{
17    internal::{seven_le, Secp256k1Scalar},
18    point::FieldBytes,
19    Secp256k1, ORDER_HEX,
20};
21
22impl Secp256k1Scalar {
23    /// Returns the SEC1 encoding of this scalar.
24    pub fn to_bytes(&self) -> FieldBytes {
25        self.to_be_bytes().into()
26    }
27}
28// --- Implement elliptic_curve traits on Secp256k1Scalar ---
29
30impl Copy for Secp256k1Scalar {}
31
32impl From<u64> for Secp256k1Scalar {
33    fn from(value: u64) -> Self {
34        Self::from_u64(value)
35    }
36}
37
38impl Default for Secp256k1Scalar {
39    fn default() -> Self {
40        <Self as IntMod>::ZERO
41    }
42}
43
44// Requires canonical form
45impl ConstantTimeEq for Secp256k1Scalar {
46    fn ct_eq(&self, other: &Self) -> Choice {
47        self.as_le_bytes().ct_eq(other.as_le_bytes())
48    }
49}
50
51impl ConditionallySelectable for Secp256k1Scalar {
52    fn conditional_select(
53        a: &Secp256k1Scalar,
54        b: &Secp256k1Scalar,
55        choice: Choice,
56    ) -> Secp256k1Scalar {
57        Secp256k1Scalar::from_le_bytes_unchecked(
58            &a.as_le_bytes()
59                .iter()
60                .zip(b.as_le_bytes().iter())
61                .map(|(a, b)| u8::conditional_select(a, b, choice))
62                .collect::<Vec<_>>(),
63        )
64    }
65}
66
67impl Field for Secp256k1Scalar {
68    const ZERO: Self = <Self as IntMod>::ZERO;
69    const ONE: Self = <Self as IntMod>::ONE;
70
71    fn random(mut _rng: impl RngCore) -> Self {
72        unimplemented!()
73    }
74
75    fn square(&self) -> Self {
76        self * self
77    }
78
79    fn double(&self) -> Self {
80        self + self
81    }
82
83    fn invert(&self) -> CtOption<Self> {
84        // needs to be in canonical form for ct_eq
85        self.assert_reduced();
86        let is_zero = self.ct_eq(&<Self as IntMod>::ZERO);
87        CtOption::new(
88            <Secp256k1Scalar as openvm_algebra_guest::Field>::invert(self),
89            !is_zero,
90        )
91    }
92
93    #[allow(clippy::many_single_char_names)]
94    fn sqrt(&self) -> CtOption<Self> {
95        match <Self as openvm_algebra_guest::Sqrt>::sqrt(self) {
96            Some(sqrt) => CtOption::new(sqrt, 1.into()),
97            None => CtOption::new(<Self as Field>::ZERO, 0.into()),
98        }
99    }
100
101    fn sqrt_ratio(num: &Self, div: &Self) -> (Choice, Self) {
102        ff::helpers::sqrt_ratio_generic(num, div)
103    }
104}
105
106impl PrimeField for Secp256k1Scalar {
107    type Repr = FieldBytes;
108
109    const MODULUS: &'static str = ORDER_HEX;
110    const NUM_BITS: u32 = 256;
111    const CAPACITY: u32 = 255;
112    const TWO_INV: Self = Self::from_const_bytes(hex!(
113        "a1201b68462fe9df1d50a457736e575dffffffffffffffffffffffffffffff7f"
114    ));
115    const MULTIPLICATIVE_GENERATOR: Self = Self::from_const_bytes(seven_le());
116    const S: u32 = 6;
117    const ROOT_OF_UNITY: Self = Self::from_const_bytes(hex!(
118        "f252b002544b2f9945607580b6eabd98a883c4fba37998df8619a9e760c01d0c"
119    ));
120    const ROOT_OF_UNITY_INV: Self = Self::from_const_bytes(hex!(
121        "1c0d4f88a030fbb6c313a40a9175a27772bb8c5bc7b0c7ef96702df181e13afd"
122    ));
123    const DELTA: Self = Self::from_const_bytes(hex!(
124        "0176bbc0c81794191e34e180e7783bd6c86145fe21bc0c000000000000000000"
125    ));
126
127    /// Attempts to parse the given byte array as an SEC1-encoded scalar.
128    ///
129    /// Returns None if the byte array does not contain a big-endian integer in the range
130    /// [0, p).
131    fn from_repr(bytes: FieldBytes) -> CtOption<Self> {
132        let ret = Self::from_be_bytes_unchecked(bytes.as_slice());
133        CtOption::new(ret, (ret.is_reduced() as u8).into())
134    }
135
136    // Endianness should match from_repr
137    fn to_repr(&self) -> FieldBytes {
138        *FieldBytes::from_slice(&self.to_be_bytes())
139    }
140
141    fn is_odd(&self) -> Choice {
142        (self.as_le_bytes()[0] & 1).into()
143    }
144}
145
146impl ShrAssign<usize> for Secp256k1Scalar {
147    fn shr_assign(&mut self, _rhs: usize) {
148        // I don't think this is used anywhere
149        unimplemented!()
150    }
151}
152
153impl Reduce<U256> for Secp256k1Scalar {
154    type Bytes = FieldBytes;
155
156    fn reduce(w: U256) -> Self {
157        <Self as openvm_algebra_guest::Reduce>::reduce_le_bytes(&w.to_le_bytes())
158    }
159
160    #[inline]
161    fn reduce_bytes(bytes: &FieldBytes) -> Self {
162        Self::reduce(U256::from_be_byte_array(*bytes))
163    }
164}
165
166impl PartialOrd for Secp256k1Scalar {
167    // requires self and other to be in canonical form
168    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
169        self.assert_reduced();
170        other.assert_reduced();
171        Some(
172            self.to_be_bytes()
173                .iter()
174                .zip(other.to_be_bytes().iter())
175                .map(|(a, b)| a.cmp(b))
176                .find(|ord| *ord != Ordering::Equal)
177                .unwrap_or(Ordering::Equal),
178        )
179    }
180}
181
182impl IsHigh for Secp256k1Scalar {
183    fn is_high(&self) -> Choice {
184        // self > n/2
185        // iff self + self overflows
186        // iff self + self < self
187        ((self + self < *self) as u8).into()
188    }
189}
190
191impl Invert for Secp256k1Scalar {
192    type Output = CtOption<Self>;
193
194    fn invert(&self) -> CtOption<Self> {
195        <Self as Field>::invert(self)
196    }
197}
198
199impl FromUintUnchecked for Secp256k1Scalar {
200    type Uint = U256;
201
202    fn from_uint_unchecked(uint: Self::Uint) -> Self {
203        Self::from_le_bytes_unchecked(&uint.to_le_bytes())
204    }
205}
206
207impl From<ScalarPrimitive<Secp256k1>> for Secp256k1Scalar {
208    fn from(scalar: ScalarPrimitive<Secp256k1>) -> Self {
209        Self::from_le_bytes_unchecked(&scalar.as_uint().to_le_bytes())
210    }
211}
212
213impl From<Secp256k1Scalar> for ScalarPrimitive<Secp256k1> {
214    fn from(scalar: Secp256k1Scalar) -> ScalarPrimitive<Secp256k1> {
215        ScalarPrimitive::from_slice(&scalar.to_be_bytes()).unwrap()
216    }
217}
218
219impl DefaultIsZeroes for Secp256k1Scalar {}
220
221impl AsRef<Secp256k1Scalar> for Secp256k1Scalar {
222    fn as_ref(&self) -> &Secp256k1Scalar {
223        self
224    }
225}
226
227impl From<Secp256k1Scalar> for U256 {
228    fn from(scalar: Secp256k1Scalar) -> Self {
229        U256::from_be_slice(&scalar.to_be_bytes())
230    }
231}
232
233impl From<Secp256k1Scalar> for FieldBytes {
234    fn from(scalar: Secp256k1Scalar) -> Self {
235        *FieldBytes::from_slice(&scalar.to_be_bytes())
236    }
237}