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
// SPDX-License-Identifier: MIT
//! Generic Field Traits
use core::convert::TryInto;
use core::iter::{Skip, Take};
use core::{fmt, hash, iter, ops};
/// A generic field.
pub trait Field:
Sized
+ PartialEq
+ Eq
+ Clone
+ Default
+ hash::Hash
+ fmt::Debug
+ fmt::Display
+ iter::Sum
+ for<'a> iter::Sum<&'a Self>
+ ops::Add<Self, Output = Self>
+ ops::Sub<Self, Output = Self>
+ ops::AddAssign
+ ops::SubAssign
+ ops::Mul<Self, Output = Self>
+ ops::MulAssign
+ ops::Div<Self, Output = Self>
+ ops::DivAssign
+ for<'a> ops::Add<&'a Self, Output = Self>
+ for<'a> ops::AddAssign<&'a Self>
+ for<'a> ops::Sub<&'a Self, Output = Self>
+ for<'a> ops::SubAssign<&'a Self>
+ for<'a> ops::Mul<&'a Self, Output = Self>
+ for<'a> ops::MulAssign<&'a Self>
+ for<'a> ops::Div<&'a Self, Output = Self>
+ for<'a> ops::DivAssign<&'a Self>
+ ops::Neg<Output = Self>
{
/// The zero constant of the field.
const ZERO: Self;
/// The one constant of the field.
const ONE: Self;
/// A primitive element, i.e. a generator of the multiplicative group of the field.
const GENERATOR: Self;
/// The smallest integer n such that 1 + ... + 1, n times, equals 0.
///
/// If this is 0, this indicates that no such integer exists.
const CHARACTERISTIC: usize;
/// The order of the multiplicative group of the field.
const MULTIPLICATIVE_ORDER: usize;
/// All factors of the multiplicative order, in increasing order.
///
/// Include both 1 and the number itself. So for example if you have `n` distinct
/// prime factors which each appearing once, this array would have size `2^n`.
const MULTIPLICATIVE_ORDER_FACTORS: &'static [usize];
/// Computes the multiplicative inverse of an element.
fn multiplicative_inverse(self) -> Self;
/// Takes the element times some integer.
fn muli(&self, mut n: i64) -> Self {
let base = if n >= 0 {
self.clone()
} else {
n *= -1;
self.clone().multiplicative_inverse()
};
let mut ret = Self::ZERO;
// Special case some particular characteristics
match Self::CHARACTERISTIC {
1 => unreachable!("no field has characteristic 1"),
2 => {
// Special-case 2 because it's easy and also the only characteristic used
// within the library. The compiler should prune away the other code.
if n % 2 == 0 {
Self::ZERO
} else {
self.clone()
}
}
x => {
// This is identical to powi below, but with * replaced by +.
if x > 0 {
n %= x as i64;
}
let mut mask = x.next_power_of_two() as i64;
while mask > 0 {
ret += ret.clone();
if n & mask != 0 {
ret += &base;
}
mask >>= 1;
}
ret
}
}
}
/// Takes the element to the power of some integer.
fn powi(&self, mut n: i64) -> Self {
let base = if n >= 0 {
self.clone()
} else {
n *= -1;
self.clone().multiplicative_inverse()
};
n %= Self::MULTIPLICATIVE_ORDER as i64;
let mut mask = Self::MULTIPLICATIVE_ORDER.next_power_of_two() as i64;
let mut ret = Self::ONE;
while mask > 0 {
ret *= ret.clone();
if n & mask != 0 {
ret *= &base;
}
mask >>= 1;
}
ret
}
/// The multiplicative order of an element.
fn multiplicative_order(&self) -> usize {
for &ord in Self::MULTIPLICATIVE_ORDER_FACTORS {
if self.powi(ord as i64) == Self::ONE {
return ord;
}
}
panic!(
"bug: `ExtensionField::MULTIPLICATIVE_ORDER_FACTORS` did not include full group order"
);
}
/// Constructs an iterator over all the powers of an element from 0 onward.
fn powers(self) -> Powers<Self> { Powers { base: self, next: Self::ONE } }
/// Constructs an iterator over all the powers of an element within a given range.
///
/// # Panics
///
/// Panics if given a range whose start is greater than its end, or whose range
/// is from 0 to `usize::MAX`. Its intended use is with [`crate::Checksum::ROOT_EXPONENTS`]
/// for which neither of these conditions should ever be true.
fn powers_range(self, range: ops::RangeInclusive<usize>) -> Take<Skip<Powers<Self>>> {
self.powers().skip(*range.start()).take(*range.end() - range.start() + 1)
}
}
/// Trait describing a simple extension field (field obtained from another by
/// adjoining one element).
pub trait ExtensionField: Field + From<Self::BaseField> + TryInto<Self::BaseField> {
/// The type of the base field.
type BaseField: Field;
/// The degree of the extension.
///
/// Must be strictly greater than 1.
const DEGREE: usize;
/// An extension field is defined as `GF32[x]/p(x)`, for some irreducible
/// monic polynomial p whose degree then becomes the degree of the extension.
///
/// If p(x) = x^d + ... p_1x + p_0 we can represent p by an element of
/// the extension field, specifically the image of p(x) - x^d. Equivalently,
/// if zeta is the image of x in the quotient map, then this value is
/// equal to zeta^d.
///
/// This value is used to define multiplication in the extension field.
const POLYNOMIAL: Self;
/// The element which is adjoined to the base field to get this field.
///
/// In other words, the image of x in the isomorphism from
/// [`Self::BaseField`]`[x]`/[`Self::POLYNOMIAL`] to [`Self`].
const EXT_ELEM: Self;
}
mod private {
/// Sealing trait.
pub trait Sealed {}
impl Sealed for crate::Fe32 {}
impl Sealed for crate::Fe1024 {}
impl Sealed for crate::Fe32768 {}
}
/// Sealed trait which extends [`Field`] with extra functionality
/// needed internally to this library.
///
/// This trait should not be used directly by users of the library.
pub trait Bech32Field: private::Sealed + Sized {
/// Adds a value to `self`. This is a helper function for implementing the
/// [`ops::Add`] and [`ops::AddAssign`] traits.
fn _add(&self, other: &Self) -> Self;
/// Subtracts a value from `self`. This is a helper function for implementing the
/// [`ops::Sub`] and [`ops::SubAssign`] traits.
fn _sub(&self, other: &Self) -> Self {
self._add(other) // all fields in this library are binary fields
}
/// Multiplies a value by `self`. This is a helper function for implementing the
/// [`ops::Mul`] and [`ops::MulAssign`] traits.
fn _mul(&self, other: &Self) -> Self;
/// Divides a value from `self`. This is a helper function for implementing the
/// [`ops::Div`] and [`ops::DivAssign`] traits.
fn _div(&self, other: &Self) -> Self;
/// Computes the additive inverse of an element.
fn _neg(self) -> Self;
/// Utility method to format a field element as Rust code.
fn format_as_rust_code(&self, f: &mut fmt::Formatter) -> fmt::Result;
}
macro_rules! impl_ops_for_fe {
(impl for $op:ident) => {
// add
impl core::ops::Add<$op> for $op {
type Output = Self;
#[inline]
fn add(self, other: $op) -> $op { $crate::primitives::Bech32Field::_add(&self, &other) }
}
impl core::ops::Add<&$op> for $op {
type Output = Self;
#[inline]
fn add(self, other: &$op) -> $op { $crate::primitives::Bech32Field::_add(&self, other) }
}
impl core::ops::Add<$op> for &$op {
type Output = $op;
#[inline]
fn add(self, other: $op) -> $op { $crate::primitives::Bech32Field::_add(self, &other) }
}
impl core::ops::Add<&$op> for &$op {
type Output = $op;
#[inline]
fn add(self, other: &$op) -> $op { $crate::primitives::Bech32Field::_add(self, other) }
}
impl core::ops::AddAssign for $op {
#[inline]
fn add_assign(&mut self, other: $op) {
*self = $crate::primitives::Bech32Field::_add(self, &other)
}
}
impl core::ops::AddAssign<&$op> for $op {
#[inline]
fn add_assign(&mut self, other: &$op) {
*self = $crate::primitives::Bech32Field::_add(self, other)
}
}
// sub
impl core::ops::Sub<$op> for $op {
type Output = Self;
#[inline]
fn sub(self, other: $op) -> $op { $crate::primitives::Bech32Field::_sub(&self, &other) }
}
impl core::ops::Sub<&$op> for $op {
type Output = Self;
#[inline]
fn sub(self, other: &$op) -> $op { $crate::primitives::Bech32Field::_sub(&self, other) }
}
impl core::ops::Sub<$op> for &$op {
type Output = $op;
#[inline]
fn sub(self, other: $op) -> $op { $crate::primitives::Bech32Field::_sub(self, &other) }
}
impl core::ops::Sub<&$op> for &$op {
type Output = $op;
#[inline]
fn sub(self, other: &$op) -> $op { $crate::primitives::Bech32Field::_sub(self, other) }
}
impl core::ops::SubAssign for $op {
#[inline]
fn sub_assign(&mut self, other: $op) {
*self = $crate::primitives::Bech32Field::_sub(self, &other)
}
}
impl core::ops::SubAssign<&$op> for $op {
#[inline]
fn sub_assign(&mut self, other: &$op) {
*self = $crate::primitives::Bech32Field::_sub(self, other)
}
}
// mul
impl core::ops::Mul<$op> for $op {
type Output = Self;
#[inline]
fn mul(self, other: $op) -> $op { $crate::primitives::Bech32Field::_mul(&self, &other) }
}
impl core::ops::Mul<&$op> for $op {
type Output = Self;
#[inline]
fn mul(self, other: &$op) -> $op { $crate::primitives::Bech32Field::_mul(&self, other) }
}
impl core::ops::Mul<$op> for &$op {
type Output = $op;
#[inline]
fn mul(self, other: $op) -> $op { $crate::primitives::Bech32Field::_mul(self, &other) }
}
impl core::ops::Mul<&$op> for &$op {
type Output = $op;
#[inline]
fn mul(self, other: &$op) -> $op { $crate::primitives::Bech32Field::_mul(self, other) }
}
impl core::ops::MulAssign for $op {
#[inline]
fn mul_assign(&mut self, other: $op) {
*self = $crate::primitives::Bech32Field::_mul(self, &other)
}
}
impl core::ops::MulAssign<&$op> for $op {
#[inline]
fn mul_assign(&mut self, other: &$op) {
*self = $crate::primitives::Bech32Field::_mul(self, other)
}
}
// div
impl core::ops::Div<$op> for $op {
type Output = Self;
#[inline]
fn div(self, other: $op) -> $op { $crate::primitives::Bech32Field::_div(&self, &other) }
}
impl core::ops::Div<&$op> for $op {
type Output = Self;
#[inline]
fn div(self, other: &$op) -> $op { $crate::primitives::Bech32Field::_div(&self, other) }
}
impl core::ops::Div<$op> for &$op {
type Output = $op;
#[inline]
fn div(self, other: $op) -> $op { $crate::primitives::Bech32Field::_div(self, &other) }
}
impl core::ops::Div<&$op> for &$op {
type Output = $op;
#[inline]
fn div(self, other: &$op) -> $op { $crate::primitives::Bech32Field::_div(self, other) }
}
impl core::ops::DivAssign for $op {
#[inline]
fn div_assign(&mut self, other: $op) {
*self = $crate::primitives::Bech32Field::_div(self, &other)
}
}
impl core::ops::DivAssign<&$op> for $op {
#[inline]
fn div_assign(&mut self, other: &$op) {
*self = $crate::primitives::Bech32Field::_div(self, other)
}
}
// neg
impl core::ops::Neg for $op {
type Output = Self;
#[inline]
fn neg(self) -> Self { $crate::primitives::Bech32Field::_neg(self) }
}
// sum
impl core::iter::Sum for $op {
fn sum<I: Iterator<Item = Self>>(iter: I) -> Self {
iter.fold(crate::primitives::Field::ZERO, |i, acc| i + acc)
}
}
impl<'s> core::iter::Sum<&'s Self> for $op {
fn sum<I: Iterator<Item = &'s Self>>(iter: I) -> Self {
iter.fold(crate::primitives::Field::ZERO, |i, acc| i + acc)
}
}
};
}
pub(super) use impl_ops_for_fe;
/// An iterator over the powers of a field, starting from zero.
///
/// This iterator starts from 1, but has an optimized version of [`Iterator::nth`]
/// which allows efficient construction.
pub struct Powers<F: Field> {
base: F,
next: F,
}
impl<F: Field> Iterator for Powers<F> {
type Item = F;
fn next(&mut self) -> Option<F> {
let ret = Some(self.next.clone());
self.next *= &self.base;
ret
}
/// Compute next by calling `F::powi`.
///
/// The default implementation of `nth` will simply call the iterator `n`
/// times, throwing away the result, which takes O(n) field multiplications.
/// For a power iterator we can do much better, taking O(log(n)) multiplications.
///
/// This is important because this method is called internally by `Iterator::skip`.
fn nth(&mut self, n: usize) -> Option<F> {
let ni64 = (n % F::MULTIPLICATIVE_ORDER) as i64; // cast ok since modulus should be small
self.next *= self.base.powi(ni64);
self.next()
}
}