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