@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,610 @@
1
+ /**
2
+ * Methods for elliptic curve multiplication by scalars.
3
+ * Contains wNAF, pippenger.
4
+ * @module
5
+ */
6
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
7
+ import { bitLen, bitMask, validateObject } from '../utils';
8
+ import { Field, FpInvertBatch, validateField } from './modular';
9
+ const _0n = /* @__PURE__ */ BigInt(0);
10
+ const _1n = /* @__PURE__ */ BigInt(1);
11
+ /**
12
+ * Validates the static surface of a point constructor.
13
+ * This is only a cheap sanity check for the constructor hooks and fields consumed by generic
14
+ * factories; it does not certify `BASE`/`ZERO` semantics or prove the curve implementation itself.
15
+ * @param Point - Runtime point constructor.
16
+ * @throws On missing constructor hooks or malformed field metadata. {@link TypeError}
17
+ * @example
18
+ * Check that one point constructor exposes the static hooks generic helpers need.
19
+ *
20
+ * ```ts
21
+ * import { ed25519 } from '../ed25519';
22
+ * import { validatePointCons } from './curve';
23
+ * validatePointCons(ed25519.Point);
24
+ * ```
25
+ */
26
+ export function validatePointCons(Point) {
27
+ const pc = Point;
28
+ if (typeof pc !== 'function')
29
+ throw new TypeError('Point must be a constructor');
30
+ // validateObject only accepts plain objects, so copy the constructor statics into one bag first.
31
+ validateObject({
32
+ Fp: pc.Fp,
33
+ Fn: pc.Fn,
34
+ fromAffine: pc.fromAffine,
35
+ fromBytes: pc.fromBytes,
36
+ fromHex: pc.fromHex,
37
+ }, {
38
+ Fp: 'object',
39
+ Fn: 'object',
40
+ fromAffine: 'function',
41
+ fromBytes: 'function',
42
+ fromHex: 'function',
43
+ });
44
+ validateField(pc.Fp);
45
+ validateField(pc.Fn);
46
+ }
47
+ /**
48
+ * Computes both candidates first, but the final selection still branches on `condition`, so this
49
+ * is not a strict constant-time CMOV primitive.
50
+ * @param condition - Whether to negate the point.
51
+ * @param item - Point-like value.
52
+ * @returns Original or negated value.
53
+ * @example
54
+ * Keep the point or return its negation based on one boolean branch.
55
+ *
56
+ * ```ts
57
+ * import { negateCt } from './curve';
58
+ * import { p256 } from '../nist';
59
+ * const maybeNegated = negateCt(true, p256.Point.BASE);
60
+ * ```
61
+ */
62
+ export function negateCt(condition, item) {
63
+ const neg = item.negate();
64
+ return condition ? neg : item;
65
+ }
66
+ /**
67
+ * Takes a bunch of Projective Points but executes only one
68
+ * inversion on all of them. Inversion is very slow operation,
69
+ * so this improves performance massively.
70
+ * Optimization: converts a list of projective points to a list of identical points with Z=1.
71
+ * Input points are left unchanged; the normalized points are returned as fresh instances.
72
+ * @param c - Point constructor.
73
+ * @param points - Projective points.
74
+ * @returns Fresh projective points reconstructed from normalized affine coordinates.
75
+ * @example
76
+ * Batch-normalize projective points with a single shared inversion.
77
+ *
78
+ * ```ts
79
+ * import { normalizeZ } from './curve';
80
+ * import { p256 } from '../nist';
81
+ * const points = normalizeZ(p256.Point, [p256.Point.BASE, p256.Point.BASE.double()]);
82
+ * ```
83
+ */
84
+ export function normalizeZ(c, points) {
85
+ const invertedZs = FpInvertBatch(c.Fp, points.map((p) => p.Z));
86
+ return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));
87
+ }
88
+ function validateW(W, bits) {
89
+ if (!Number.isSafeInteger(W) || W <= 0 || W > bits)
90
+ throw new Error('invalid window size, expected [1..' + bits + '], got W=' + W);
91
+ }
92
+ function calcWOpts(W, scalarBits) {
93
+ validateW(W, scalarBits);
94
+ const windows = Math.ceil(scalarBits / W) + 1; // W=8 33. Not 32, because we skip zero
95
+ const windowSize = 2 ** (W - 1); // W=8 128. Not 256, because we skip zero
96
+ const maxNumber = 2 ** W; // W=8 256
97
+ const mask = bitMask(W); // W=8 255 == mask 0b11111111
98
+ const shiftBy = BigInt(W); // W=8 8
99
+ return { windows, windowSize, mask, maxNumber, shiftBy };
100
+ }
101
+ function calcOffsets(n, window, wOpts) {
102
+ const { windowSize, mask, maxNumber, shiftBy } = wOpts;
103
+ let wbits = Number(n & mask); // extract W bits.
104
+ let nextN = n >> shiftBy; // shift number by W bits.
105
+ // What actually happens here:
106
+ // const highestBit = Number(mask ^ (mask >> 1n));
107
+ // let wbits2 = wbits - 1; // skip zero
108
+ // if (wbits2 & highestBit) { wbits2 ^= Number(mask); // (~);
109
+ // split if bits > max: +224 => 256-32
110
+ if (wbits > windowSize) {
111
+ // we skip zero, which means instead of `>= size-1`, we do `> size`
112
+ wbits -= maxNumber; // -32, can be maxNumber - wbits, but then we need to set isNeg here.
113
+ nextN += _1n; // +256 (carry)
114
+ }
115
+ const offsetStart = window * windowSize;
116
+ const offset = offsetStart + Math.abs(wbits) - 1; // -1 because we skip zero; ignore when isZero
117
+ const isZero = wbits === 0; // is current window slice a 0?
118
+ const isNeg = wbits < 0; // is current window slice negative?
119
+ const isNegF = window % 2 !== 0; // fake branch noise only
120
+ const offsetF = offsetStart; // fake branch noise only
121
+ return { nextN, offset, isZero, isNeg, isNegF, offsetF };
122
+ }
123
+ function validateMSMPoints(points, c) {
124
+ if (!Array.isArray(points))
125
+ throw new Error('array expected');
126
+ points.forEach((p, i) => {
127
+ if (!(p instanceof c))
128
+ throw new Error('invalid point at index ' + i);
129
+ });
130
+ }
131
+ function validateMSMScalars(scalars, field) {
132
+ if (!Array.isArray(scalars))
133
+ throw new Error('array of scalars expected');
134
+ scalars.forEach((s, i) => {
135
+ if (!field.isValid(s))
136
+ throw new Error('invalid scalar at index ' + i);
137
+ });
138
+ }
139
+ // Since points in different groups cannot be equal (different object constructor),
140
+ // we can have single place to store precomputes.
141
+ // Allows to make points frozen / immutable.
142
+ const pointPrecomputes = new WeakMap();
143
+ const pointWindowSizes = new WeakMap();
144
+ function getW(P) {
145
+ // To disable precomputes:
146
+ // return 1;
147
+ // `1` is also the uncached sentinel: use the ladder / non-precomputed path.
148
+ return pointWindowSizes.get(P) || 1;
149
+ }
150
+ function assert0(n) {
151
+ // Internal invariant: a non-zero remainder here means the wNAF window decomposition or loop
152
+ // count is inconsistent, not that the original caller provided a bad scalar.
153
+ if (n !== _0n)
154
+ throw new Error('invalid wNAF');
155
+ }
156
+ /**
157
+ * Elliptic curve multiplication of Point by scalar. Fragile.
158
+ * Table generation takes **30MB of ram and 10ms on high-end CPU**,
159
+ * but may take much longer on slow devices. Actual generation will happen on
160
+ * first call of `multiply()`. By default, `BASE` point is precomputed.
161
+ *
162
+ * Scalars should always be less than curve order: this should be checked inside of a curve itself.
163
+ * Creates precomputation tables for fast multiplication:
164
+ * - private scalar is split by fixed size windows of W bits
165
+ * - every window point is collected from window's table & added to accumulator
166
+ * - since windows are different, same point inside tables won't be accessed more than once per calc
167
+ * - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar)
168
+ * - +1 window is neccessary for wNAF
169
+ * - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication
170
+ *
171
+ * TODO: research returning a 2d JS array of windows instead of a single window.
172
+ * This would allow windows to be in different memory locations.
173
+ * @param Point - Point constructor.
174
+ * @param bits - Scalar bit length.
175
+ * @example
176
+ * Elliptic curve multiplication of Point by scalar.
177
+ *
178
+ * ```ts
179
+ * import { wNAF } from './curve';
180
+ * import { p256 } from '../nist';
181
+ * const ladder = new wNAF(p256.Point, p256.Point.Fn.BITS);
182
+ * ```
183
+ */
184
+ export class wNAF {
185
+ BASE;
186
+ ZERO;
187
+ Fn;
188
+ bits;
189
+ // Parametrized with a given Point class (not individual point)
190
+ constructor(Point, bits) {
191
+ this.BASE = Point.BASE;
192
+ this.ZERO = Point.ZERO;
193
+ this.Fn = Point.Fn;
194
+ this.bits = bits;
195
+ }
196
+ // non-const time multiplication ladder
197
+ _unsafeLadder(elm, n, p = this.ZERO) {
198
+ let d = elm;
199
+ while (n > _0n) {
200
+ if (n & _1n)
201
+ p = p.add(d);
202
+ d = d.double();
203
+ n >>= _1n;
204
+ }
205
+ return p;
206
+ }
207
+ /**
208
+ * Creates a wNAF precomputation window. Used for caching.
209
+ * Default window size is set by `utils.precompute()` and is equal to 8.
210
+ * Number of precomputed points depends on the curve size:
211
+ * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:
212
+ * - 𝑊 is the window size
213
+ * - 𝑛 is the bitlength of the curve order.
214
+ * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
215
+ * @param point - Point instance
216
+ * @param W - window size
217
+ * @returns precomputed point tables flattened to a single array
218
+ */
219
+ precomputeWindow(point, W) {
220
+ const { windows, windowSize } = calcWOpts(W, this.bits);
221
+ const points = [];
222
+ let p = point;
223
+ let base = p;
224
+ for (let window = 0; window < windows; window++) {
225
+ base = p;
226
+ points.push(base);
227
+ // i=1, bc we skip 0
228
+ for (let i = 1; i < windowSize; i++) {
229
+ base = base.add(p);
230
+ points.push(base);
231
+ }
232
+ p = base.double();
233
+ }
234
+ return points;
235
+ }
236
+ /**
237
+ * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.
238
+ * More compact implementation:
239
+ * https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541
240
+ * @returns real and fake (for const-time) points
241
+ */
242
+ wNAF(W, precomputes, n) {
243
+ // Scalar should be smaller than field order
244
+ if (!this.Fn.isValid(n))
245
+ throw new Error('invalid scalar');
246
+ // Accumulators
247
+ let p = this.ZERO;
248
+ let f = this.BASE;
249
+ // This code was first written with assumption that 'f' and 'p' will never be infinity point:
250
+ // since each addition is multiplied by 2 ** W, it cannot cancel each other. However,
251
+ // there is negate now: it is possible that negated element from low value
252
+ // would be the same as high element, which will create carry into next window.
253
+ // It's not obvious how this can fail, but still worth investigating later.
254
+ const wo = calcWOpts(W, this.bits);
255
+ for (let window = 0; window < wo.windows; window++) {
256
+ // (n === _0n) is handled and not early-exited. isEven and offsetF are used for noise
257
+ const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);
258
+ n = nextN;
259
+ if (isZero) {
260
+ // bits are 0: add garbage to fake point
261
+ // Important part for const-time getPublicKey: add random "noise" point to f.
262
+ f = f.add(negateCt(isNegF, precomputes[offsetF]));
263
+ }
264
+ else {
265
+ // bits are 1: add to result point
266
+ p = p.add(negateCt(isNeg, precomputes[offset]));
267
+ }
268
+ }
269
+ assert0(n);
270
+ // Return both real and fake points so JIT keeps the noise path alive.
271
+ // Known caveat: negate/carry interactions can still drive `f` to infinity even when `p` is not,
272
+ // which weakens the noise path and leaves this only "less const-time" by about one bigint mul.
273
+ return { p, f };
274
+ }
275
+ /**
276
+ * Implements unsafe EC multiplication using precomputed tables
277
+ * and w-ary non-adjacent form.
278
+ * @param acc - accumulator point to add result of multiplication
279
+ * @returns point
280
+ */
281
+ wNAFUnsafe(W, precomputes, n, acc = this.ZERO) {
282
+ const wo = calcWOpts(W, this.bits);
283
+ for (let window = 0; window < wo.windows; window++) {
284
+ if (n === _0n)
285
+ break; // Early-exit, skip 0 value
286
+ const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);
287
+ n = nextN;
288
+ if (isZero) {
289
+ // Window bits are 0: skip processing.
290
+ // Move to next window.
291
+ continue;
292
+ }
293
+ else {
294
+ const item = precomputes[offset];
295
+ acc = acc.add(isNeg ? item.negate() : item); // Re-using acc allows to save adds in MSM
296
+ }
297
+ }
298
+ assert0(n);
299
+ return acc;
300
+ }
301
+ getPrecomputes(W, point, transform) {
302
+ // Cache key is only point identity plus the remembered window size; callers must not reuse the
303
+ // same point with incompatible `transform(...)` layouts and expect a separate cache entry.
304
+ let comp = pointPrecomputes.get(point);
305
+ if (!comp) {
306
+ comp = this.precomputeWindow(point, W);
307
+ if (W !== 1) {
308
+ // Doing transform outside of if brings 15% perf hit
309
+ if (typeof transform === 'function')
310
+ comp = transform(comp);
311
+ pointPrecomputes.set(point, comp);
312
+ }
313
+ }
314
+ return comp;
315
+ }
316
+ cached(point, scalar, transform) {
317
+ const W = getW(point);
318
+ return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);
319
+ }
320
+ unsafe(point, scalar, transform, prev) {
321
+ const W = getW(point);
322
+ if (W === 1)
323
+ return this._unsafeLadder(point, scalar, prev); // For W=1 ladder is ~x2 faster
324
+ return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);
325
+ }
326
+ // We calculate precomputes for elliptic curve point multiplication
327
+ // using windowed method. This specifies window size and
328
+ // stores precomputed values. Usually only base point would be precomputed.
329
+ createCache(P, W) {
330
+ validateW(W, this.bits);
331
+ pointWindowSizes.set(P, W);
332
+ pointPrecomputes.delete(P);
333
+ }
334
+ hasCache(elm) {
335
+ return getW(elm) !== 1;
336
+ }
337
+ }
338
+ /**
339
+ * Endomorphism-specific multiplication for Koblitz curves.
340
+ * Cost: 128 dbl, 0-256 adds.
341
+ * @param Point - Point constructor.
342
+ * @param point - Input point.
343
+ * @param k1 - First non-negative absolute scalar chunk.
344
+ * @param k2 - Second non-negative absolute scalar chunk.
345
+ * @returns Partial multiplication results.
346
+ * @example
347
+ * Endomorphism-specific multiplication for Koblitz curves.
348
+ *
349
+ * ```ts
350
+ * import { mulEndoUnsafe } from './curve';
351
+ * import { secp256k1 } from '../secp256k1';
352
+ * const parts = mulEndoUnsafe(secp256k1.Point, secp256k1.Point.BASE, 3n, 5n);
353
+ * ```
354
+ */
355
+ export function mulEndoUnsafe(Point, point, k1, k2) {
356
+ let acc = point;
357
+ let p1 = Point.ZERO;
358
+ let p2 = Point.ZERO;
359
+ while (k1 > _0n || k2 > _0n) {
360
+ if (k1 & _1n)
361
+ p1 = p1.add(acc);
362
+ if (k2 & _1n)
363
+ p2 = p2.add(acc);
364
+ acc = acc.double();
365
+ k1 >>= _1n;
366
+ k2 >>= _1n;
367
+ }
368
+ return { p1, p2 };
369
+ }
370
+ /**
371
+ * Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).
372
+ * 30x faster vs naive addition on L=4096, 10x faster than precomputes.
373
+ * For N=254bit, L=1, it does: 1024 ADD + 254 DBL. For L=5: 1536 ADD + 254 DBL.
374
+ * Algorithmically constant-time (for same L), even when 1 point + scalar, or when scalar = 0.
375
+ * @param c - Curve Point constructor
376
+ * @param points - array of L curve points
377
+ * @param scalars - array of L scalars (aka secret keys / bigints)
378
+ * @returns MSM result point. Empty input is accepted and returns the identity.
379
+ * @throws If the point set, scalar set, or MSM sizing is invalid. {@link Error}
380
+ * @example
381
+ * Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).
382
+ *
383
+ * ```ts
384
+ * import { pippenger } from './curve';
385
+ * import { p256 } from '../nist';
386
+ * const point = pippenger(p256.Point, [p256.Point.BASE, p256.Point.BASE.double()], [2n, 3n]);
387
+ * ```
388
+ */
389
+ export function pippenger(c, points, scalars) {
390
+ // If we split scalars by some window (let's say 8 bits), every chunk will only
391
+ // take 256 buckets even if there are 4096 scalars, also re-uses double.
392
+ // TODO:
393
+ // - https://eprint.iacr.org/2024/750.pdf
394
+ // - https://tches.iacr.org/index.php/TCHES/article/view/10287
395
+ // 0 is accepted in scalars
396
+ const fieldN = c.Fn;
397
+ validateMSMPoints(points, c);
398
+ validateMSMScalars(scalars, fieldN);
399
+ const plength = points.length;
400
+ const slength = scalars.length;
401
+ if (plength !== slength)
402
+ throw new Error('arrays of points and scalars must have equal length');
403
+ // if (plength === 0) throw new Error('array must be of length >= 2');
404
+ const zero = c.ZERO;
405
+ const wbits = bitLen(BigInt(plength));
406
+ let windowSize = 1; // bits
407
+ if (wbits > 12)
408
+ windowSize = wbits - 3;
409
+ else if (wbits > 4)
410
+ windowSize = wbits - 2;
411
+ else if (wbits > 0)
412
+ windowSize = 2;
413
+ const MASK = bitMask(windowSize);
414
+ const buckets = new Array(Number(MASK) + 1).fill(zero); // +1 for zero array
415
+ const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize;
416
+ let sum = zero;
417
+ for (let i = lastBits; i >= 0; i -= windowSize) {
418
+ buckets.fill(zero);
419
+ for (let j = 0; j < slength; j++) {
420
+ const scalar = scalars[j];
421
+ const wbits = Number((scalar >> BigInt(i)) & MASK);
422
+ buckets[wbits] = buckets[wbits].add(points[j]);
423
+ }
424
+ let resI = zero; // not using this will do small speed-up, but will lose ct
425
+ // Skip first bucket, because it is zero
426
+ for (let j = buckets.length - 1, sumI = zero; j > 0; j--) {
427
+ sumI = sumI.add(buckets[j]);
428
+ resI = resI.add(sumI);
429
+ }
430
+ sum = sum.add(resI);
431
+ if (i !== 0)
432
+ for (let j = 0; j < windowSize; j++)
433
+ sum = sum.double();
434
+ }
435
+ return sum;
436
+ }
437
+ /**
438
+ * Precomputed multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).
439
+ * @param c - Curve Point constructor
440
+ * @param points - array of L curve points
441
+ * @param windowSize - Precompute window size.
442
+ * @returns Function which multiplies points with scalars. The closure accepts
443
+ * `scalars.length <= points.length`, and omitted trailing scalars are treated as zero.
444
+ * @throws If the point set or precompute window is invalid. {@link Error}
445
+ * @example
446
+ * Precomputed multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).
447
+ *
448
+ * ```ts
449
+ * import { precomputeMSMUnsafe } from './curve';
450
+ * import { p256 } from '../nist';
451
+ * const msm = precomputeMSMUnsafe(p256.Point, [p256.Point.BASE], 4);
452
+ * const point = msm([3n]);
453
+ * ```
454
+ */
455
+ export function precomputeMSMUnsafe(c, points, windowSize) {
456
+ /**
457
+ * Performance Analysis of Window-based Precomputation
458
+ *
459
+ * Base Case (256-bit scalar, 8-bit window):
460
+ * - Standard precomputation requires:
461
+ * - 31 additions per scalar × 256 scalars = 7,936 ops
462
+ * - Plus 255 summary additions = 8,191 total ops
463
+ * Note: Summary additions can be optimized via accumulator
464
+ *
465
+ * Chunked Precomputation Analysis:
466
+ * - Using 32 chunks requires:
467
+ * - 255 additions per chunk
468
+ * - 256 doublings
469
+ * - Total: (255 × 32) + 256 = 8,416 ops
470
+ *
471
+ * Memory Usage Comparison:
472
+ * Window Size | Standard Points | Chunked Points
473
+ * ------------|-----------------|---------------
474
+ * 4-bit | 520 | 15
475
+ * 8-bit | 4,224 | 255
476
+ * 10-bit | 13,824 | 1,023
477
+ * 16-bit | 557,056 | 65,535
478
+ *
479
+ * Key Advantages:
480
+ * 1. Enables larger window sizes due to reduced memory overhead
481
+ * 2. More efficient for smaller scalar counts:
482
+ * - 16 chunks: (16 × 255) + 256 = 4,336 ops
483
+ * - ~2x faster than standard 8,191 ops
484
+ *
485
+ * Limitations:
486
+ * - Not suitable for plain precomputes (requires 256 constant doublings)
487
+ * - Performance degrades with larger scalar counts:
488
+ * - Optimal for ~256 scalars
489
+ * - Less efficient for 4096+ scalars (Pippenger preferred)
490
+ */
491
+ const fieldN = c.Fn;
492
+ validateW(windowSize, fieldN.BITS);
493
+ validateMSMPoints(points, c);
494
+ const zero = c.ZERO;
495
+ const tableSize = 2 ** windowSize - 1; // table size (without zero)
496
+ const chunks = Math.ceil(fieldN.BITS / windowSize); // chunks of item
497
+ const MASK = bitMask(windowSize);
498
+ const tables = points.map((p) => {
499
+ const res = [];
500
+ for (let i = 0, acc = p; i < tableSize; i++) {
501
+ res.push(acc);
502
+ acc = acc.add(p);
503
+ }
504
+ return res;
505
+ });
506
+ return (scalars) => {
507
+ validateMSMScalars(scalars, fieldN);
508
+ if (scalars.length > points.length)
509
+ throw new Error('array of scalars must be smaller than array of points');
510
+ let res = zero;
511
+ for (let i = 0; i < chunks; i++) {
512
+ // No need to double if accumulator is still zero.
513
+ if (res !== zero)
514
+ for (let j = 0; j < windowSize; j++)
515
+ res = res.double();
516
+ const shiftBy = BigInt(chunks * windowSize - (i + 1) * windowSize);
517
+ for (let j = 0; j < scalars.length; j++) {
518
+ const n = scalars[j];
519
+ const curr = Number((n >> shiftBy) & MASK);
520
+ if (!curr)
521
+ continue; // skip zero scalars chunks
522
+ res = res.add(tables[j][curr - 1]);
523
+ }
524
+ }
525
+ return res;
526
+ };
527
+ }
528
+ function createField(order, field, isLE) {
529
+ if (field) {
530
+ // Reuse supplied field overrides as-is; `isLE` only affects freshly constructed fallback
531
+ // fields, and validateField() below only checks the arithmetic subset, not full byte/cmov
532
+ // behavior.
533
+ if (field.ORDER !== order)
534
+ throw new Error('Field.ORDER must match order: Fp == p, Fn == n');
535
+ validateField(field);
536
+ return field;
537
+ }
538
+ else {
539
+ return Field(order, { isLE });
540
+ }
541
+ }
542
+ /**
543
+ * Validates basic CURVE shape and field membership, then creates fields.
544
+ * This does not prove that the generator is on-curve, that subgroup/order data are consistent, or
545
+ * that the curve equation itself is otherwise sane.
546
+ * @param type - Curve family.
547
+ * @param CURVE - Curve parameters.
548
+ * @param curveOpts - Optional field overrides:
549
+ * - `Fp` (optional): Optional base-field override.
550
+ * - `Fn` (optional): Optional scalar-field override.
551
+ * @param FpFnLE - Whether field encoding is little-endian.
552
+ * @returns Frozen curve parameters and fields.
553
+ * @throws If the curve parameters or field overrides are invalid. {@link Error}
554
+ * @example
555
+ * Build curve fields from raw constants before constructing a curve instance.
556
+ *
557
+ * ```ts
558
+ * const curve = createCurveFields('weierstrass', {
559
+ * p: 17n,
560
+ * n: 19n,
561
+ * h: 1n,
562
+ * a: 2n,
563
+ * b: 2n,
564
+ * Gx: 5n,
565
+ * Gy: 1n,
566
+ * });
567
+ * ```
568
+ */
569
+ export function createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) {
570
+ if (FpFnLE === undefined)
571
+ FpFnLE = type === 'edwards';
572
+ if (!CURVE || typeof CURVE !== 'object')
573
+ throw new Error(`expected valid ${type} CURVE object`);
574
+ for (const p of ['p', 'n', 'h']) {
575
+ const val = CURVE[p];
576
+ if (!(typeof val === 'bigint' && val > _0n))
577
+ throw new Error(`CURVE.${p} must be positive bigint`);
578
+ }
579
+ const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE);
580
+ const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);
581
+ const _b = type === 'weierstrass' ? 'b' : 'd';
582
+ const params = ['Gx', 'Gy', 'a', _b];
583
+ for (const p of params) {
584
+ // @ts-ignore
585
+ if (!Fp.isValid(CURVE[p]))
586
+ throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);
587
+ }
588
+ CURVE = Object.freeze(Object.assign({}, CURVE));
589
+ return { CURVE, Fp, Fn };
590
+ }
591
+ /**
592
+ * @param randomSecretKey - Secret-key generator.
593
+ * @param getPublicKey - Public-key derivation helper.
594
+ * @returns Keypair generator.
595
+ * @example
596
+ * Build a `keygen()` helper from existing secret-key and public-key primitives.
597
+ *
598
+ * ```ts
599
+ * import { createKeygen } from './curve';
600
+ * import { p256 } from '../nist';
601
+ * const keygen = createKeygen(p256.utils.randomSecretKey, p256.getPublicKey);
602
+ * const pair = keygen();
603
+ * ```
604
+ */
605
+ export function createKeygen(randomSecretKey, getPublicKey) {
606
+ return function keygen(seed) {
607
+ const secretKey = randomSecretKey(seed);
608
+ return { secretKey, publicKey: getPublicKey(secretKey) };
609
+ };
610
+ }