1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
use cfg_if::cfg_if;
cfg_if! {
if #[cfg(any(target_pointer_width = "32", feature = "force-32-bit"))] {
mod scalar_8x32;
use scalar_8x32::Scalar8x32 as ScalarImpl;
#[cfg(feature = "rand")]
use scalar_8x32::WideScalar16x32 as WideScalarImpl;
} else if #[cfg(target_pointer_width = "64")] {
mod scalar_4x64;
use scalar_4x64::Scalar4x64 as ScalarImpl;
#[cfg(feature = "rand")]
use scalar_4x64::WideScalar8x64 as WideScalarImpl;
}
}
use crate::{ElementBytes, Secp256k1};
use core::ops::{Add, AddAssign, Mul, MulAssign, Neg, Shr, Sub, SubAssign};
use elliptic_curve::{
consts::U32,
ops::Invert,
subtle::{Choice, ConditionallySelectable, ConstantTimeEq, CtOption},
FromBytes,
};
#[cfg(feature = "digest")]
use ecdsa_core::signature::digest::Digest;
#[cfg(feature = "rand")]
use elliptic_curve::{
rand_core::{CryptoRng, RngCore},
Generate,
};
#[cfg(feature = "zeroize")]
use elliptic_curve::zeroize::Zeroize;
#[cfg(test)]
use num_bigint::{BigUint, ToBigUint};
pub type NonZeroScalar = elliptic_curve::scalar::NonZeroScalar<Secp256k1>;
#[derive(Clone, Copy, Debug, Default)]
#[cfg_attr(docsrs, doc(cfg(feature = "arithmetic")))]
pub struct Scalar(ScalarImpl);
impl From<u32> for Scalar {
fn from(k: u32) -> Self {
Self(ScalarImpl::from(k))
}
}
impl Scalar {
pub const fn zero() -> Self {
Self(ScalarImpl::zero())
}
pub const fn one() -> Scalar {
Self(ScalarImpl::one())
}
pub fn is_zero(&self) -> Choice {
self.0.is_zero()
}
pub fn truncate_to_u32(&self) -> u32 {
self.0.truncate_to_u32()
}
#[cfg(feature = "endomorphism-mul")]
pub(crate) const fn from_bytes_unchecked(bytes: &[u8; 32]) -> Self {
Self(ScalarImpl::from_bytes_unchecked(bytes))
}
pub fn from_bytes_reduced(bytes: &ElementBytes) -> Self {
Self(ScalarImpl::from_bytes_reduced(bytes.as_ref()))
}
#[cfg(feature = "digest")]
#[cfg_attr(docsrs, doc(cfg(feature = "digest")))]
pub fn from_digest<D>(digest: D) -> Self
where
D: Digest<OutputSize = U32>,
{
Self::from_bytes_reduced(&digest.finalize())
}
pub fn to_bytes(&self) -> ElementBytes {
self.0.to_bytes()
}
pub fn is_high(&self) -> Choice {
self.0.is_high()
}
pub fn negate(&self) -> Self {
Self(self.0.negate())
}
pub fn add(&self, rhs: &Scalar) -> Scalar {
Self(self.0.add(&(rhs.0)))
}
pub fn sub(&self, rhs: &Scalar) -> Scalar {
Self(self.0.sub(&(rhs.0)))
}
pub fn mul(&self, rhs: &Scalar) -> Scalar {
Self(self.0.mul(&(rhs.0)))
}
pub fn square(&self) -> Self {
self.mul(&self)
}
pub fn rshift(&self, shift: usize) -> Scalar {
Self(self.0.rshift(shift))
}
fn pow2k(&self, k: usize) -> Self {
let mut x = *self;
for _j in 0..k {
x = x.square();
}
x
}
pub fn invert(&self) -> CtOption<Self> {
let x_1 = *self;
let x_10 = self.pow2k(1);
let x_11 = x_10.mul(&x_1);
let x_101 = x_10.mul(&x_11);
let x_111 = x_10.mul(&x_101);
let x_1001 = x_10.mul(&x_111);
let x_1011 = x_10.mul(&x_1001);
let x_1101 = x_10.mul(&x_1011);
let x6 = x_1101.pow2k(2).mul(&x_1011);
let x8 = x6.pow2k(2).mul(&x_11);
let x14 = x8.pow2k(6).mul(&x6);
let x28 = x14.pow2k(14).mul(&x14);
let x56 = x28.pow2k(28).mul(&x28);
#[rustfmt::skip]
let res = x56
.pow2k(56).mul(&x56)
.pow2k(14).mul(&x14)
.pow2k(3).mul(&x_101)
.pow2k(4).mul(&x_111)
.pow2k(4).mul(&x_101)
.pow2k(5).mul(&x_1011)
.pow2k(4).mul(&x_1011)
.pow2k(4).mul(&x_111)
.pow2k(5).mul(&x_111)
.pow2k(6).mul(&x_1101)
.pow2k(4).mul(&x_101)
.pow2k(3).mul(&x_111)
.pow2k(5).mul(&x_1001)
.pow2k(6).mul(&x_101)
.pow2k(10).mul(&x_111)
.pow2k(4).mul(&x_111)
.pow2k(9).mul(&x8)
.pow2k(5).mul(&x_1001)
.pow2k(6).mul(&x_1011)
.pow2k(4).mul(&x_1101)
.pow2k(5).mul(&x_11)
.pow2k(6).mul(&x_1101)
.pow2k(10).mul(&x_1101)
.pow2k(4).mul(&x_1001)
.pow2k(6).mul(&x_1)
.pow2k(8).mul(&x6);
CtOption::new(res, !self.is_zero())
}
#[cfg(test)]
pub fn modulus_as_biguint() -> BigUint {
Self::one().negate().to_biguint().unwrap() + 1.to_biguint().unwrap()
}
#[cfg(feature = "rand")]
pub fn generate_biased(mut rng: impl CryptoRng + RngCore) -> Self {
let mut buf = [0u8; 64];
rng.fill_bytes(&mut buf);
Scalar(WideScalarImpl::from_bytes(&buf).reduce())
}
#[cfg(feature = "rand")]
pub fn generate_vartime(mut rng: impl CryptoRng + RngCore) -> Self {
let mut bytes = ElementBytes::default();
loop {
rng.fill_bytes(&mut bytes);
let scalar = Scalar::from_bytes(&bytes);
if scalar.is_some().into() {
#[cfg(feature = "zeroize")]
bytes.zeroize();
return scalar.unwrap();
}
}
}
pub fn conditional_add_bit(&self, bit: usize, flag: Choice) -> Self {
Self(self.0.conditional_add_bit(bit, flag))
}
pub fn mul_shift_var(&self, b: &Scalar, shift: usize) -> Self {
Self(self.0.mul_shift_var(&(b.0), shift))
}
}
impl FromBytes for Scalar {
type Size = U32;
fn from_bytes(bytes: &ElementBytes) -> CtOption<Self> {
ScalarImpl::from_bytes(bytes.as_ref()).map(Self)
}
}
impl Shr<usize> for Scalar {
type Output = Self;
fn shr(self, rhs: usize) -> Self::Output {
self.rshift(rhs)
}
}
impl Shr<usize> for &Scalar {
type Output = Scalar;
fn shr(self, rhs: usize) -> Self::Output {
self.rshift(rhs)
}
}
impl ConditionallySelectable for Scalar {
fn conditional_select(a: &Self, b: &Self, choice: Choice) -> Self {
Self(ScalarImpl::conditional_select(&(a.0), &(b.0), choice))
}
}
impl ConstantTimeEq for Scalar {
fn ct_eq(&self, other: &Self) -> Choice {
self.0.ct_eq(&(other.0))
}
}
impl PartialEq for Scalar {
fn eq(&self, other: &Self) -> bool {
self.ct_eq(other).into()
}
}
impl Neg for Scalar {
type Output = Scalar;
fn neg(self) -> Scalar {
self.negate()
}
}
impl Neg for &Scalar {
type Output = Scalar;
fn neg(self) -> Scalar {
self.negate()
}
}
impl Add<&Scalar> for &Scalar {
type Output = Scalar;
fn add(self, other: &Scalar) -> Scalar {
Scalar::add(self, other)
}
}
impl Add<Scalar> for &Scalar {
type Output = Scalar;
fn add(self, other: Scalar) -> Scalar {
Scalar::add(self, &other)
}
}
impl Add<&Scalar> for Scalar {
type Output = Scalar;
fn add(self, other: &Scalar) -> Scalar {
Scalar::add(&self, other)
}
}
impl AddAssign<Scalar> for Scalar {
fn add_assign(&mut self, rhs: Scalar) {
*self = Scalar::add(self, &rhs);
}
}
impl Sub<&Scalar> for &Scalar {
type Output = Scalar;
fn sub(self, other: &Scalar) -> Scalar {
Scalar::sub(self, other)
}
}
impl Sub<&Scalar> for Scalar {
type Output = Scalar;
fn sub(self, other: &Scalar) -> Scalar {
Scalar::sub(&self, other)
}
}
impl SubAssign<Scalar> for Scalar {
fn sub_assign(&mut self, rhs: Scalar) {
*self = Scalar::sub(self, &rhs);
}
}
impl Mul<&Scalar> for &Scalar {
type Output = Scalar;
fn mul(self, other: &Scalar) -> Scalar {
Scalar::mul(self, other)
}
}
impl Mul<&Scalar> for Scalar {
type Output = Scalar;
fn mul(self, other: &Scalar) -> Scalar {
Scalar::mul(&self, other)
}
}
impl MulAssign<Scalar> for Scalar {
fn mul_assign(&mut self, rhs: Scalar) {
*self = Scalar::mul(self, &rhs);
}
}
impl Invert for Scalar {
type Output = Self;
fn invert(&self) -> CtOption<Self> {
Scalar::invert(self)
}
}
impl From<Scalar> for ElementBytes {
fn from(scalar: Scalar) -> Self {
scalar.to_bytes()
}
}
#[cfg(feature = "rand")]
impl Generate for Scalar {
fn generate(rng: impl CryptoRng + RngCore) -> Self {
Self::generate_vartime(rng)
}
}
#[cfg(feature = "zeroize")]
impl Zeroize for Scalar {
fn zeroize(&mut self) {
self.0.zeroize()
}
}
#[cfg(test)]
mod tests {
use super::Scalar;
use crate::arithmetic::util::{biguint_to_bytes, bytes_to_biguint};
use elliptic_curve::FromBytes;
use num_bigint::{BigUint, ToBigUint};
use proptest::prelude::*;
impl From<&BigUint> for Scalar {
fn from(x: &BigUint) -> Self {
debug_assert!(x < &Scalar::modulus_as_biguint());
let bytes = biguint_to_bytes(x);
Self::from_bytes(&bytes.into()).unwrap()
}
}
impl From<BigUint> for Scalar {
fn from(x: BigUint) -> Self {
Self::from(&x)
}
}
impl ToBigUint for Scalar {
fn to_biguint(&self) -> Option<BigUint> {
Some(bytes_to_biguint(self.to_bytes().as_ref()))
}
}
#[test]
fn is_high() {
let high: bool = Scalar::zero().is_high().into();
assert!(!high);
let m = Scalar::modulus_as_biguint();
let m_by_2 = &m >> 1;
let one = 1.to_biguint().unwrap();
let high: bool = Scalar::from(&m_by_2 - &one).is_high().into();
assert!(!high);
let high: bool = Scalar::from(&m_by_2).is_high().into();
assert!(high);
let high: bool = Scalar::from(&m - &one).is_high().into();
assert!(high);
}
#[test]
fn negate() {
let zero_neg = -Scalar::zero();
assert_eq!(zero_neg, Scalar::zero());
let m = Scalar::modulus_as_biguint();
let one = 1.to_biguint().unwrap();
let m_minus_one = &m - &one;
let m_by_2 = &m >> 1;
let one_neg = -Scalar::one();
assert_eq!(one_neg, Scalar::from(&m_minus_one));
let frac_modulus_2_neg = -Scalar::from(&m_by_2);
let frac_modulus_2_plus_one = Scalar::from(&m_by_2 + &one);
assert_eq!(frac_modulus_2_neg, frac_modulus_2_plus_one);
let modulus_minus_one_neg = -Scalar::from(&m - &one);
assert_eq!(modulus_minus_one_neg, Scalar::one());
}
#[test]
fn add_result_within_256_bits() {
let t = 1.to_biguint().unwrap() << 255;
let one = 1.to_biguint().unwrap();
let a = Scalar::from(&t - &one);
let b = Scalar::from(&t);
let res = &a + &b;
let m = Scalar::modulus_as_biguint();
let res_ref = Scalar::from((&t + &t - &one) % &m);
assert_eq!(res, res_ref);
}
#[cfg(feature = "rand")]
#[test]
fn generate_biased() {
use elliptic_curve::rand_core::OsRng;
let a = Scalar::generate_biased(&mut OsRng);
assert_eq!((a - &a).is_zero().unwrap_u8(), 1);
}
#[cfg(feature = "rand")]
#[test]
fn generate_vartime() {
use elliptic_curve::rand_core::OsRng;
let a = Scalar::generate_vartime(&mut OsRng);
assert_eq!((a - &a).is_zero().unwrap_u8(), 1);
}
prop_compose! {
fn scalar()(bytes in any::<[u8; 32]>()) -> Scalar {
let mut res = bytes_to_biguint(&bytes);
let m = Scalar::modulus_as_biguint();
if res >= m {
res -= m;
}
Scalar::from(&res)
}
}
proptest! {
#[test]
fn fuzzy_roundtrip_to_bytes(a in scalar()) {
let a_back = Scalar::from_bytes(&a.to_bytes().into()).unwrap();
assert_eq!(a, a_back);
}
#[test]
#[cfg(feature = "endomorphism-mul")]
fn fuzzy_roundtrip_to_bytes_unchecked(a in scalar()) {
let bytes = a.to_bytes();
let a_back = Scalar::from_bytes_unchecked(bytes.as_ref());
assert_eq!(a, a_back);
}
#[test]
fn fuzzy_add(a in scalar(), b in scalar()) {
let a_bi = a.to_biguint().unwrap();
let b_bi = b.to_biguint().unwrap();
let res_bi = (&a_bi + &b_bi) % &Scalar::modulus_as_biguint();
let res_ref = Scalar::from(&res_bi);
let res_test = a.add(&b);
assert_eq!(res_ref, res_test);
}
#[test]
fn fuzzy_sub(a in scalar(), b in scalar()) {
let a_bi = a.to_biguint().unwrap();
let b_bi = b.to_biguint().unwrap();
let m = Scalar::modulus_as_biguint();
let res_bi = (&m + &a_bi - &b_bi) % &m;
let res_ref = Scalar::from(&res_bi);
let res_test = a.sub(&b);
assert_eq!(res_ref, res_test);
}
#[test]
fn fuzzy_neg(a in scalar()) {
let a_bi = a.to_biguint().unwrap();
let m = Scalar::modulus_as_biguint();
let res_bi = (&m - &a_bi) % &m;
let res_ref = Scalar::from(&res_bi);
let res_test = -a;
assert_eq!(res_ref, res_test);
}
#[test]
fn fuzzy_mul(a in scalar(), b in scalar()) {
let a_bi = a.to_biguint().unwrap();
let b_bi = b.to_biguint().unwrap();
let res_bi = (&a_bi * &b_bi) % &Scalar::modulus_as_biguint();
let res_ref = Scalar::from(&res_bi);
let res_test = a.mul(&b);
assert_eq!(res_ref, res_test);
}
#[test]
fn fuzzy_rshift(a in scalar(), b in 0usize..512) {
let a_bi = a.to_biguint().unwrap();
let res_bi = &a_bi >> b;
let res_ref = Scalar::from(&res_bi);
let res_test = a >> b;
assert_eq!(res_ref, res_test);
}
#[test]
fn fuzzy_invert(
a in scalar()
) {
let a = if bool::from(a.is_zero()) { Scalar::one() } else { a };
let a_bi = a.to_biguint().unwrap();
let inv = a.invert().unwrap();
let inv_bi = inv.to_biguint().unwrap();
let m = Scalar::modulus_as_biguint();
assert_eq!((&inv_bi * &a_bi) % &m, 1.to_biguint().unwrap());
}
}
}