@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,471 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.PoseidonSponge = void 0;
4
+ exports.grainGenConstants = grainGenConstants;
5
+ exports.validateOpts = validateOpts;
6
+ exports.splitConstants = splitConstants;
7
+ exports.poseidon = poseidon;
8
+ exports.poseidonSponge = poseidonSponge;
9
+ /**
10
+ * Implements [Poseidon](https://www.poseidon-hash.info) ZK-friendly hash.
11
+ *
12
+ * There are many poseidon variants with different constants.
13
+ * We don't provide them: you should construct them manually.
14
+ * Check out [micro-starknet](https://github.com/paulmillr/micro-starknet) package for a proper example.
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
+ // Grain LFSR (Linear-Feedback Shift Register): https://eprint.iacr.org/2009/109.pdf
21
+ function grainLFSR(state) {
22
+ // Advances the caller-provided 80-entry state array in place; only the length
23
+ // is checked here, so entries are assumed to already be bits.
24
+ let pos = 0;
25
+ if (state.length !== 80)
26
+ throw new Error('grainLFRS: wrong state length, should be 80 bits');
27
+ const getBit = () => {
28
+ const r = (offset) => state[(pos + offset) % 80];
29
+ const bit = r(62) ^ r(51) ^ r(38) ^ r(23) ^ r(13) ^ r(0);
30
+ state[pos] = bit;
31
+ pos = ++pos % 80;
32
+ return !!bit;
33
+ };
34
+ for (let i = 0; i < 160; i++)
35
+ getBit();
36
+ return () => {
37
+ // https://en.wikipedia.org/wiki/Shrinking_generator
38
+ while (true) {
39
+ const b1 = getBit();
40
+ const b2 = getBit();
41
+ if (!b1)
42
+ continue;
43
+ return b2;
44
+ }
45
+ };
46
+ }
47
+ function assertValidPosOpts(opts) {
48
+ const { Fp, roundsFull } = opts;
49
+ (0, modular_1.validateField)(Fp);
50
+ (0, utils_1.validateObject)(opts, {
51
+ t: 'number',
52
+ roundsFull: 'number',
53
+ roundsPartial: 'number',
54
+ }, {
55
+ isSboxInverse: 'boolean',
56
+ });
57
+ for (const k of ['t', 'roundsFull', 'roundsPartial']) {
58
+ (0, utils_1.asafenumber)(opts[k], k);
59
+ if (opts[k] < 1)
60
+ throw new Error('invalid number ' + k);
61
+ }
62
+ // Poseidon splits full rounds as `R_F / 2`, then partial rounds, then `R_F / 2` again.
63
+ if (roundsFull & 1)
64
+ throw new Error('roundsFull is not even' + roundsFull);
65
+ }
66
+ function poseidonGrain(opts) {
67
+ assertValidPosOpts(opts);
68
+ const { Fp } = opts;
69
+ const state = Array(80).fill(1);
70
+ let pos = 0;
71
+ const writeBits = (value, bitCount) => {
72
+ for (let i = bitCount - 1; i >= 0; i--)
73
+ state[pos++] = Number((0, utils_1.bitGet)(value, i));
74
+ };
75
+ const _0n = BigInt(0);
76
+ const _1n = BigInt(1);
77
+ // The Grain seed layout is fixed-width: `Fp.BITS` and `t` use 12 bits,
78
+ // `roundsFull` and `roundsPartial` use 10, so larger values are truncated here.
79
+ // This is intentional for compatibility with snarkVM / arkworks PoseidonGrainLFSR:
80
+ // they write the same fixed-width seed fields without range checks, then still consume
81
+ // the LFSR using the caller-provided round count for ARK/MDS generation.
82
+ // Normalizing or rejecting here would diverge from those implementations.
83
+ writeBits(_1n, 2); // prime field
84
+ writeBits(opts.isSboxInverse ? _1n : _0n, 4); // b2..b5
85
+ writeBits(BigInt(Fp.BITS), 12); // b6..b17
86
+ writeBits(BigInt(opts.t), 12); // b18..b29
87
+ writeBits(BigInt(opts.roundsFull), 10); // b30..b39
88
+ writeBits(BigInt(opts.roundsPartial), 10); // b40..b49
89
+ const getBit = grainLFSR(state);
90
+ return (count, reject) => {
91
+ const res = [];
92
+ for (let i = 0; i < count; i++) {
93
+ while (true) {
94
+ let num = _0n;
95
+ for (let i = 0; i < Fp.BITS; i++) {
96
+ num <<= _1n;
97
+ if (getBit())
98
+ num |= _1n;
99
+ }
100
+ if (reject && num >= Fp.ORDER)
101
+ continue; // rejection sampling
102
+ res.push(Fp.create(num));
103
+ break;
104
+ }
105
+ }
106
+ return res;
107
+ };
108
+ }
109
+ // NOTE: this is not standard but used often for constant generation for poseidon
110
+ // (grain LFRS-like structure)
111
+ /**
112
+ * @param opts - Poseidon grain options. See {@link PoseidonGrainOpts}.
113
+ * @param skipMDS - Number of MDS samples to skip.
114
+ * @returns Generated constants.
115
+ * @throws If the generated MDS matrix contains a zero denominator. {@link Error}
116
+ * @example
117
+ * Generate Poseidon round constants and an MDS matrix from the Grain LFSR.
118
+ *
119
+ * ```ts
120
+ * import { grainGenConstants } from './poseidon';
121
+ * import { Field } from './modular';
122
+ * const Fp = Field(17n);
123
+ * const constants = grainGenConstants({ Fp, t: 2, roundsFull: 8, roundsPartial: 8 });
124
+ * ```
125
+ */
126
+ function grainGenConstants(opts, skipMDS = 0) {
127
+ const { Fp, t, roundsFull, roundsPartial } = opts;
128
+ // `skipMDS` counts how many candidate matrices to discard before taking one.
129
+ (0, utils_1.asafenumber)(skipMDS, 'skipMDS');
130
+ if (skipMDS < 0)
131
+ throw new Error('invalid number skipMDS');
132
+ const rounds = roundsFull + roundsPartial;
133
+ // `sboxPower` is carried in the opts shape for Poseidon compatibility, but
134
+ // Grain constant generation here only depends on field/size/round counts/inverse flag.
135
+ const sample = poseidonGrain(opts);
136
+ const roundConstants = [];
137
+ for (let r = 0; r < rounds; r++)
138
+ roundConstants.push(sample(t, true));
139
+ if (skipMDS > 0)
140
+ for (let i = 0; i < skipMDS; i++)
141
+ sample(2 * t, false);
142
+ const xs = sample(t, false);
143
+ const ys = sample(t, false);
144
+ // Construct MDS Matrix M[i][j] = 1 / (xs[i] + ys[j])
145
+ const mds = [];
146
+ for (let i = 0; i < t; i++) {
147
+ const row = [];
148
+ for (let j = 0; j < t; j++) {
149
+ const xy = Fp.add(xs[i], ys[j]);
150
+ if (Fp.is0(xy))
151
+ throw new Error(`Error generating MDS matrix: xs[${i}] + ys[${j}] resulted in zero.`);
152
+ row.push(xy);
153
+ }
154
+ mds.push((0, modular_1.FpInvertBatch)(Fp, row));
155
+ }
156
+ return { roundConstants, mds };
157
+ }
158
+ /**
159
+ * @param opts - Poseidon options. See {@link PoseidonOpts}.
160
+ * @returns Normalized poseidon options.
161
+ * @throws If the Poseidon options, constants, or MDS matrix are invalid. {@link Error}
162
+ * @example
163
+ * Validate generated constants before constructing a permutation.
164
+ *
165
+ * ```ts
166
+ * import { grainGenConstants, validateOpts } from './poseidon';
167
+ * import { Field } from './modular';
168
+ * const Fp = Field(17n);
169
+ * const constants = grainGenConstants({ Fp, t: 2, roundsFull: 8, roundsPartial: 8 });
170
+ * const opts = validateOpts({ ...constants, Fp, t: 2, roundsFull: 8, roundsPartial: 8, sboxPower: 3 });
171
+ * ```
172
+ */
173
+ function validateOpts(opts) {
174
+ // This only normalizes shapes and field membership for the provided constants;
175
+ // it does not prove the stronger MDS/security criteria discussed in the specs.
176
+ assertValidPosOpts(opts);
177
+ const { Fp, mds, reversePartialPowIdx: rev, roundConstants: rc } = opts;
178
+ const { roundsFull, roundsPartial, sboxPower, t } = opts;
179
+ // MDS is TxT matrix
180
+ if (!Array.isArray(mds) || mds.length !== t)
181
+ throw new Error('Poseidon: invalid MDS matrix');
182
+ const _mds = mds.map((mdsRow) => {
183
+ if (!Array.isArray(mdsRow) || mdsRow.length !== t)
184
+ throw new Error('invalid MDS matrix row: ' + mdsRow);
185
+ return mdsRow.map((i) => {
186
+ if (typeof i !== 'bigint')
187
+ throw new Error('invalid MDS matrix bigint: ' + i);
188
+ // Hardcoded Poseidon MDS matrices often use signed entries like `-1`;
189
+ // accept bigint representatives here and reduce them into the field.
190
+ return Fp.create(i);
191
+ });
192
+ });
193
+ if (rev !== undefined && typeof rev !== 'boolean')
194
+ throw new Error('invalid param reversePartialPowIdx=' + rev);
195
+ if (roundsFull & 1)
196
+ throw new Error('roundsFull is not even' + roundsFull);
197
+ const rounds = roundsFull + roundsPartial;
198
+ if (!Array.isArray(rc) || rc.length !== rounds)
199
+ throw new Error('Poseidon: invalid round constants');
200
+ const roundConstants = rc.map((rc) => {
201
+ if (!Array.isArray(rc) || rc.length !== t)
202
+ throw new Error('invalid round constants');
203
+ return rc.map((i) => {
204
+ if (typeof i !== 'bigint' || !Fp.isValid(i))
205
+ throw new Error('invalid round constant');
206
+ return Fp.create(i);
207
+ });
208
+ });
209
+ // Freeze nested constants so exported handles cannot retune a live permutation instance.
210
+ const freezeRows = (rows) => Object.freeze(rows.map((row) => Object.freeze(row)));
211
+ if (!sboxPower || ![3, 5, 7, 17].includes(sboxPower))
212
+ throw new Error('invalid sboxPower');
213
+ const _sboxPower = BigInt(sboxPower);
214
+ let sboxFn = (n) => (0, modular_1.FpPow)(Fp, n, _sboxPower);
215
+ // Unwrapped sbox power for common cases (195->142μs)
216
+ if (sboxPower === 3)
217
+ sboxFn = (n) => Fp.mul(Fp.sqrN(n), n);
218
+ else if (sboxPower === 5)
219
+ sboxFn = (n) => Fp.mul(Fp.sqrN(Fp.sqrN(n)), n);
220
+ return Object.freeze({
221
+ ...opts,
222
+ rounds,
223
+ sboxFn,
224
+ roundConstants: freezeRows(roundConstants),
225
+ mds: freezeRows(_mds),
226
+ });
227
+ }
228
+ /**
229
+ * @param rc - Flattened round constants.
230
+ * @param t - Poseidon width.
231
+ * @returns Constants grouped by round.
232
+ * @throws If the width or flattened constant array is invalid. {@link Error}
233
+ * @example
234
+ * Regroup a flat constant list into per-round chunks.
235
+ *
236
+ * ```ts
237
+ * const rounds = splitConstants([1n, 2n, 3n, 4n], 2);
238
+ * ```
239
+ */
240
+ function splitConstants(rc, t) {
241
+ (0, utils_1.asafenumber)(t, 't');
242
+ if (t < 1)
243
+ throw new Error('poseidonSplitConstants: invalid t');
244
+ if (!Array.isArray(rc) || rc.length % t)
245
+ throw new Error('poseidonSplitConstants: invalid rc');
246
+ const res = [];
247
+ let tmp = [];
248
+ for (let i = 0; i < rc.length; i++) {
249
+ const c = rc[i];
250
+ if (typeof c !== 'bigint')
251
+ throw new Error('invalid bigint=' + c);
252
+ tmp.push(c);
253
+ if (tmp.length === t) {
254
+ res.push(tmp);
255
+ tmp = [];
256
+ }
257
+ }
258
+ return res;
259
+ }
260
+ /** Poseidon NTT-friendly hash. */
261
+ /**
262
+ * @param opts - Poseidon options. See {@link PoseidonOpts}.
263
+ * @returns Poseidon permutation.
264
+ * @throws If the Poseidon options or state vector are invalid. {@link Error}
265
+ * @example
266
+ * Build a Poseidon permutation from validated parameters and constants.
267
+ *
268
+ * ```ts
269
+ * import { grainGenConstants, poseidon } from './poseidon';
270
+ * import { Field } from './modular';
271
+ * const Fp = Field(17n);
272
+ * const constants = grainGenConstants({ Fp, t: 2, roundsFull: 8, roundsPartial: 8 });
273
+ * const hash = poseidon({ ...constants, Fp, t: 2, roundsFull: 8, roundsPartial: 8, sboxPower: 3 });
274
+ * const state = hash([1n, 2n]);
275
+ * ```
276
+ */
277
+ function poseidon(opts) {
278
+ const _opts = validateOpts(opts);
279
+ const { Fp, mds, roundConstants, rounds: totalRounds, roundsPartial, sboxFn, t } = _opts;
280
+ const halfRoundsFull = _opts.roundsFull / 2;
281
+ const partialIdx = _opts.reversePartialPowIdx ? t - 1 : 0;
282
+ const poseidonRound = (values, isFull, idx) => {
283
+ values = values.map((i, j) => Fp.add(i, roundConstants[idx][j]));
284
+ if (isFull)
285
+ values = values.map((i) => sboxFn(i));
286
+ else
287
+ values[partialIdx] = sboxFn(values[partialIdx]);
288
+ // Matrix multiplication
289
+ values = mds.map((i) => i.reduce((acc, i, j) => Fp.add(acc, Fp.mulN(i, values[j])), Fp.ZERO));
290
+ return values;
291
+ };
292
+ const poseidonHash = function poseidonHash(values) {
293
+ if (!Array.isArray(values) || values.length !== t)
294
+ throw new Error('invalid values, expected array of bigints with length ' + t);
295
+ // `.map()` skips sparse holes, which would leak `undefined` into round math below.
296
+ values = values.slice();
297
+ for (let j = 0; j < values.length; j++) {
298
+ const i = values[j];
299
+ if (typeof i !== 'bigint')
300
+ throw new Error('invalid bigint=' + i);
301
+ values[j] = Fp.create(i);
302
+ }
303
+ let lastRound = 0;
304
+ // Apply r_f/2 full rounds.
305
+ for (let i = 0; i < halfRoundsFull; i++)
306
+ values = poseidonRound(values, true, lastRound++);
307
+ // Apply r_p partial rounds.
308
+ for (let i = 0; i < roundsPartial; i++)
309
+ values = poseidonRound(values, false, lastRound++);
310
+ // Apply r_f/2 full rounds.
311
+ for (let i = 0; i < halfRoundsFull; i++)
312
+ values = poseidonRound(values, true, lastRound++);
313
+ if (lastRound !== totalRounds)
314
+ throw new Error('invalid number of rounds');
315
+ return values;
316
+ };
317
+ // For verification in tests
318
+ Object.defineProperty(poseidonHash, 'roundConstants', {
319
+ value: roundConstants,
320
+ enumerable: true,
321
+ });
322
+ return poseidonHash;
323
+ }
324
+ /**
325
+ * @param Fp - Field implementation.
326
+ * @param rate - Sponge rate.
327
+ * @param capacity - Sponge capacity.
328
+ * @param hash - Poseidon permutation.
329
+ * @example
330
+ * Wrap one Poseidon permutation in a sponge interface.
331
+ *
332
+ * ```ts
333
+ * import { PoseidonSponge, grainGenConstants, poseidon } from './poseidon';
334
+ * import { Field } from './modular';
335
+ * const Fp = Field(17n);
336
+ * const constants = grainGenConstants({ Fp, t: 2, roundsFull: 8, roundsPartial: 8 });
337
+ * const hash = poseidon({ ...constants, Fp, t: 2, roundsFull: 8, roundsPartial: 8, sboxPower: 3 });
338
+ * const sponge = new PoseidonSponge(Fp, 1, 1, hash);
339
+ * sponge.absorb([1n]);
340
+ * const out = sponge.squeeze(1);
341
+ * ```
342
+ */
343
+ class PoseidonSponge {
344
+ Fp;
345
+ rate;
346
+ capacity;
347
+ hash;
348
+ state; // [...capacity, ...rate]
349
+ pos = 0;
350
+ isAbsorbing = true;
351
+ constructor(Fp, rate, capacity, hash) {
352
+ const width = spongeShape(rate, capacity);
353
+ // The direct constructor accepts an arbitrary permutation hook, but callers still
354
+ // need to preserve the `PoseidonFn.roundConstants` width metadata. Reject width
355
+ // mismatches here instead of deferring them until the first `process()` call.
356
+ if (width !== hash.roundConstants[0]?.length)
357
+ throw new Error(`invalid sponge width: expected ${hash.roundConstants[0]?.length}, got ${width}`);
358
+ this.Fp = Fp;
359
+ this.hash = hash;
360
+ this.rate = rate;
361
+ this.capacity = capacity;
362
+ this.state = new Array(width);
363
+ this.clean();
364
+ }
365
+ process() {
366
+ // The permutation is expected to return an owned state array. If callers inject a custom
367
+ // hook that reuses external storage, `clean()` will zero that shared buffer too.
368
+ this.state = this.hash(this.state);
369
+ }
370
+ absorb(input) {
371
+ for (const i of input)
372
+ if (typeof i !== 'bigint' || !this.Fp.isValid(i))
373
+ throw new Error('invalid input: ' + i);
374
+ for (let i = 0; i < input.length;) {
375
+ if (!this.isAbsorbing || this.pos === this.rate) {
376
+ this.process();
377
+ this.pos = 0;
378
+ this.isAbsorbing = true;
379
+ }
380
+ const chunk = Math.min(this.rate - this.pos, input.length - i);
381
+ for (let j = 0; j < chunk; j++) {
382
+ const idx = this.capacity + this.pos++;
383
+ this.state[idx] = this.Fp.add(this.state[idx], input[i++]);
384
+ }
385
+ }
386
+ }
387
+ squeeze(count) {
388
+ // Rust oracles use unsigned counts. In JS we keep `squeeze(0) => []` for
389
+ // compatibility, but still reject negative/fractional counts explicitly.
390
+ (0, utils_1.asafenumber)(count, 'count');
391
+ if (count < 0)
392
+ throw new Error('invalid number count');
393
+ const res = [];
394
+ while (res.length < count) {
395
+ if (this.isAbsorbing || this.pos === this.rate) {
396
+ this.process();
397
+ this.pos = 0;
398
+ this.isAbsorbing = false;
399
+ }
400
+ const chunk = Math.min(this.rate - this.pos, count - res.length);
401
+ for (let i = 0; i < chunk; i++)
402
+ res.push(this.state[this.capacity + this.pos++]);
403
+ }
404
+ return res;
405
+ }
406
+ clean() {
407
+ this.state.fill(this.Fp.ZERO);
408
+ this.isAbsorbing = true;
409
+ this.pos = 0;
410
+ }
411
+ clone() {
412
+ const c = new PoseidonSponge(this.Fp, this.rate, this.capacity, this.hash);
413
+ c.pos = this.pos;
414
+ c.isAbsorbing = this.isAbsorbing;
415
+ c.state = [...this.state];
416
+ return c;
417
+ }
418
+ }
419
+ exports.PoseidonSponge = PoseidonSponge;
420
+ const spongeShape = (rate, capacity) => {
421
+ (0, utils_1.asafenumber)(rate, 'rate');
422
+ (0, utils_1.asafenumber)(capacity, 'capacity');
423
+ // A sponge with zero rate cannot absorb or squeeze any field elements.
424
+ if (rate < 1)
425
+ throw new Error('invalid number rate');
426
+ // Negative capacity can accidentally keep `rate + capacity` coherent while still
427
+ // producing a nonsensical sponge shape.
428
+ if (capacity < 0)
429
+ throw new Error('invalid number capacity');
430
+ return rate + capacity;
431
+ };
432
+ /**
433
+ * The method is not defined in spec, but nevertheless used often.
434
+ * Check carefully for compatibility: there are many edge cases, like absorbing an empty array.
435
+ * We cross-test against:
436
+ * - {@link https://github.com/ProvableHQ/snarkVM/tree/staging/algorithms | snarkVM algorithms}
437
+ * - {@link https://github.com/arkworks-rs/crypto-primitives/tree/main | arkworks crypto-primitives}
438
+ * @param opts - Sponge options. See {@link PoseidonSpongeOpts}.
439
+ * @returns Factory for sponge instances.
440
+ * @throws If the sponge dimensions or backing permutation options are invalid. {@link Error}
441
+ * @example
442
+ * Use the sponge helper to absorb several field elements and squeeze one digest.
443
+ *
444
+ * ```ts
445
+ * import { grainGenConstants, poseidonSponge } from './poseidon';
446
+ * import { Field } from './modular';
447
+ * const Fp = Field(17n);
448
+ * const constants = grainGenConstants({ Fp, t: 2, roundsFull: 8, roundsPartial: 8 });
449
+ * const makeSponge = poseidonSponge({
450
+ * ...constants,
451
+ * Fp,
452
+ * rate: 1,
453
+ * capacity: 1,
454
+ * roundsFull: 8,
455
+ * roundsPartial: 8,
456
+ * sboxPower: 3,
457
+ * });
458
+ * const sponge = makeSponge();
459
+ * sponge.absorb([1n]);
460
+ * const out = sponge.squeeze(1);
461
+ * ```
462
+ */
463
+ function poseidonSponge(opts) {
464
+ const { rate, capacity } = opts;
465
+ const t = spongeShape(rate, capacity);
466
+ // Re-use one hash instance between sponge instances; isolation depends on
467
+ // poseidon(...) itself staying immutable and not carrying mutable call state.
468
+ const hash = poseidon({ ...opts, t });
469
+ const { Fp } = opts;
470
+ return (() => new PoseidonSponge(Fp, rate, capacity, hash));
471
+ }
@@ -0,0 +1,213 @@
1
+ /**
2
+ * Towered extension fields.
3
+ * Rather than implementing a massive 12th-degree extension directly, it is more efficient
4
+ * to build it up from smaller extensions: a tower of extensions.
5
+ *
6
+ * For BLS12-381, the Fp12 field is implemented as a quadratic (degree two) extension,
7
+ * on top of a cubic (degree three) extension, on top of a quadratic extension of Fp.
8
+ *
9
+ * For more info: "Pairings for beginners" by Costello, section 7.3.
10
+ * @module
11
+ */
12
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
13
+ import { type TArg, type TRet } from '../utils';
14
+ import * as mod from './modular';
15
+ import type { WeierstrassPoint, WeierstrassPointCons } from './weierstrass';
16
+ /** Pair of bigints used for quadratic-extension tuples. */
17
+ export type BigintTuple = [bigint, bigint];
18
+ /** Prime-field element. */
19
+ export type Fp = bigint;
20
+ /** Quadratic-extension field element `c0 + c1 * u`. */
21
+ export type Fp2 = {
22
+ /** Real component. */
23
+ c0: bigint;
24
+ /** Imaginary component. */
25
+ c1: bigint;
26
+ };
27
+ /** Six bigints used for sextic-extension tuples. */
28
+ export type BigintSix = [bigint, bigint, bigint, bigint, bigint, bigint];
29
+ /** Sextic-extension field element `c0 + c1 * v + c2 * v^2`. */
30
+ export type Fp6 = {
31
+ /** Constant coefficient. */
32
+ c0: Fp2;
33
+ /** Linear coefficient. */
34
+ c1: Fp2;
35
+ /** Quadratic coefficient. */
36
+ c2: Fp2;
37
+ };
38
+ /**
39
+ * Degree-12 extension field element `c0 + c1 * w`.
40
+ * Fp₁₂ = Fp₆² over Fp₂³, with Fp₆(w) / (w² - γ) where γ = v.
41
+ */
42
+ export type Fp12 = {
43
+ /** Constant coefficient. */
44
+ c0: Fp6;
45
+ /** Linear coefficient. */
46
+ c1: Fp6;
47
+ };
48
+ /** Twelve bigints used for degree-12 extension tuples. */
49
+ export type BigintTwelve = [
50
+ bigint,
51
+ bigint,
52
+ bigint,
53
+ bigint,
54
+ bigint,
55
+ bigint,
56
+ bigint,
57
+ bigint,
58
+ bigint,
59
+ bigint,
60
+ bigint,
61
+ bigint
62
+ ];
63
+ /** BLS-friendly helpers on top of the quadratic extension field. */
64
+ export type Fp2Bls = mod.IField<Fp2> & {
65
+ /** Underlying prime field. */
66
+ Fp: mod.IField<Fp>;
67
+ /** Apply one Frobenius map. */
68
+ frobeniusMap(num: Fp2, power: number): Fp2;
69
+ /** Build one field element from a raw bigint tuple. */
70
+ fromBigTuple(num: BigintTuple): Fp2;
71
+ /** Multiply by the curve `b` constant. */
72
+ mulByB: (num: Fp2) => Fp2;
73
+ /** Multiply by the quadratic non-residue. */
74
+ mulByNonresidue: (num: Fp2) => Fp2;
75
+ /** Split one quadratic element into real and imaginary components. */
76
+ reim: (num: Fp2) => {
77
+ re: Fp;
78
+ im: Fp;
79
+ };
80
+ /** Specialized helper used by sextic squaring formulas. */
81
+ Fp4Square: (a: Fp2, b: Fp2) => {
82
+ first: Fp2;
83
+ second: Fp2;
84
+ };
85
+ /** Quadratic non-residue used by the extension. */
86
+ NONRESIDUE: Fp2;
87
+ };
88
+ /** BLS-friendly helpers on top of the sextic extension field. */
89
+ export type Fp6Bls = mod.IField<Fp6> & {
90
+ /** Underlying quadratic extension field. */
91
+ Fp2: Fp2Bls;
92
+ /** Apply one Frobenius map. */
93
+ frobeniusMap(num: Fp6, power: number): Fp6;
94
+ /** Build one field element from a raw six-bigint tuple. */
95
+ fromBigSix: (tuple: BigintSix) => Fp6;
96
+ /** Multiply by a sparse `(0, b1, 0)` sextic element. */
97
+ mul1(num: Fp6, b1: Fp2): Fp6;
98
+ /** Multiply by a sparse `(b0, b1, 0)` sextic element. */
99
+ mul01(num: Fp6, b0: Fp2, b1: Fp2): Fp6;
100
+ /** Multiply by one quadratic-extension element. */
101
+ mulByFp2(lhs: Fp6, rhs: Fp2): Fp6;
102
+ /** Multiply by the sextic non-residue. */
103
+ mulByNonresidue: (num: Fp6) => Fp6;
104
+ };
105
+ /** BLS-friendly helpers on top of the degree-12 extension field. */
106
+ export type Fp12Bls = mod.IField<Fp12> & {
107
+ /** Underlying sextic extension field. */
108
+ Fp6: Fp6Bls;
109
+ /** Apply one Frobenius map. */
110
+ frobeniusMap(num: Fp12, power: number): Fp12;
111
+ /** Build one field element from a raw twelve-bigint tuple. */
112
+ fromBigTwelve: (t: BigintTwelve) => Fp12;
113
+ /** Multiply by a sparse `(o0, o1, 0, 0, o4, 0)` element. */
114
+ mul014(num: Fp12, o0: Fp2, o1: Fp2, o4: Fp2): Fp12;
115
+ /** Multiply by a sparse `(o0, 0, 0, o3, o4, 0)` element. */
116
+ mul034(num: Fp12, o0: Fp2, o3: Fp2, o4: Fp2): Fp12;
117
+ /** Multiply by one quadratic-extension element. */
118
+ mulByFp2(lhs: Fp12, rhs: Fp2): Fp12;
119
+ /** Conjugate one degree-12 element. */
120
+ conjugate(num: Fp12): Fp12;
121
+ /** Apply the final exponentiation from pairing arithmetic. */
122
+ finalExponentiate(num: Fp12): Fp12;
123
+ /** Apply one cyclotomic square. */
124
+ _cyclotomicSquare(num: Fp12): Fp12;
125
+ /** Apply one cyclotomic exponentiation. */
126
+ _cyclotomicExp(num: Fp12, n: bigint): Fp12;
127
+ };
128
+ declare function calcFrobeniusCoefficients<T>(Fp: TArg<mod.IField<T>>, nonResidue: T, modulus: bigint, degree: number, num?: number, divisor?: number): T[][];
129
+ export declare const __TEST: {
130
+ calcFrobeniusCoefficients: typeof calcFrobeniusCoefficients;
131
+ };
132
+ /**
133
+ * @param Fp - Base field implementation.
134
+ * @param Fp2 - Quadratic extension field.
135
+ * @param base - Twist-specific Frobenius base whose powers yield the `c1` / `c2` constants.
136
+ * BLS12-381 uses `1 / NONRESIDUE`; BN254 uses `NONRESIDUE`.
137
+ * @returns Frobenius endomorphism helpers.
138
+ * @throws If the derived Frobenius constants are inconsistent for the tower. {@link Error}
139
+ * @example
140
+ * Build Frobenius endomorphism helpers for a BLS extension tower.
141
+ *
142
+ * ```ts
143
+ * import { psiFrobenius } from './tower';
144
+ * import { bls12_381 } from '../bls12-381';
145
+ * const Fp = bls12_381.fields.Fp;
146
+ * const Fp2 = bls12_381.fields.Fp2;
147
+ * const frob = psiFrobenius(Fp, Fp2, Fp2.div(Fp2.ONE, Fp2.NONRESIDUE));
148
+ * const point = frob.G2psi(bls12_381.G2.Point, bls12_381.G2.Point.BASE);
149
+ * ```
150
+ */
151
+ export declare function psiFrobenius(Fp: TArg<mod.IField<Fp>>, Fp2: TArg<Fp2Bls>, base: TArg<Fp2>): {
152
+ psi: (x: Fp2, y: Fp2) => [Fp2, Fp2];
153
+ psi2: (x: Fp2, y: Fp2) => [Fp2, Fp2];
154
+ G2psi: (c: WeierstrassPointCons<Fp2>, P: WeierstrassPoint<Fp2>) => WeierstrassPoint<Fp2>;
155
+ G2psi2: (c: WeierstrassPointCons<Fp2>, P: WeierstrassPoint<Fp2>) => WeierstrassPoint<Fp2>;
156
+ PSI_X: Fp2;
157
+ PSI_Y: Fp2;
158
+ PSI2_X: Fp2;
159
+ PSI2_Y: Fp2;
160
+ };
161
+ /** Construction options for the BLS-style degree-12 tower. */
162
+ export type Tower12Opts = {
163
+ /** Prime-field order. */
164
+ ORDER: bigint;
165
+ /** Bit length of the BLS parameter `x`. */
166
+ X_LEN: number;
167
+ /** Prime-field non-residue used by the quadratic extension. */
168
+ NONRESIDUE?: Fp;
169
+ /** Quadratic-extension non-residue used by the sextic tower. */
170
+ FP2_NONRESIDUE: BigintTuple;
171
+ /**
172
+ * Optional custom quadratic square-root helper.
173
+ * Receives one quadratic-extension element and returns one square root.
174
+ */
175
+ Fp2sqrt?: (num: Fp2) => Fp2;
176
+ /**
177
+ * Multiply one quadratic element by the curve `b` constant.
178
+ * @param num - Quadratic-extension element to scale.
179
+ * @returns Product by the curve `b` constant.
180
+ */
181
+ Fp2mulByB: (num: Fp2) => Fp2;
182
+ /**
183
+ * Final exponentiation used by pairing arithmetic.
184
+ * @param num - Degree-12 field element to exponentiate.
185
+ * @returns Pairing result after final exponentiation.
186
+ */
187
+ Fp12finalExponentiate: (num: Fp12) => Fp12;
188
+ };
189
+ /**
190
+ * @param opts - Tower construction options. See {@link Tower12Opts}.
191
+ * @returns BLS tower fields.
192
+ * @throws If the tower options or derived Frobenius helpers are invalid. {@link Error}
193
+ * @example
194
+ * Construct the Fp2/Fp6/Fp12 tower used by a pairing-friendly curve.
195
+ *
196
+ * ```ts
197
+ * const fields = tower12({
198
+ * ORDER: 17n,
199
+ * X_LEN: 4,
200
+ * FP2_NONRESIDUE: [1n, 1n],
201
+ * Fp2mulByB: (num) => num,
202
+ * Fp12finalExponentiate: (num) => num,
203
+ * });
204
+ * const fp12 = fields.Fp12.ONE;
205
+ * ```
206
+ */
207
+ export declare function tower12(opts: TArg<Tower12Opts>): TRet<{
208
+ Fp: Readonly<mod.IField<bigint> & Required<Pick<mod.IField<bigint>, 'isOdd'>>>;
209
+ Fp2: Fp2Bls;
210
+ Fp6: Fp6Bls;
211
+ Fp12: Fp12Bls;
212
+ }>;
213
+ export {};