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
use std::ops::{Add, Index, IndexMut, Mul, Sub};
use rand_core::{CryptoRng, RngCore};
use subtle::{Choice, ConstantTimeEq};
use crate::constants;
#[derive(Debug, Copy, Clone)]
pub struct Scalar(pub(crate) [u32; 14]);
pub(crate) const MODULUS: Scalar = constants::BASEPOINT_ORDER;
const R2: Scalar = Scalar([
0x049b9b60, 0xe3539257, 0xc1b195d9, 0x7af32c4b, 0x88ea1859, 0x0d66de23, 0x5ee4d838, 0xae17cf72,
0xa3c47c44, 0x1a9cc14b, 0xe4d070af, 0x2052bcb7, 0xf823b729, 0x3402a939,
]);
const R: Scalar = Scalar([
0x529eec34, 0x721cf5b5, 0xc8e9c2ab, 0x7a4cf635, 0x44a725bf, 0xeec492d9, 0xcd77058, 0x2, 0, 0,
0, 0, 0, 0,
]);
impl ConstantTimeEq for Scalar {
fn ct_eq(&self, other: &Self) -> Choice {
self.to_bytes().ct_eq(&other.to_bytes())
}
}
impl PartialEq for Scalar {
fn eq(&self, other: &Scalar) -> bool {
self.ct_eq(&other).into()
}
}
impl Eq for Scalar {}
impl From<u32> for Scalar {
fn from(a: u32) -> Scalar {
Scalar([a, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
}
}
impl Index<usize> for Scalar {
type Output = u32;
fn index(&self, index: usize) -> &Self::Output {
&self.0[index]
}
}
impl IndexMut<usize> for Scalar {
fn index_mut(&mut self, index: usize) -> &mut Self::Output {
&mut self.0[index]
}
}
impl Add<Scalar> for Scalar {
type Output = Scalar;
fn add(self, rhs: Scalar) -> Self::Output {
add(&self, &rhs)
}
}
impl Mul<Scalar> for Scalar {
type Output = Scalar;
fn mul(self, rhs: Scalar) -> Self::Output {
let unreduced = montgomery_multiply(&self, &rhs);
montgomery_multiply(&unreduced, &R2)
}
}
impl Sub<Scalar> for Scalar {
type Output = Scalar;
fn sub(self, rhs: Scalar) -> Self::Output {
sub_extra(&self, &rhs, 0)
}
}
impl Default for Scalar {
fn default() -> Scalar {
Scalar::zero()
}
}
impl Scalar {
pub const fn one() -> Scalar {
Scalar([1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
}
pub const fn zero() -> Scalar {
Scalar([0; 14])
}
pub(crate) fn div_by_four(&mut self) {
for i in 0..=12 {
self.0[i] = (self.0[i + 1] << 30) | (self.0[i] >> 2);
}
self.0[13] >>= 2
}
pub(crate) fn to_radix_16(&self) -> [i8; 113] {
let bytes = self.to_bytes();
let mut output = [0i8; 113];
#[inline(always)]
fn bot_half(x: u8) -> u8 {
(x >> 0) & 15
}
#[inline(always)]
fn top_half(x: u8) -> u8 {
(x >> 4) & 15
}
for i in 0..56 {
output[2 * i] = bot_half(bytes[i]) as i8;
output[2 * i + 1] = top_half(bytes[i]) as i8;
}
for i in 0..112 {
let carry = (output[i] + 8) >> 4;
output[i] -= carry << 4;
output[i + 1] += carry;
}
output
}
pub fn bits(&self) -> Vec<bool> {
let mut bits: Vec<bool> = Vec::with_capacity(14 * 32);
for limb in self.0.iter() {
for j in 0..32 {
bits.push(limb & (1 << j) != 0)
}
}
bits
}
pub fn from_bytes(bytes: [u8; 56]) -> Scalar {
let load7 = |input: &[u8]| -> u64 {
(input[0] as u64)
| ((input[1] as u64) << 8)
| ((input[2] as u64) << 16)
| ((input[3] as u64) << 24)
};
let mut res = Scalar::zero();
for i in 0..14 {
let out = load7(&bytes[i * 4..]);
res[i] = out as u32;
}
res
}
pub fn to_bytes(&self) -> [u8; 56] {
let mut res = [0u8; 56];
for i in 0..14 {
let mut l = self.0[i];
for j in 0..4 {
res[4 * i + j] = l as u8;
l >>= 8;
}
}
res
}
fn square(&self) -> Scalar {
montgomery_multiply(&self, &self)
}
pub fn invert(&self) -> Self {
let mut pre_comp: Vec<Scalar> = vec![Scalar::zero(); 8];
let mut result = Scalar::zero();
let scalar_window_bits = 3;
let last = (1 << scalar_window_bits) - 1;
pre_comp[0] = montgomery_multiply(self, &R2);
if last > 0 {
pre_comp[last] = montgomery_multiply(&pre_comp[0], &pre_comp[0]);
}
for i in 1..=last {
pre_comp[i] = montgomery_multiply(&pre_comp[i - 1], &pre_comp[last])
}
let mut residue: usize = 0;
let mut trailing: usize = 0;
let mut started: usize = 0;
let loop_start = -scalar_window_bits as isize;
let loop_end = 446 - 1;
for i in (loop_start..=loop_end).rev() {
if started != 0 {
result = result.square()
}
let mut w: u32;
if i >= 0 {
w = MODULUS[(i / 32) as usize];
} else {
w = 0;
}
if i >= 0 && i < 32 {
w -= 2
}
residue = (((residue as u32) << 1) | ((w >> ((i as u32) % 32)) & 1)) as usize;
if residue >> scalar_window_bits != 0 {
trailing = residue;
residue = 0
}
if trailing > 0 && (trailing & ((1 << scalar_window_bits) - 1)) == 0 {
if started != 0 {
result = montgomery_multiply(
&result,
&pre_comp[trailing >> (scalar_window_bits + 1)],
)
} else {
result = pre_comp[trailing >> (scalar_window_bits + 1)];
started = 1
}
trailing = 0
}
trailing <<= 1
}
montgomery_multiply(&result, &Scalar::one())
}
pub fn halve(&self) -> Self {
let mut result = Scalar::zero();
let mask = 0u32.wrapping_sub(self[0] & 1);
let mut chain = 0u64;
for i in 0..14 {
chain += (self[i] as u64) + ((MODULUS[i] & mask) as u64);
result[i] = chain as u32;
chain >>= 32
}
for i in 0..13 {
result[i] = (result[i] >> 1) | (result[i + 1] << 31);
}
result[13] = (result[13] >> 1) | ((chain << 31) as u32);
result
}
pub fn from_canonical_bytes(bytes: [u8; 57]) -> Option<Scalar> {
if bytes[56] != 0u8 || (bytes[55] >> 6) != 0u8 {
return None;
}
let bytes: [u8; 56] = std::array::from_fn(|i| bytes[i]);
let candidate = Scalar::from_bytes(bytes);
let reduced = sub_extra(&candidate, &MODULUS, 0);
if candidate == reduced {
Some(candidate)
} else {
None
}
}
pub fn to_bytes_rfc_8032(&self) -> [u8; 57] {
let bytes = self.to_bytes();
let res: [u8; 57] = std::array::from_fn(|i| if i < 56 { bytes[i] } else { 0 });
res
}
pub fn from_bytes_mod_order_wide(input: &[u8; 114]) -> Scalar {
let lo: [u8; 56] = std::array::from_fn(|i| input[i]);
let lo = Scalar::from_bytes(lo);
let lo = montgomery_multiply(&lo, &R);
let hi: [u8; 56] = std::array::from_fn(|i| input[i + 56]);
let hi = Scalar::from_bytes(hi);
let hi = montgomery_multiply(&hi, &R2);
let top: [u8; 56] = std::array::from_fn(|i| if i < 2 { input[i + 112] } else { 0 });
let top = Scalar::from_bytes(top);
let top = montgomery_multiply(&top, &R2);
let top = montgomery_multiply(&top, &R2);
add(&lo, &hi).add(top)
}
pub fn random<R: RngCore + CryptoRng>(rng: &mut R) -> Self {
let mut scalar_bytes = [0u8; 114];
rng.fill_bytes(&mut scalar_bytes);
Scalar::from_bytes_mod_order_wide(&scalar_bytes)
}
}
pub fn add(a: &Scalar, b: &Scalar) -> Scalar {
let mut result = Scalar::zero();
let mut chain = 0u64;
for i in 0..14 {
chain += (a[i] as u64) + (b[i] as u64);
result[i] = chain as u32;
chain >>= 32;
}
sub_extra(&result, &MODULUS, chain as u32)
}
fn sub_extra(a: &Scalar, b: &Scalar, carry: u32) -> Scalar {
let mut result = Scalar::zero();
let mut chain = 0i64;
for i in 0..14 {
chain += a[i] as i64 - b[i] as i64;
result[i] = chain as u32;
chain >>= 32
}
let borrow = chain + (carry as i64);
assert!(borrow == -1 || borrow == 0);
chain = 0i64;
for i in 0..14 {
chain += (result[i] as i64) + ((MODULUS[i] as i64) & borrow);
result[i] = chain as u32;
chain >>= 32;
}
result
}
fn montgomery_multiply(x: &Scalar, y: &Scalar) -> Scalar {
const MONTGOMERY_FACTOR: u32 = 0xae918bc5;
let mut result = Scalar::zero();
let mut carry = 0u32;
let mul_add = |a: u32, b: u32, c: u32| -> u64 { ((a as u64) * (b as u64)) + (c as u64) };
for i in 0..14 {
let mut chain = 0u64;
for j in 0..14 {
chain += mul_add(x[i], y[j], result[j]);
result[j] = chain as u32;
chain >>= 32;
}
let saved = chain as u32;
let multiplicand = result[0].wrapping_mul(MONTGOMERY_FACTOR);
chain = 0u64;
for j in 0..14 {
chain += mul_add(multiplicand, MODULUS[j], result[j]);
if j > 0 {
result[j - 1] = chain as u32;
}
chain >>= 32;
}
chain += (saved as u64) + (carry as u64);
result[14 - 1] = chain as u32;
carry = (chain >> 32) as u32;
}
sub_extra(&result, &MODULUS, carry)
}
#[cfg(test)]
mod test {
use std::convert::TryInto;
use super::*;
#[test]
fn test_basic_add() {
let five = Scalar::from(5);
let six = Scalar::from(6);
assert_eq!(five + six, Scalar::from(11))
}
#[test]
fn test_basic_sub() {
let ten = Scalar::from(10);
let five = Scalar::from(5);
assert_eq!(ten - five, Scalar::from(5))
}
#[test]
fn test_basic_mul() {
let ten = Scalar::from(10);
let five = Scalar::from(5);
assert_eq!(ten * five, Scalar::from(50))
}
#[test]
fn test_mul() {
let a = Scalar([
0xffb823a3, 0xc96a3c35, 0x7f8ed27d, 0x087b8fb9, 0x1d9ac30a, 0x74d65764, 0xc0be082e,
0xa8cb0ae8, 0xa8fa552b, 0x2aae8688, 0x2c3dc273, 0x47cf8cac, 0x3b089f07, 0x1e63e807,
]);
let b = Scalar([
0xd8bedc42, 0x686eb329, 0xe416b899, 0x17aa6d9b, 0x1e30b38b, 0x188c6b1a, 0xd099595b,
0xbc343bcb, 0x1adaa0e7, 0x24e8d499, 0x8e59b308, 0x0a92de2d, 0xcae1cb68, 0x16c5450a,
]);
let exp = Scalar([
0xa18d010a, 0x1f5b3197, 0x994c9c2b, 0x6abd26f5, 0x08a3a0e4, 0x36a14920, 0x74e9335f,
0x07bcd931, 0xf2d89c1e, 0xb9036ff6, 0x203d424b, 0xfccd61b3, 0x4ca389ed, 0x31e055c1,
]);
assert_eq!(a * b, exp)
}
#[test]
fn test_basic_square() {
let a = Scalar([
0xcf5fac3d, 0x7e56a34b, 0xf640922b, 0x3fa50692, 0x1370f8b8, 0x6f08f331, 0x8dccc486,
0x4bb395e0, 0xf22c6951, 0x21cc3078, 0xd2391f9d, 0x930392e5, 0x04b3273b, 0x31620816,
]);
let expected_a_squared = Scalar([
0x15598f62, 0xb9b1ed71, 0x52fcd042, 0x862a9f10, 0x1e8a309f, 0x9988f8e0, 0xa22347d7,
0xe9ab2c22, 0x38363f74, 0xfd7c58aa, 0xc49a1433, 0xd9a6c4c3, 0x75d3395e, 0x0d79f6e3,
]);
assert_eq!(a.square(), expected_a_squared)
}
#[test]
fn test_sanity_check_index_mut() {
let mut x = Scalar::one();
x[0] = 2u32;
assert_eq!(x, Scalar::from(2))
}
#[test]
fn test_basic_halving() {
let eight = Scalar::from(8);
let four = Scalar::from(4);
let two = Scalar::from(2);
assert_eq!(eight.halve(), four);
assert_eq!(four.halve(), two);
assert_eq!(two.halve(), Scalar::one());
}
#[test]
fn test_equals() {
let a = Scalar::from(5);
let b = Scalar::from(5);
let c = Scalar::from(10);
assert!(a == b);
assert!(!(a == c))
}
#[test]
fn test_basic_inversion() {
for i in 1..=100 {
let x = Scalar::from(i);
let x_inv = x.invert();
assert_eq!(x_inv * x, Scalar::one())
}
let zero = Scalar::zero();
let expected_zero = zero.invert();
assert_eq!(expected_zero, zero)
}
#[test]
fn test_serialise() {
let scalar = Scalar([
0x15598f62, 0xb9b1ed71, 0x52fcd042, 0x862a9f10, 0x1e8a309f, 0x9988f8e0, 0xa22347d7,
0xe9ab2c22, 0x38363f74, 0xfd7c58aa, 0xc49a1433, 0xd9a6c4c3, 0x75d3395e, 0x0d79f6e3,
]);
let got = Scalar::from_bytes(scalar.to_bytes());
assert_eq!(scalar, got)
}
#[test]
fn test_debug() {
let k = Scalar([
200, 210, 250, 145, 130, 180, 147, 122, 222, 230, 214, 247, 203, 32,
]);
let s = k;
dbg!(&s.to_radix_16()[..]);
}
#[test]
fn test_from_canonical_bytes() {
let mut bytes: [u8; 57] = hex::decode("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff").unwrap().try_into().unwrap();
bytes.reverse();
let s = Scalar::from_canonical_bytes(bytes);
assert_eq!(s, None);
let mut bytes: [u8; 57] = hex::decode("003fffffffffffffffffffffffffffffffffffffffffffffffffffffff7cca23e9c44edb49aed63690216cc2728dc58f552378c292ab5844f3").unwrap().try_into().unwrap();
bytes.reverse();
let s = Scalar::from_canonical_bytes(bytes);
assert_eq!(s, None);
let mut bytes: [u8; 57] = hex::decode("003fffffffffffffffffffffffffffffffffffffffffffffffffffffff7cca23e9c44edb49aed63690216cc2728dc58f552378c292ab5844f2").unwrap().try_into().unwrap();
bytes.reverse();
let s = Scalar::from_canonical_bytes(bytes);
match s {
Some(s) => assert_eq!(s, Scalar::zero() - Scalar::one()),
None => panic!("should not return None"),
};
}
#[test]
fn test_from_bytes_mod_order_wide() {
let mut bytes: [u8; 114] = hex::decode("000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003fffffffffffffffffffffffffffffffffffffffffffffffffffffff7cca23e9c44edb49aed63690216cc2728dc58f552378c292ab5844f3").unwrap().try_into().unwrap();
bytes.reverse();
let s = Scalar::from_bytes_mod_order_wide(&bytes);
assert_eq!(s, Scalar::zero());
let mut bytes: [u8; 114] = hex::decode("000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003fffffffffffffffffffffffffffffffffffffffffffffffffffffff7cca23e9c44edb49aed63690216cc2728dc58f552378c292ab5844f2").unwrap().try_into().unwrap();
bytes.reverse();
let s = Scalar::from_bytes_mod_order_wide(&bytes);
assert_eq!(s, Scalar::zero() - Scalar::one());
let mut bytes: [u8; 114] = hex::decode("000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003fffffffffffffffffffffffffffffffffffffffffffffffffffffff7cca23e9c44edb49aed63690216cc2728dc58f552378c292ab5844f4").unwrap().try_into().unwrap();
bytes.reverse();
let s = Scalar::from_bytes_mod_order_wide(&bytes);
assert_eq!(s, Scalar::one());
let mut bytes: [u8; 114] = hex::decode("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff").unwrap().try_into().unwrap();
bytes.reverse();
let s = Scalar::from_bytes_mod_order_wide(&bytes);
let mut bytes: [u8; 57] = hex::decode("002939f823b7292052bcb7e4d070af1a9cc14ba3c47c44ae17cf72c985bb24b6c520e319fb37a63e29800f160787ad1d2e11883fa931e7de81").unwrap().try_into().unwrap();
bytes.reverse();
let reduced = Scalar::from_canonical_bytes(bytes).unwrap();
assert_eq!(s, reduced);
}
#[test]
fn test_to_bytes_rfc8032() {
let mut bytes: [u8; 57] = hex::decode("003fffffffffffffffffffffffffffffffffffffffffffffffffffffff7cca23e9c44edb49aed63690216cc2728dc58f552378c292ab5844f2").unwrap().try_into().unwrap();
bytes.reverse();
let x = Scalar::zero() - Scalar::one();
let candidate = x.to_bytes_rfc_8032();
assert_eq!(bytes, candidate);
}
}