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