@decryption/curves 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +75 -0
- package/abstract/bls.d.ts +410 -0
- package/abstract/bls.js +433 -0
- package/abstract/curve.d.ts +441 -0
- package/abstract/curve.js +622 -0
- package/abstract/edwards.d.ts +319 -0
- package/abstract/edwards.js +697 -0
- package/abstract/fft.d.ts +438 -0
- package/abstract/fft.js +580 -0
- package/abstract/frost.d.ts +292 -0
- package/abstract/frost.js +705 -0
- package/abstract/hash-to-curve.d.ts +238 -0
- package/abstract/hash-to-curve.js +353 -0
- package/abstract/modular.d.ts +550 -0
- package/abstract/modular.js +872 -0
- package/abstract/montgomery.d.ts +95 -0
- package/abstract/montgomery.js +180 -0
- package/abstract/oprf.d.ts +354 -0
- package/abstract/oprf.js +358 -0
- package/abstract/poseidon.d.ts +198 -0
- package/abstract/poseidon.js +471 -0
- package/abstract/tower.d.ts +213 -0
- package/abstract/tower.js +963 -0
- package/abstract/weierstrass.d.ts +587 -0
- package/abstract/weierstrass.js +1421 -0
- package/bls12-381.d.ts +23 -0
- package/bls12-381.js +680 -0
- package/bn254.d.ts +74 -0
- package/bn254.js +248 -0
- package/ed25519.d.ts +211 -0
- package/ed25519.js +626 -0
- package/ed448.d.ts +184 -0
- package/ed448.js +596 -0
- package/esm/abstract/bls.js +429 -0
- package/esm/abstract/curve.js +610 -0
- package/esm/abstract/edwards.js +691 -0
- package/esm/abstract/fft.js +567 -0
- package/esm/abstract/frost.js +702 -0
- package/esm/abstract/hash-to-curve.js +345 -0
- package/esm/abstract/modular.js +849 -0
- package/esm/abstract/montgomery.js +177 -0
- package/esm/abstract/oprf.js +355 -0
- package/esm/abstract/poseidon.js +462 -0
- package/esm/abstract/tower.js +925 -0
- package/esm/abstract/weierstrass.js +1411 -0
- package/esm/bls12-381.js +677 -0
- package/esm/bn254.js +244 -0
- package/esm/ed25519.js +622 -0
- package/esm/ed448.js +593 -0
- package/esm/index.js +38 -0
- package/esm/misc.js +211 -0
- package/esm/nist.js +266 -0
- package/esm/secp256k1.js +465 -0
- package/esm/utils.js +597 -0
- package/esm/webcrypto.js +362 -0
- package/index.d.ts +0 -0
- package/index.js +38 -0
- package/misc.d.ts +113 -0
- package/misc.js +216 -0
- package/nist.d.ts +136 -0
- package/nist.js +269 -0
- package/package.json +46 -0
- package/secp256k1.d.ts +152 -0
- package/secp256k1.js +468 -0
- package/utils.d.ts +535 -0
- package/utils.js +626 -0
- package/webcrypto.d.ts +240 -0
- package/webcrypto.js +365 -0
package/abstract/fft.js
ADDED
|
@@ -0,0 +1,580 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.FFTCore = void 0;
|
|
4
|
+
exports.isPowerOfTwo = isPowerOfTwo;
|
|
5
|
+
exports.nextPowerOfTwo = nextPowerOfTwo;
|
|
6
|
+
exports.reverseBits = reverseBits;
|
|
7
|
+
exports.log2 = log2;
|
|
8
|
+
exports.bitReversalInplace = bitReversalInplace;
|
|
9
|
+
exports.bitReversalPermutation = bitReversalPermutation;
|
|
10
|
+
exports.rootsOfUnity = rootsOfUnity;
|
|
11
|
+
exports.FFT = FFT;
|
|
12
|
+
exports.poly = poly;
|
|
13
|
+
function checkU32(n) {
|
|
14
|
+
// 0xff_ff_ff_ff
|
|
15
|
+
if (!Number.isSafeInteger(n) || n < 0 || n > 0xffffffff)
|
|
16
|
+
throw new Error('wrong u32 integer:' + n);
|
|
17
|
+
return n;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Checks if integer is in form of `1 << X`.
|
|
21
|
+
* @param x - Integer to inspect.
|
|
22
|
+
* @returns `true` when the value is a power of two.
|
|
23
|
+
* @throws If `x` is not a valid unsigned 32-bit integer. {@link Error}
|
|
24
|
+
* @example
|
|
25
|
+
* Validate that an FFT size is a power of two.
|
|
26
|
+
*
|
|
27
|
+
* ```ts
|
|
28
|
+
* isPowerOfTwo(8);
|
|
29
|
+
* ```
|
|
30
|
+
*/
|
|
31
|
+
function isPowerOfTwo(x) {
|
|
32
|
+
checkU32(x);
|
|
33
|
+
return (x & (x - 1)) === 0 && x !== 0;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* @param n - Input value.
|
|
37
|
+
* @returns Next power of two within the u32/array-length domain.
|
|
38
|
+
* @throws If `n` is not a valid unsigned 32-bit integer. {@link Error}
|
|
39
|
+
* @example
|
|
40
|
+
* Round an integer up to the FFT size it needs.
|
|
41
|
+
*
|
|
42
|
+
* ```ts
|
|
43
|
+
* nextPowerOfTwo(9);
|
|
44
|
+
* ```
|
|
45
|
+
*/
|
|
46
|
+
function nextPowerOfTwo(n) {
|
|
47
|
+
checkU32(n);
|
|
48
|
+
if (n <= 1)
|
|
49
|
+
return 1;
|
|
50
|
+
// FFT sizes here are used as JS array lengths, so `2^32` is not a meaningful result:
|
|
51
|
+
// keep the fast u32 bit-twiddling path and fail explicitly instead of wrapping to 1.
|
|
52
|
+
if (n > 0x8000_0000)
|
|
53
|
+
throw new Error('nextPowerOfTwo overflow: result does not fit u32');
|
|
54
|
+
return (1 << (log2(n - 1) + 1)) >>> 0;
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* @param n - Value to reverse.
|
|
58
|
+
* @param bits - Number of bits to use.
|
|
59
|
+
* @returns Bit-reversed integer.
|
|
60
|
+
* @throws If `n` is not a valid unsigned 32-bit integer. {@link Error}
|
|
61
|
+
* @example
|
|
62
|
+
* Reverse the low `bits` bits of one index.
|
|
63
|
+
*
|
|
64
|
+
* ```ts
|
|
65
|
+
* reverseBits(3, 3);
|
|
66
|
+
* ```
|
|
67
|
+
*/
|
|
68
|
+
function reverseBits(n, bits) {
|
|
69
|
+
checkU32(n);
|
|
70
|
+
if (!Number.isSafeInteger(bits) || bits < 0 || bits > 32)
|
|
71
|
+
throw new Error(`expected integer 0 <= bits <= 32, got ${bits}`);
|
|
72
|
+
let reversed = 0;
|
|
73
|
+
for (let i = 0; i < bits; i++, n >>>= 1)
|
|
74
|
+
reversed = (reversed << 1) | (n & 1);
|
|
75
|
+
// JS bitwise ops are signed i32; cast back so 32-bit reversals stay in the unsigned u32 domain.
|
|
76
|
+
return reversed >>> 0;
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Similar to `bitLen(x)-1` but much faster for small integers, like indices.
|
|
80
|
+
* @param n - Input value.
|
|
81
|
+
* @returns Base-2 logarithm. For `n = 0`, the current implementation returns `-1`.
|
|
82
|
+
* @throws If `n` is not a valid unsigned 32-bit integer. {@link Error}
|
|
83
|
+
* @example
|
|
84
|
+
* Compute the radix-2 stage count for one transform size.
|
|
85
|
+
*
|
|
86
|
+
* ```ts
|
|
87
|
+
* log2(8);
|
|
88
|
+
* ```
|
|
89
|
+
*/
|
|
90
|
+
function log2(n) {
|
|
91
|
+
checkU32(n);
|
|
92
|
+
return 31 - Math.clz32(n);
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* Moves lowest bit to highest position, which at first step splits
|
|
96
|
+
* array on even and odd indices, then it applied again to each part,
|
|
97
|
+
* which is core of fft
|
|
98
|
+
* @param values - Mutable coefficient array.
|
|
99
|
+
* @returns Mutated input array.
|
|
100
|
+
* @throws If the array length is not a positive power of two. {@link Error}
|
|
101
|
+
* @example
|
|
102
|
+
* Reorder coefficients into bit-reversed order in place.
|
|
103
|
+
*
|
|
104
|
+
* ```ts
|
|
105
|
+
* const values = Uint8Array.from([0, 1, 2, 3]);
|
|
106
|
+
* bitReversalInplace(values);
|
|
107
|
+
* ```
|
|
108
|
+
*/
|
|
109
|
+
function bitReversalInplace(values) {
|
|
110
|
+
const n = values.length;
|
|
111
|
+
// Size-1 FFT is the identity, so bit-reversal must stay a no-op there instead of rejecting it.
|
|
112
|
+
if (!isPowerOfTwo(n))
|
|
113
|
+
throw new Error('expected positive power-of-two length, got ' + n);
|
|
114
|
+
const bits = log2(n);
|
|
115
|
+
for (let i = 0; i < n; i++) {
|
|
116
|
+
const j = reverseBits(i, bits);
|
|
117
|
+
if (i < j) {
|
|
118
|
+
const tmp = values[i];
|
|
119
|
+
values[i] = values[j];
|
|
120
|
+
values[j] = tmp;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
return values;
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* @param values - Input values.
|
|
127
|
+
* @returns Reordered copy.
|
|
128
|
+
* @throws If the array length is not a positive power of two. {@link Error}
|
|
129
|
+
* @example
|
|
130
|
+
* Return a reordered copy instead of mutating the input in place.
|
|
131
|
+
*
|
|
132
|
+
* ```ts
|
|
133
|
+
* const reordered = bitReversalPermutation([0, 1, 2, 3]);
|
|
134
|
+
* ```
|
|
135
|
+
*/
|
|
136
|
+
function bitReversalPermutation(values) {
|
|
137
|
+
return bitReversalInplace(values.slice());
|
|
138
|
+
}
|
|
139
|
+
const _1n = /** @__PURE__ */ BigInt(1);
|
|
140
|
+
function findGenerator(field) {
|
|
141
|
+
let G = BigInt(2);
|
|
142
|
+
for (; field.eql(field.pow(G, field.ORDER >> _1n), field.ONE); G++)
|
|
143
|
+
;
|
|
144
|
+
return G;
|
|
145
|
+
}
|
|
146
|
+
/**
|
|
147
|
+
* We limit roots up to 2**31, which is a lot: 2-billion polynomimal should be rare.
|
|
148
|
+
* @param field - Field implementation.
|
|
149
|
+
* @param generator - Optional generator override.
|
|
150
|
+
* @returns Roots-of-unity cache.
|
|
151
|
+
* @example
|
|
152
|
+
* Cache roots once, then ask for the omega table of one FFT size.
|
|
153
|
+
*
|
|
154
|
+
* ```ts
|
|
155
|
+
* import { rootsOfUnity } from './fft';
|
|
156
|
+
* import { Field } from './modular';
|
|
157
|
+
* const roots = rootsOfUnity(Field(17n));
|
|
158
|
+
* const omega = roots.omega(4);
|
|
159
|
+
* ```
|
|
160
|
+
*/
|
|
161
|
+
function rootsOfUnity(field, generator) {
|
|
162
|
+
// Factor field.ORDER-1 as oddFactor * 2^powerOfTwo
|
|
163
|
+
let oddFactor = field.ORDER - _1n;
|
|
164
|
+
let powerOfTwo = 0;
|
|
165
|
+
for (; (oddFactor & _1n) !== _1n; powerOfTwo++, oddFactor >>= _1n)
|
|
166
|
+
;
|
|
167
|
+
// Find non quadratic residue
|
|
168
|
+
let G = generator !== undefined ? BigInt(generator) : findGenerator(field);
|
|
169
|
+
// Powers of generator
|
|
170
|
+
const omegas = new Array(powerOfTwo + 1);
|
|
171
|
+
omegas[powerOfTwo] = field.pow(G, oddFactor);
|
|
172
|
+
for (let i = powerOfTwo; i > 0; i--)
|
|
173
|
+
omegas[i - 1] = field.sqr(omegas[i]);
|
|
174
|
+
// Compute all roots of unity for powers up to maxPower
|
|
175
|
+
const rootsCache = [];
|
|
176
|
+
const checkBits = (bits) => {
|
|
177
|
+
checkU32(bits);
|
|
178
|
+
if (bits > 31 || bits > powerOfTwo)
|
|
179
|
+
throw new Error('rootsOfUnity: wrong bits ' + bits + ' powerOfTwo=' + powerOfTwo);
|
|
180
|
+
return bits;
|
|
181
|
+
};
|
|
182
|
+
const precomputeRoots = (maxPower) => {
|
|
183
|
+
checkBits(maxPower);
|
|
184
|
+
for (let power = maxPower; power >= 0; power--) {
|
|
185
|
+
if (rootsCache[power])
|
|
186
|
+
continue; // Skip if we've already computed roots for this power
|
|
187
|
+
const rootsAtPower = [];
|
|
188
|
+
for (let j = 0, cur = field.ONE; j < 2 ** power; j++, cur = field.mul(cur, omegas[power]))
|
|
189
|
+
rootsAtPower.push(cur);
|
|
190
|
+
rootsCache[power] = rootsAtPower;
|
|
191
|
+
}
|
|
192
|
+
return rootsCache[maxPower];
|
|
193
|
+
};
|
|
194
|
+
const brpCache = new Map();
|
|
195
|
+
const inverseCache = new Map();
|
|
196
|
+
// roots()/brp()/inverse() expose shared cached arrays by reference for speed; callers must treat them as read-only.
|
|
197
|
+
// NOTE: we use bits instead of power, because power = 2**bits,
|
|
198
|
+
// but power is not neccesary isPowerOfTwo(power)!
|
|
199
|
+
return {
|
|
200
|
+
info: { G, powerOfTwo, oddFactor },
|
|
201
|
+
roots: (bits) => {
|
|
202
|
+
const b = checkBits(bits);
|
|
203
|
+
return precomputeRoots(b);
|
|
204
|
+
},
|
|
205
|
+
brp(bits) {
|
|
206
|
+
const b = checkBits(bits);
|
|
207
|
+
if (brpCache.has(b))
|
|
208
|
+
return brpCache.get(b);
|
|
209
|
+
else {
|
|
210
|
+
const res = bitReversalPermutation(this.roots(b));
|
|
211
|
+
brpCache.set(b, res);
|
|
212
|
+
return res;
|
|
213
|
+
}
|
|
214
|
+
},
|
|
215
|
+
inverse(bits) {
|
|
216
|
+
const b = checkBits(bits);
|
|
217
|
+
if (inverseCache.has(b))
|
|
218
|
+
return inverseCache.get(b);
|
|
219
|
+
else {
|
|
220
|
+
const res = field.invertBatch(this.roots(b));
|
|
221
|
+
inverseCache.set(b, res);
|
|
222
|
+
return res;
|
|
223
|
+
}
|
|
224
|
+
},
|
|
225
|
+
omega: (bits) => omegas[checkBits(bits)],
|
|
226
|
+
clear: () => {
|
|
227
|
+
rootsCache.splice(0, rootsCache.length);
|
|
228
|
+
brpCache.clear();
|
|
229
|
+
inverseCache.clear();
|
|
230
|
+
},
|
|
231
|
+
};
|
|
232
|
+
}
|
|
233
|
+
/**
|
|
234
|
+
* Constructs different flavors of FFT. radix2 implementation of low level mutating API. Flavors:
|
|
235
|
+
*
|
|
236
|
+
* - DIT (Decimation-in-Time): Bottom-Up (leaves to root), Cool-Turkey
|
|
237
|
+
* - DIF (Decimation-in-Frequency): Top-Down (root to leaves), Gentleman-Sande
|
|
238
|
+
*
|
|
239
|
+
* DIT takes brp input, returns natural output.
|
|
240
|
+
* DIF takes natural input, returns brp output.
|
|
241
|
+
*
|
|
242
|
+
* The output is actually identical. Time / frequence distinction is not meaningful
|
|
243
|
+
* for Polynomial multiplication in fields.
|
|
244
|
+
* Which means if protocol supports/needs brp output/inputs, then we can skip this step.
|
|
245
|
+
*
|
|
246
|
+
* Cyclic NTT: Rq = Zq[x]/(x^n-1). butterfly_DIT+loop_DIT OR butterfly_DIF+loop_DIT, roots are omega
|
|
247
|
+
* Negacyclic NTT: Rq = Zq[x]/(x^n+1). butterfly_DIT+loop_DIF, at least for mlkem / mldsa
|
|
248
|
+
* @param F - Field operations.
|
|
249
|
+
* @param coreOpts - FFT configuration:
|
|
250
|
+
* - `N`: Transform size. Must be a power of two.
|
|
251
|
+
* - `roots`: Stage roots for the selected transform size.
|
|
252
|
+
* - `dit`: Whether to run the DIT variant instead of DIF.
|
|
253
|
+
* - `invertButterflies` (optional): Whether to invert butterfly placement.
|
|
254
|
+
* - `skipStages` (optional): Number of initial stages to skip.
|
|
255
|
+
* - `brp` (optional): Whether to apply bit-reversal permutation at the boundary.
|
|
256
|
+
* @returns Low-level FFT loop.
|
|
257
|
+
* @throws If the FFT options or cached roots are invalid for the requested size. {@link Error}
|
|
258
|
+
* @example
|
|
259
|
+
* Constructs different flavors of FFT.
|
|
260
|
+
*
|
|
261
|
+
* ```ts
|
|
262
|
+
* import { FFTCore, rootsOfUnity } from './fft';
|
|
263
|
+
* import { Field } from './modular';
|
|
264
|
+
* const Fp = Field(17n);
|
|
265
|
+
* const roots = rootsOfUnity(Fp).roots(2);
|
|
266
|
+
* const loop = FFTCore(Fp, { N: 4, roots, dit: true });
|
|
267
|
+
* const values = loop([1n, 2n, 3n, 4n]);
|
|
268
|
+
* ```
|
|
269
|
+
*/
|
|
270
|
+
const FFTCore = (F, coreOpts) => {
|
|
271
|
+
const { N, roots, dit, invertButterflies = false, skipStages = 0, brp = true } = coreOpts;
|
|
272
|
+
const bits = log2(N);
|
|
273
|
+
if (!isPowerOfTwo(N))
|
|
274
|
+
throw new Error('FFT: Polynomial size should be power of two');
|
|
275
|
+
// Wrong-sized root tables can stay in-bounds for some loop shapes and silently compute nonsense.
|
|
276
|
+
if (roots.length !== N)
|
|
277
|
+
throw new Error(`FFT: wrong roots length: expected ${N}, got ${roots.length}`);
|
|
278
|
+
const isDit = dit !== invertButterflies;
|
|
279
|
+
isDit;
|
|
280
|
+
return (values) => {
|
|
281
|
+
if (values.length !== N)
|
|
282
|
+
throw new Error('FFT: wrong Polynomial length');
|
|
283
|
+
if (dit && brp)
|
|
284
|
+
bitReversalInplace(values);
|
|
285
|
+
for (let i = 0, g = 1; i < bits - skipStages; i++) {
|
|
286
|
+
// For each stage s (sub-FFT length m = 2^s)
|
|
287
|
+
const s = dit ? i + 1 + skipStages : bits - i;
|
|
288
|
+
const m = 1 << s;
|
|
289
|
+
const m2 = m >> 1;
|
|
290
|
+
const stride = N >> s;
|
|
291
|
+
// Loop over each subarray of length m
|
|
292
|
+
for (let k = 0; k < N; k += m) {
|
|
293
|
+
// Loop over each butterfly within the subarray
|
|
294
|
+
for (let j = 0, grp = g++; j < m2; j++) {
|
|
295
|
+
const rootPos = invertButterflies ? (dit ? N - grp : grp) : j * stride;
|
|
296
|
+
const i0 = k + j;
|
|
297
|
+
const i1 = k + j + m2;
|
|
298
|
+
const omega = roots[rootPos];
|
|
299
|
+
const b = values[i1];
|
|
300
|
+
const a = values[i0];
|
|
301
|
+
// Inlining gives us 10% perf in kyber vs functions
|
|
302
|
+
if (isDit) {
|
|
303
|
+
const t = F.mul(b, omega); // Standard DIT butterfly
|
|
304
|
+
values[i0] = F.add(a, t);
|
|
305
|
+
values[i1] = F.sub(a, t);
|
|
306
|
+
}
|
|
307
|
+
else if (invertButterflies) {
|
|
308
|
+
values[i0] = F.add(b, a); // DIT loop + inverted butterflies (Kyber decode)
|
|
309
|
+
values[i1] = F.mul(F.sub(b, a), omega);
|
|
310
|
+
}
|
|
311
|
+
else {
|
|
312
|
+
values[i0] = F.add(a, b); // Standard DIF butterfly
|
|
313
|
+
values[i1] = F.mul(F.sub(a, b), omega);
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
if (!dit && brp)
|
|
319
|
+
bitReversalInplace(values);
|
|
320
|
+
return values;
|
|
321
|
+
};
|
|
322
|
+
};
|
|
323
|
+
exports.FFTCore = FFTCore;
|
|
324
|
+
/**
|
|
325
|
+
* NTT aka FFT over finite field (NOT over complex numbers).
|
|
326
|
+
* Naming mirrors other libraries.
|
|
327
|
+
* @param roots - Roots-of-unity cache.
|
|
328
|
+
* @param opts - Field operations. See {@link FFTOpts}.
|
|
329
|
+
* @returns Forward and inverse FFT helpers.
|
|
330
|
+
* @example
|
|
331
|
+
* NTT aka FFT over finite field (NOT over complex numbers).
|
|
332
|
+
*
|
|
333
|
+
* ```ts
|
|
334
|
+
* import { FFT, rootsOfUnity } from './fft';
|
|
335
|
+
* import { Field } from './modular';
|
|
336
|
+
* const Fp = Field(17n);
|
|
337
|
+
* const fft = FFT(rootsOfUnity(Fp), Fp);
|
|
338
|
+
* const values = fft.direct([1n, 2n, 3n, 4n]);
|
|
339
|
+
* ```
|
|
340
|
+
*/
|
|
341
|
+
function FFT(roots, opts) {
|
|
342
|
+
const getLoop = (N, roots, brpInput = false, brpOutput = false) => {
|
|
343
|
+
if (brpInput && brpOutput) {
|
|
344
|
+
// we cannot optimize this case, but lets support it anyway
|
|
345
|
+
return (values) => (0, exports.FFTCore)(opts, { N, roots, dit: false, brp: false })(bitReversalInplace(values));
|
|
346
|
+
}
|
|
347
|
+
if (brpInput)
|
|
348
|
+
return (0, exports.FFTCore)(opts, { N, roots, dit: true, brp: false });
|
|
349
|
+
if (brpOutput)
|
|
350
|
+
return (0, exports.FFTCore)(opts, { N, roots, dit: false, brp: false });
|
|
351
|
+
return (0, exports.FFTCore)(opts, { N, roots, dit: true, brp: true }); // all natural
|
|
352
|
+
};
|
|
353
|
+
return {
|
|
354
|
+
direct(values, brpInput = false, brpOutput = false) {
|
|
355
|
+
const N = values.length;
|
|
356
|
+
if (!isPowerOfTwo(N))
|
|
357
|
+
throw new Error('FFT: Polynomial size should be power of two');
|
|
358
|
+
const bits = log2(N);
|
|
359
|
+
return getLoop(N, roots.roots(bits), brpInput, brpOutput)(values.slice());
|
|
360
|
+
},
|
|
361
|
+
inverse(values, brpInput = false, brpOutput = false) {
|
|
362
|
+
const N = values.length;
|
|
363
|
+
if (!isPowerOfTwo(N))
|
|
364
|
+
throw new Error('FFT: Polynomial size should be power of two');
|
|
365
|
+
const bits = log2(N);
|
|
366
|
+
const res = getLoop(N, roots.inverse(bits), brpInput, brpOutput)(values.slice());
|
|
367
|
+
const ivm = opts.inv(BigInt(values.length)); // scale
|
|
368
|
+
// we can get brp output if we use dif instead of dit!
|
|
369
|
+
for (let i = 0; i < res.length; i++)
|
|
370
|
+
res[i] = opts.mul(res[i], ivm);
|
|
371
|
+
// Allows to re-use non-inverted roots, but is VERY fragile
|
|
372
|
+
// return [res[0]].concat(res.slice(1).reverse());
|
|
373
|
+
// inverse calculated as pow(-1), which transforms into ω^{-kn} (-> reverses indices)
|
|
374
|
+
return res;
|
|
375
|
+
},
|
|
376
|
+
};
|
|
377
|
+
}
|
|
378
|
+
function poly(field, roots, create, fft, length) {
|
|
379
|
+
const F = field;
|
|
380
|
+
const _create = create ||
|
|
381
|
+
((len, elm) => new Array(len).fill(elm ?? F.ZERO));
|
|
382
|
+
// `poly.mul(a, b)` distinguishes polynomial-vs-scalar at runtime, so keep accepted
|
|
383
|
+
// polynomial containers concrete instead of trying to support arbitrary wrappers.
|
|
384
|
+
const isPoly = (x) => {
|
|
385
|
+
if (Array.isArray(x))
|
|
386
|
+
return true;
|
|
387
|
+
if (!ArrayBuffer.isView(x))
|
|
388
|
+
return false;
|
|
389
|
+
const v = x;
|
|
390
|
+
return (typeof v.length === 'number' &&
|
|
391
|
+
typeof v.slice === 'function' &&
|
|
392
|
+
typeof v[Symbol.iterator] === 'function');
|
|
393
|
+
};
|
|
394
|
+
const checkLength = (...lst) => {
|
|
395
|
+
if (!lst.length)
|
|
396
|
+
return 0;
|
|
397
|
+
for (const i of lst)
|
|
398
|
+
if (!isPoly(i))
|
|
399
|
+
throw new Error('poly: not polynomial: ' + i);
|
|
400
|
+
const L = lst[0].length;
|
|
401
|
+
for (let i = 1; i < lst.length; i++)
|
|
402
|
+
if (lst[i].length !== L)
|
|
403
|
+
throw new Error(`poly: mismatched lengths ${L} vs ${lst[i].length}`);
|
|
404
|
+
if (length !== undefined && L !== length)
|
|
405
|
+
throw new Error(`poly: expected fixed length ${length}, got ${L}`);
|
|
406
|
+
return L;
|
|
407
|
+
};
|
|
408
|
+
function findOmegaIndex(x, n, brp = false) {
|
|
409
|
+
const bits = log2(n);
|
|
410
|
+
const omega = brp ? roots.brp(bits) : roots.roots(bits);
|
|
411
|
+
for (let i = 0; i < n; i++)
|
|
412
|
+
if (F.eql(x, omega[i]))
|
|
413
|
+
return i;
|
|
414
|
+
return -1;
|
|
415
|
+
}
|
|
416
|
+
// TODO: mutating versions for mlkem/mldsa
|
|
417
|
+
return {
|
|
418
|
+
roots,
|
|
419
|
+
create: _create,
|
|
420
|
+
length,
|
|
421
|
+
extend: (a, len) => {
|
|
422
|
+
checkLength(a);
|
|
423
|
+
const out = _create(len, F.ZERO);
|
|
424
|
+
// Plain arrays grow when writing past `out.length`, so cap the copy explicitly to keep
|
|
425
|
+
// `extend()` consistent with typed arrays and with its documented truncate behavior.
|
|
426
|
+
for (let i = 0; i < Math.min(a.length, len); i++)
|
|
427
|
+
out[i] = a[i];
|
|
428
|
+
return out;
|
|
429
|
+
},
|
|
430
|
+
degree: (a) => {
|
|
431
|
+
checkLength(a);
|
|
432
|
+
for (let i = a.length - 1; i >= 0; i--)
|
|
433
|
+
if (!F.is0(a[i]))
|
|
434
|
+
return i;
|
|
435
|
+
return -1;
|
|
436
|
+
},
|
|
437
|
+
add: (a, b) => {
|
|
438
|
+
const len = checkLength(a, b);
|
|
439
|
+
const out = _create(len);
|
|
440
|
+
for (let i = 0; i < len; i++)
|
|
441
|
+
out[i] = F.add(a[i], b[i]);
|
|
442
|
+
return out;
|
|
443
|
+
},
|
|
444
|
+
sub: (a, b) => {
|
|
445
|
+
const len = checkLength(a, b);
|
|
446
|
+
const out = _create(len);
|
|
447
|
+
for (let i = 0; i < len; i++)
|
|
448
|
+
out[i] = F.sub(a[i], b[i]);
|
|
449
|
+
return out;
|
|
450
|
+
},
|
|
451
|
+
dot: (a, b) => {
|
|
452
|
+
const len = checkLength(a, b);
|
|
453
|
+
const out = _create(len);
|
|
454
|
+
for (let i = 0; i < len; i++)
|
|
455
|
+
out[i] = F.mul(a[i], b[i]);
|
|
456
|
+
return out;
|
|
457
|
+
},
|
|
458
|
+
mul: (a, b) => {
|
|
459
|
+
if (isPoly(b)) {
|
|
460
|
+
const len = checkLength(a, b);
|
|
461
|
+
if (fft) {
|
|
462
|
+
const A = fft.direct(a, false, true);
|
|
463
|
+
const B = fft.direct(b, false, true);
|
|
464
|
+
for (let i = 0; i < A.length; i++)
|
|
465
|
+
A[i] = F.mul(A[i], B[i]);
|
|
466
|
+
return fft.inverse(A, true, false);
|
|
467
|
+
}
|
|
468
|
+
else {
|
|
469
|
+
// NOTE: this is quadratic and mostly for compat tests with FFT
|
|
470
|
+
const res = _create(len);
|
|
471
|
+
for (let i = 0; i < len; i++) {
|
|
472
|
+
for (let j = 0; j < len; j++) {
|
|
473
|
+
const k = (i + j) % len; // wrap mod length
|
|
474
|
+
res[k] = F.add(res[k], F.mul(a[i], b[j]));
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
return res;
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
else {
|
|
481
|
+
const out = _create(checkLength(a));
|
|
482
|
+
for (let i = 0; i < out.length; i++)
|
|
483
|
+
out[i] = F.mul(a[i], b);
|
|
484
|
+
return out;
|
|
485
|
+
}
|
|
486
|
+
},
|
|
487
|
+
convolve(a, b) {
|
|
488
|
+
const len = nextPowerOfTwo(a.length + b.length - 1);
|
|
489
|
+
return this.mul(this.extend(a, len), this.extend(b, len));
|
|
490
|
+
},
|
|
491
|
+
shift(p, factor) {
|
|
492
|
+
const out = _create(checkLength(p));
|
|
493
|
+
out[0] = p[0];
|
|
494
|
+
for (let i = 1, power = F.ONE; i < p.length; i++) {
|
|
495
|
+
power = F.mul(power, factor);
|
|
496
|
+
out[i] = F.mul(p[i], power);
|
|
497
|
+
}
|
|
498
|
+
return out;
|
|
499
|
+
},
|
|
500
|
+
clone: (a) => {
|
|
501
|
+
checkLength(a);
|
|
502
|
+
const out = _create(a.length);
|
|
503
|
+
for (let i = 0; i < a.length; i++)
|
|
504
|
+
out[i] = a[i];
|
|
505
|
+
return out;
|
|
506
|
+
},
|
|
507
|
+
eval: (a, basis) => {
|
|
508
|
+
checkLength(a, basis);
|
|
509
|
+
let acc = F.ZERO;
|
|
510
|
+
for (let i = 0; i < a.length; i++)
|
|
511
|
+
acc = F.add(acc, F.mul(a[i], basis[i]));
|
|
512
|
+
return acc;
|
|
513
|
+
},
|
|
514
|
+
monomial: {
|
|
515
|
+
basis: (x, n) => {
|
|
516
|
+
const out = _create(n);
|
|
517
|
+
let pow = F.ONE;
|
|
518
|
+
for (let i = 0; i < n; i++) {
|
|
519
|
+
out[i] = pow;
|
|
520
|
+
pow = F.mul(pow, x);
|
|
521
|
+
}
|
|
522
|
+
return out;
|
|
523
|
+
},
|
|
524
|
+
eval: (a, x) => {
|
|
525
|
+
checkLength(a);
|
|
526
|
+
// Same as eval(a, monomialBasis(x, a.length)), but it is faster this way
|
|
527
|
+
let acc = F.ZERO;
|
|
528
|
+
for (let i = a.length - 1; i >= 0; i--)
|
|
529
|
+
acc = F.add(F.mul(acc, x), a[i]);
|
|
530
|
+
return acc;
|
|
531
|
+
},
|
|
532
|
+
},
|
|
533
|
+
lagrange: {
|
|
534
|
+
basis: (x, n, brp = false, weights) => {
|
|
535
|
+
const bits = log2(n);
|
|
536
|
+
const cache = weights || (brp ? roots.brp(bits) : roots.roots(bits)); // [ω⁰, ω¹, ..., ωⁿ⁻¹]
|
|
537
|
+
const out = _create(n);
|
|
538
|
+
// Fast Kronecker-δ shortcut
|
|
539
|
+
const idx = findOmegaIndex(x, n, brp);
|
|
540
|
+
if (idx !== -1) {
|
|
541
|
+
out[idx] = F.ONE;
|
|
542
|
+
return out;
|
|
543
|
+
}
|
|
544
|
+
const tm = F.pow(x, BigInt(n));
|
|
545
|
+
const c = F.mul(F.sub(tm, F.ONE), F.inv(BigInt(n))); // c = (xⁿ - 1)/n
|
|
546
|
+
const denom = _create(n);
|
|
547
|
+
for (let i = 0; i < n; i++)
|
|
548
|
+
denom[i] = F.sub(x, cache[i]);
|
|
549
|
+
const inv = F.invertBatch(denom);
|
|
550
|
+
for (let i = 0; i < n; i++)
|
|
551
|
+
out[i] = F.mul(c, F.mul(cache[i], inv[i]));
|
|
552
|
+
return out;
|
|
553
|
+
},
|
|
554
|
+
eval(a, x, brp = false) {
|
|
555
|
+
checkLength(a);
|
|
556
|
+
const idx = findOmegaIndex(x, a.length, brp);
|
|
557
|
+
if (idx !== -1)
|
|
558
|
+
return a[idx]; // fast path
|
|
559
|
+
const L = this.basis(x, a.length, brp); // Lᵢ(x)
|
|
560
|
+
let acc = F.ZERO;
|
|
561
|
+
for (let i = 0; i < a.length; i++)
|
|
562
|
+
if (!F.is0(a[i]))
|
|
563
|
+
acc = F.add(acc, F.mul(a[i], L[i]));
|
|
564
|
+
return acc;
|
|
565
|
+
},
|
|
566
|
+
},
|
|
567
|
+
vanishing(roots) {
|
|
568
|
+
checkLength(roots);
|
|
569
|
+
const out = _create(roots.length + 1, F.ZERO);
|
|
570
|
+
out[0] = F.ONE;
|
|
571
|
+
for (const r of roots) {
|
|
572
|
+
const neg = F.neg(r);
|
|
573
|
+
for (let j = out.length - 1; j > 0; j--)
|
|
574
|
+
out[j] = F.add(F.mul(out[j], neg), out[j - 1]);
|
|
575
|
+
out[0] = F.mul(out[0], neg);
|
|
576
|
+
}
|
|
577
|
+
return out;
|
|
578
|
+
},
|
|
579
|
+
};
|
|
580
|
+
}
|