@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,358 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createOPRF = createOPRF;
4
+ /**
5
+ * RFC 9497: Oblivious Pseudorandom Functions (OPRFs) Using Prime-Order Groups.
6
+ * https://www.rfc-editor.org/rfc/rfc9497
7
+ *
8
+
9
+ OPRF allows to interactively create an `Output = PRF(Input, serverSecretKey)`:
10
+
11
+ - Server cannot calculate Output by itself: it doesn't know Input
12
+ - Client cannot calculate Output by itself: it doesn't know server secretKey
13
+ - An attacker interception the communication can't restore Input/Output/serverSecretKey and can't
14
+ link Input to some value.
15
+
16
+ ## Issues
17
+
18
+ - Low-entropy inputs (e.g. password '123') enable brute-forced dictionary attacks by the server
19
+ (solveable by domain separation in POPRF)
20
+ - High-level protocol needs to be constructed on top, because OPRF is low-level
21
+
22
+ ## Use cases
23
+
24
+ 1. **Password-Authenticated Key Exchange (PAKE):** Enables secure password login (e.g., OPAQUE)
25
+ without revealing the password to the server.
26
+ 2. **Private Set Intersection (PSI):** Allows two parties to compute the intersection of their
27
+ private sets without revealing non-intersecting elements.
28
+ 3. **Anonymous Credential Systems:** Supports issuance of anonymous, unlinkable credentials
29
+ (e.g., Privacy Pass) using blind OPRF evaluation.
30
+ 4. **Private Information Retrieval (PIR):** Helps users query databases without revealing which
31
+ item they accessed.
32
+ 5. **Encrypted Search / Secure Indexing:** Enables keyword search over encrypted data while keeping
33
+ queries private.
34
+ 6. **Spam Prevention and Rate-Limiting:** Issues anonymous tokens to prevent abuse
35
+ (e.g., CAPTCHA bypass) without compromising user privacy.
36
+
37
+ ## Modes
38
+
39
+ - OPRF: simple mode, client doesn't need to know server public key
40
+ - VOPRF: verifiable mode. It lets the client verify that the server used the
41
+ secret key corresponding to a known public key
42
+ - POPRF: partially oblivious mode, VOPRF + domain separation
43
+
44
+ There is also non-interactive mode (Evaluate), which creates Output
45
+ non-interactively with knowledge of the secret key.
46
+
47
+ Flow:
48
+ - (once) Server generates secret and public keys, distributes public keys to clients
49
+ - deterministically: `deriveKeyPair` or just random: `generateKeyPair`
50
+ - Client blinds input: `blind(secretInput)`
51
+ - Server evaluates blinded input: `blindEvaluate` generated by client, sends result to client
52
+ - Client creates output using result of evaluation via 'finalize'
53
+
54
+ * @module
55
+ */
56
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
57
+ const utils_1 = require("../utils");
58
+ const curve_1 = require("./curve");
59
+ const hash_to_curve_1 = require("./hash-to-curve");
60
+ const modular_1 = require("./modular");
61
+ const _DST_scalarBytes = /* @__PURE__ */ (0, utils_1.asciiToBytes)(hash_to_curve_1._DST_scalar);
62
+ // welcome to generic hell
63
+ /**
64
+ * @param opts - OPRF ciphersuite options. See {@link OPRFOpts}.
65
+ * @returns OPRF helper namespace.
66
+ * @example
67
+ * Instantiate an OPRF suite from curve-specific hashing hooks.
68
+ *
69
+ * ```ts
70
+ * import { createOPRF } from './oprf';
71
+ * import { p256, p256_hasher } from '../nist';
72
+ * import { sha256 } from '@decryption/hashes/sha2';
73
+ * const oprf = createOPRF({
74
+ * name: 'P256-SHA256',
75
+ * Point: p256.Point,
76
+ * hash: sha256,
77
+ * hashToGroup: p256_hasher.hashToCurve,
78
+ * hashToScalar: p256_hasher.hashToScalar,
79
+ * });
80
+ * const keys = oprf.oprf.generateKeyPair();
81
+ * ```
82
+ */
83
+ function createOPRF(opts) {
84
+ (0, utils_1.validateObject)(opts, {
85
+ name: 'string',
86
+ hash: 'function',
87
+ hashToScalar: 'function',
88
+ hashToGroup: 'function',
89
+ });
90
+ // Cheap constructor-surface sanity check only: this verifies the generic static hooks/fields that
91
+ // OPRF consumes, but it does not certify point semantics like BASE/ZERO correctness.
92
+ (0, curve_1.validatePointCons)(opts.Point);
93
+ const { name, Point, hash } = opts;
94
+ const { Fn } = Point;
95
+ const hashToGroup = (msg, ctx) => opts.hashToGroup(msg, {
96
+ DST: (0, utils_1.concatBytes)((0, utils_1.asciiToBytes)('HashToGroup-'), ctx),
97
+ });
98
+ const hashToScalarPrefixed = (msg, ctx) => opts.hashToScalar(msg, { DST: (0, utils_1.concatBytes)(_DST_scalarBytes, ctx) });
99
+ const randomScalar = (rng = utils_1.randomBytes) => {
100
+ // RFC 9497 §2.1 defines RandomScalar as nonzero; blind inversion and generated public keys
101
+ // both rely on keeping this helper in the `1..n-1` range.
102
+ const t = (0, modular_1.mapHashToField)(rng((0, modular_1.getMinHashLength)(Fn.ORDER)), Fn.ORDER, Fn.isLE);
103
+ // We cannot use Fn.fromBytes here, because field
104
+ // can have different number of bytes (like ed448)
105
+ return Fn.isLE ? (0, utils_1.bytesToNumberLE)(t) : (0, utils_1.bytesToNumberBE)(t);
106
+ };
107
+ const msm = (points, scalars) => (0, curve_1.pippenger)(Point, points, scalars);
108
+ const getCtx = (mode) => (0, utils_1.concatBytes)((0, utils_1.asciiToBytes)('OPRFV1-'), new Uint8Array([mode]), (0, utils_1.asciiToBytes)('-' + name));
109
+ const ctxOPRF = getCtx(0x00);
110
+ const ctxVOPRF = getCtx(0x01);
111
+ const ctxPOPRF = getCtx(0x02);
112
+ function encode(...args) {
113
+ const res = [];
114
+ for (const a of args) {
115
+ if (typeof a === 'number')
116
+ res.push((0, utils_1.numberToBytesBE)(a, 2));
117
+ else if (typeof a === 'string')
118
+ res.push((0, utils_1.asciiToBytes)(a));
119
+ else {
120
+ (0, utils_1.abytes)(a);
121
+ res.push((0, utils_1.numberToBytesBE)(a.length, 2), a);
122
+ }
123
+ }
124
+ // No wipe here, since will modify actual bytes
125
+ return (0, utils_1.concatBytes)(...res);
126
+ }
127
+ const inputBytes = (title, bytes) => {
128
+ (0, utils_1.abytes)(bytes, undefined, title);
129
+ // RFC 9497 §1.2 limits PrivateInput/PublicInput to 2^16 - 1 bytes because these values are
130
+ // length-prefixed with two bytes before use throughout the protocol.
131
+ if (bytes.length > 0xffff)
132
+ throw new Error(`"${title}" expected Uint8Array of length <= 65535, got length=${bytes.length}`);
133
+ return bytes;
134
+ };
135
+ const hashInput = (...bytes) => hash(encode(...bytes, 'Finalize'));
136
+ function getTranscripts(B, C, D, ctx) {
137
+ const Bm = B.toBytes();
138
+ const seed = hash(encode(Bm, (0, utils_1.concatBytes)((0, utils_1.asciiToBytes)('Seed-'), ctx)));
139
+ const res = [];
140
+ for (let i = 0; i < C.length; i++) {
141
+ const Ci = C[i].toBytes();
142
+ const Di = D[i].toBytes();
143
+ const di = hashToScalarPrefixed(encode(seed, i, Ci, Di, 'Composite'), ctx);
144
+ res.push(di);
145
+ }
146
+ return res;
147
+ }
148
+ function computeComposites(B, C, D, ctx) {
149
+ const T = getTranscripts(B, C, D, ctx);
150
+ const M = msm(C, T);
151
+ const Z = msm(D, T);
152
+ return { M, Z };
153
+ }
154
+ function computeCompositesFast(k, B, C, D, ctx) {
155
+ const T = getTranscripts(B, C, D, ctx);
156
+ const M = msm(C, T);
157
+ // RFC 9497 §2.2.1 ComputeCompositesFast derives weights from both C and D in getTranscripts(),
158
+ // then uses the server shortcut Z = k * M instead of a second MSM over D.
159
+ const Z = M.multiply(k);
160
+ return { M, Z };
161
+ }
162
+ function challengeTranscript(B, M, Z, t2, t3, ctx) {
163
+ const [Bm, a0, a1, a2, a3] = [B, M, Z, t2, t3].map((i) => i.toBytes());
164
+ return hashToScalarPrefixed(encode(Bm, a0, a1, a2, a3, 'Challenge'), ctx);
165
+ }
166
+ function generateProof(ctx, k, B, C, D, rng) {
167
+ const { M, Z } = computeCompositesFast(k, B, C, D, ctx);
168
+ const r = randomScalar(rng);
169
+ const t2 = Point.BASE.multiply(r);
170
+ const t3 = M.multiply(r);
171
+ const c = challengeTranscript(B, M, Z, t2, t3, ctx);
172
+ const s = Fn.sub(r, Fn.mul(c, k)); // r - c*k
173
+ return (0, utils_1.concatBytes)(...[c, s].map((i) => Fn.toBytes(i)));
174
+ }
175
+ function verifyProof(ctx, B, C, D, proof) {
176
+ (0, utils_1.abytes)(proof, 2 * Fn.BYTES);
177
+ const { M, Z } = computeComposites(B, C, D, ctx);
178
+ const [c, s] = [proof.subarray(0, Fn.BYTES), proof.subarray(Fn.BYTES)].map((f) => Fn.fromBytes(f));
179
+ const t2 = Point.BASE.multiply(s).add(B.multiply(c)); // s*G + c*B
180
+ const t3 = M.multiply(s).add(Z.multiply(c)); // s*M + c*Z
181
+ const expectedC = challengeTranscript(B, M, Z, t2, t3, ctx);
182
+ if (!Fn.eql(c, expectedC))
183
+ throw new Error('proof verification failed');
184
+ }
185
+ function generateKeyPair() {
186
+ const skS = randomScalar();
187
+ const pkS = Point.BASE.multiply(skS);
188
+ return { secretKey: Fn.toBytes(skS), publicKey: pkS.toBytes() };
189
+ }
190
+ function deriveKeyPair(ctx, seed, info) {
191
+ // RFC 9497 §3.2.1 defines `seed[32]`; reject other sizes here because this public API already
192
+ // documents a 32-byte seed instead of generic input keying material.
193
+ (0, utils_1.abytes)(seed, 32, 'seed');
194
+ info = inputBytes('keyInfo', info);
195
+ const dst = (0, utils_1.concatBytes)((0, utils_1.asciiToBytes)('DeriveKeyPair'), ctx);
196
+ const msg = (0, utils_1.concatBytes)(seed, encode(info), Uint8Array.of(0));
197
+ for (let counter = 0; counter <= 255; counter++) {
198
+ msg[msg.length - 1] = counter;
199
+ const skS = opts.hashToScalar(msg, { DST: dst });
200
+ if (Fn.is0(skS))
201
+ continue; // should not happen
202
+ return {
203
+ secretKey: Fn.toBytes(skS),
204
+ publicKey: Point.BASE.multiply(skS).toBytes(),
205
+ };
206
+ }
207
+ throw new Error('Cannot derive key');
208
+ }
209
+ const wirePoint = (label, bytes) => {
210
+ const point = Point.fromBytes(bytes);
211
+ // RFC 9497 §3.3 says applications MUST reject group-identity Elements received over the wire
212
+ // after deserialization, even if the suite decoder itself accepts the identity encoding.
213
+ if (point.equals(Point.ZERO))
214
+ throw new Error(label + ' point at infinity');
215
+ return point;
216
+ };
217
+ function blind(ctx, input, rng = utils_1.randomBytes) {
218
+ input = inputBytes('input', input);
219
+ const blind = randomScalar(rng);
220
+ const inputPoint = hashToGroup(input, ctx);
221
+ if (inputPoint.equals(Point.ZERO))
222
+ throw new Error('Input point at infinity');
223
+ const blinded = inputPoint.multiply(blind);
224
+ return { blind: Fn.toBytes(blind), blinded: blinded.toBytes() };
225
+ }
226
+ function evaluate(ctx, secretKey, input) {
227
+ input = inputBytes('input', input);
228
+ const skS = Fn.fromBytes(secretKey);
229
+ const inputPoint = hashToGroup(input, ctx);
230
+ if (inputPoint.equals(Point.ZERO))
231
+ throw new Error('Input point at infinity');
232
+ const unblinded = inputPoint.multiply(skS).toBytes();
233
+ return hashInput(input, unblinded);
234
+ }
235
+ const oprf = Object.freeze({
236
+ generateKeyPair,
237
+ deriveKeyPair: (seed, keyInfo) => deriveKeyPair(ctxOPRF, seed, keyInfo),
238
+ blind: (input, rng = utils_1.randomBytes) => blind(ctxOPRF, input, rng),
239
+ blindEvaluate(secretKey, blindedPoint) {
240
+ const skS = Fn.fromBytes(secretKey);
241
+ const elm = wirePoint('blinded', blindedPoint);
242
+ return elm.multiply(skS).toBytes();
243
+ },
244
+ finalize(input, blindBytes, evaluatedBytes) {
245
+ input = inputBytes('input', input);
246
+ const blind = Fn.fromBytes(blindBytes);
247
+ const evalPoint = wirePoint('evaluated', evaluatedBytes);
248
+ const unblinded = evalPoint.multiply(Fn.inv(blind)).toBytes();
249
+ return hashInput(input, unblinded);
250
+ },
251
+ evaluate: (secretKey, input) => evaluate(ctxOPRF, secretKey, input),
252
+ });
253
+ const voprf = Object.freeze({
254
+ generateKeyPair,
255
+ deriveKeyPair: (seed, keyInfo) => deriveKeyPair(ctxVOPRF, seed, keyInfo),
256
+ blind: (input, rng = utils_1.randomBytes) => blind(ctxVOPRF, input, rng),
257
+ blindEvaluateBatch(secretKey, publicKey, blinded, rng = utils_1.randomBytes) {
258
+ if (!Array.isArray(blinded))
259
+ throw new Error('expected array');
260
+ const skS = Fn.fromBytes(secretKey);
261
+ const pkS = wirePoint('public key', publicKey);
262
+ const blindedPoints = blinded.map((i) => wirePoint('blinded', i));
263
+ const evaluated = blindedPoints.map((i) => i.multiply(skS));
264
+ const proof = generateProof(ctxVOPRF, skS, pkS, blindedPoints, evaluated, rng);
265
+ return { evaluated: evaluated.map((i) => i.toBytes()), proof };
266
+ },
267
+ blindEvaluate(secretKey, publicKey, blinded, rng = utils_1.randomBytes) {
268
+ const res = this.blindEvaluateBatch(secretKey, publicKey, [blinded], rng);
269
+ return { evaluated: res.evaluated[0], proof: res.proof };
270
+ },
271
+ finalizeBatch(items, publicKey, proof) {
272
+ if (!Array.isArray(items))
273
+ throw new Error('expected array');
274
+ const pkS = wirePoint('public key', publicKey);
275
+ const blindedPoints = items.map((i) => wirePoint('blinded', i.blinded));
276
+ const evalPoints = items.map((i) => wirePoint('evaluated', i.evaluated));
277
+ verifyProof(ctxVOPRF, pkS, blindedPoints, evalPoints, proof);
278
+ return items.map((i) => oprf.finalize(i.input, i.blind, i.evaluated));
279
+ },
280
+ finalize(input, blind, evaluated, blinded, publicKey, proof) {
281
+ return this.finalizeBatch([{ input, blind, evaluated, blinded }], publicKey, proof)[0];
282
+ },
283
+ evaluate: (secretKey, input) => evaluate(ctxVOPRF, secretKey, input),
284
+ });
285
+ // NOTE: info is domain separation
286
+ const poprf = (info) => {
287
+ info = inputBytes('info', info);
288
+ const m = hashToScalarPrefixed(encode('Info', info), ctxPOPRF);
289
+ const T = Point.BASE.multiply(m);
290
+ return Object.freeze({
291
+ generateKeyPair,
292
+ deriveKeyPair: (seed, keyInfo) => deriveKeyPair(ctxPOPRF, seed, keyInfo),
293
+ blind(input, publicKey, rng = utils_1.randomBytes) {
294
+ input = inputBytes('input', input);
295
+ const pkS = wirePoint('public key', publicKey);
296
+ const tweakedKey = T.add(pkS);
297
+ if (tweakedKey.equals(Point.ZERO))
298
+ throw new Error('tweakedKey point at infinity');
299
+ const blind = randomScalar(rng);
300
+ const inputPoint = hashToGroup(input, ctxPOPRF);
301
+ if (inputPoint.equals(Point.ZERO))
302
+ throw new Error('Input point at infinity');
303
+ const blindedPoint = inputPoint.multiply(blind);
304
+ return {
305
+ blind: Fn.toBytes(blind),
306
+ blinded: blindedPoint.toBytes(),
307
+ tweakedKey: tweakedKey.toBytes(),
308
+ };
309
+ },
310
+ blindEvaluateBatch(secretKey, blinded, rng = utils_1.randomBytes) {
311
+ if (!Array.isArray(blinded))
312
+ throw new Error('expected array');
313
+ const skS = Fn.fromBytes(secretKey);
314
+ const t = Fn.add(skS, m);
315
+ // "Hence, this error can be a signal for the server to replace its
316
+ // private key". We throw inside; this should be impossible.
317
+ const invT = Fn.inv(t);
318
+ const blindedPoints = blinded.map((i) => wirePoint('blinded', i));
319
+ const evalPoints = blindedPoints.map((i) => i.multiply(invT));
320
+ const tweakedKey = Point.BASE.multiply(t);
321
+ const proof = generateProof(ctxPOPRF, t, tweakedKey, evalPoints, blindedPoints, rng);
322
+ return { evaluated: evalPoints.map((i) => i.toBytes()), proof };
323
+ },
324
+ blindEvaluate(secretKey, blinded, rng = utils_1.randomBytes) {
325
+ const res = this.blindEvaluateBatch(secretKey, [blinded], rng);
326
+ return { evaluated: res.evaluated[0], proof: res.proof };
327
+ },
328
+ finalizeBatch(items, proof, tweakedKey) {
329
+ if (!Array.isArray(items))
330
+ throw new Error('expected array');
331
+ const inputs = items.map((i) => inputBytes('input', i.input));
332
+ const evalPoints = items.map((i) => wirePoint('evaluated', i.evaluated));
333
+ verifyProof(ctxPOPRF, wirePoint('tweakedKey', tweakedKey), evalPoints, items.map((i) => wirePoint('blinded', i.blinded)), proof);
334
+ return items.map((i, j) => {
335
+ const blind = Fn.fromBytes(i.blind);
336
+ const point = evalPoints[j].multiply(Fn.inv(blind)).toBytes();
337
+ return hashInput(inputs[j], info, point);
338
+ });
339
+ },
340
+ finalize(input, blind, evaluated, blinded, proof, tweakedKey) {
341
+ return this.finalizeBatch([{ input, blind, evaluated, blinded }], proof, tweakedKey)[0];
342
+ },
343
+ evaluate(secretKey, input) {
344
+ input = inputBytes('input', input);
345
+ const skS = Fn.fromBytes(secretKey);
346
+ const inputPoint = hashToGroup(input, ctxPOPRF);
347
+ if (inputPoint.equals(Point.ZERO))
348
+ throw new Error('Input point at infinity');
349
+ const t = Fn.add(skS, m);
350
+ const invT = Fn.inv(t);
351
+ const unblinded = inputPoint.multiply(invT).toBytes();
352
+ return hashInput(input, info, unblinded);
353
+ },
354
+ });
355
+ };
356
+ const res = { name, oprf, voprf, poprf, __tests: Object.freeze({ Fn }) };
357
+ return Object.freeze(res);
358
+ }
@@ -0,0 +1,198 @@
1
+ /**
2
+ * Implements [Poseidon](https://www.poseidon-hash.info) ZK-friendly hash.
3
+ *
4
+ * There are many poseidon variants with different constants.
5
+ * We don't provide them: you should construct them manually.
6
+ * Check out [micro-starknet](https://github.com/paulmillr/micro-starknet) package for a proper example.
7
+ * @module
8
+ */
9
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
10
+ import { type TArg, type TRet } from '../utils';
11
+ import { type IField } from './modular';
12
+ /** Core Poseidon permutation parameters shared by all variants. */
13
+ export type PoseidonBasicOpts = {
14
+ /** Prime field used by the permutation. */
15
+ Fp: IField<bigint>;
16
+ /** Poseidon width `t = rate + capacity`. */
17
+ t: number;
18
+ /** Number of full S-box rounds. */
19
+ roundsFull: number;
20
+ /** Number of partial S-box rounds. */
21
+ roundsPartial: number;
22
+ /** Whether to use the inverse S-box variant. */
23
+ isSboxInverse?: boolean;
24
+ };
25
+ /** Poseidon settings used by the Grain-LFSR constant generator. */
26
+ export type PoseidonGrainOpts = PoseidonBasicOpts & {
27
+ /** S-box power used while generating constants. */
28
+ sboxPower?: number;
29
+ };
30
+ type PoseidonConstants = {
31
+ mds: bigint[][];
32
+ roundConstants: bigint[][];
33
+ };
34
+ /**
35
+ * @param opts - Poseidon grain options. See {@link PoseidonGrainOpts}.
36
+ * @param skipMDS - Number of MDS samples to skip.
37
+ * @returns Generated constants.
38
+ * @throws If the generated MDS matrix contains a zero denominator. {@link Error}
39
+ * @example
40
+ * Generate Poseidon round constants and an MDS matrix from the Grain LFSR.
41
+ *
42
+ * ```ts
43
+ * import { grainGenConstants } from './poseidon';
44
+ * import { Field } from './modular';
45
+ * const Fp = Field(17n);
46
+ * const constants = grainGenConstants({ Fp, t: 2, roundsFull: 8, roundsPartial: 8 });
47
+ * ```
48
+ */
49
+ export declare function grainGenConstants(opts: TArg<PoseidonGrainOpts>, skipMDS?: number): PoseidonConstants;
50
+ /** Fully specified Poseidon permutation options with explicit constants. */
51
+ export type PoseidonOpts = PoseidonBasicOpts & PoseidonConstants & {
52
+ /** S-box power used by the permutation. */
53
+ sboxPower?: number;
54
+ /** Whether to reverse the partial-round S-box index. */
55
+ reversePartialPowIdx?: boolean;
56
+ };
57
+ /**
58
+ * @param opts - Poseidon options. See {@link PoseidonOpts}.
59
+ * @returns Normalized poseidon options.
60
+ * @throws If the Poseidon options, constants, or MDS matrix are invalid. {@link Error}
61
+ * @example
62
+ * Validate generated constants before constructing a permutation.
63
+ *
64
+ * ```ts
65
+ * import { grainGenConstants, validateOpts } from './poseidon';
66
+ * import { Field } from './modular';
67
+ * const Fp = Field(17n);
68
+ * const constants = grainGenConstants({ Fp, t: 2, roundsFull: 8, roundsPartial: 8 });
69
+ * const opts = validateOpts({ ...constants, Fp, t: 2, roundsFull: 8, roundsPartial: 8, sboxPower: 3 });
70
+ * ```
71
+ */
72
+ export declare function validateOpts(opts: TArg<PoseidonOpts>): TRet<Readonly<{
73
+ rounds: number;
74
+ sboxFn: (n: bigint) => bigint;
75
+ roundConstants: bigint[][];
76
+ mds: bigint[][];
77
+ Fp: IField<bigint>;
78
+ t: number;
79
+ roundsFull: number;
80
+ roundsPartial: number;
81
+ sboxPower?: number;
82
+ reversePartialPowIdx?: boolean;
83
+ }>>;
84
+ /**
85
+ * @param rc - Flattened round constants.
86
+ * @param t - Poseidon width.
87
+ * @returns Constants grouped by round.
88
+ * @throws If the width or flattened constant array is invalid. {@link Error}
89
+ * @example
90
+ * Regroup a flat constant list into per-round chunks.
91
+ *
92
+ * ```ts
93
+ * const rounds = splitConstants([1n, 2n, 3n, 4n], 2);
94
+ * ```
95
+ */
96
+ export declare function splitConstants(rc: bigint[], t: number): bigint[][];
97
+ /**
98
+ * Poseidon permutation callable.
99
+ * @param values - Poseidon state vector. Non-canonical bigints are normalized with `Fp.create(...)`.
100
+ * @returns Permuted state vector.
101
+ */
102
+ export type PoseidonFn = {
103
+ (values: bigint[]): bigint[];
104
+ /** Round constants captured by the permutation instance. */
105
+ roundConstants: bigint[][];
106
+ };
107
+ /** Poseidon NTT-friendly hash. */
108
+ /**
109
+ * @param opts - Poseidon options. See {@link PoseidonOpts}.
110
+ * @returns Poseidon permutation.
111
+ * @throws If the Poseidon options or state vector are invalid. {@link Error}
112
+ * @example
113
+ * Build a Poseidon permutation from validated parameters and constants.
114
+ *
115
+ * ```ts
116
+ * import { grainGenConstants, poseidon } from './poseidon';
117
+ * import { Field } from './modular';
118
+ * const Fp = Field(17n);
119
+ * const constants = grainGenConstants({ Fp, t: 2, roundsFull: 8, roundsPartial: 8 });
120
+ * const hash = poseidon({ ...constants, Fp, t: 2, roundsFull: 8, roundsPartial: 8, sboxPower: 3 });
121
+ * const state = hash([1n, 2n]);
122
+ * ```
123
+ */
124
+ export declare function poseidon(opts: TArg<PoseidonOpts>): PoseidonFn;
125
+ /**
126
+ * @param Fp - Field implementation.
127
+ * @param rate - Sponge rate.
128
+ * @param capacity - Sponge capacity.
129
+ * @param hash - Poseidon permutation.
130
+ * @example
131
+ * Wrap one Poseidon permutation in a sponge interface.
132
+ *
133
+ * ```ts
134
+ * import { PoseidonSponge, grainGenConstants, poseidon } from './poseidon';
135
+ * import { Field } from './modular';
136
+ * const Fp = Field(17n);
137
+ * const constants = grainGenConstants({ Fp, t: 2, roundsFull: 8, roundsPartial: 8 });
138
+ * const hash = poseidon({ ...constants, Fp, t: 2, roundsFull: 8, roundsPartial: 8, sboxPower: 3 });
139
+ * const sponge = new PoseidonSponge(Fp, 1, 1, hash);
140
+ * sponge.absorb([1n]);
141
+ * const out = sponge.squeeze(1);
142
+ * ```
143
+ */
144
+ export declare class PoseidonSponge {
145
+ private Fp;
146
+ readonly rate: number;
147
+ readonly capacity: number;
148
+ readonly hash: PoseidonFn;
149
+ private state;
150
+ private pos;
151
+ private isAbsorbing;
152
+ constructor(Fp: IField<bigint>, rate: number, capacity: number, hash: PoseidonFn);
153
+ private process;
154
+ absorb(input: bigint[]): void;
155
+ squeeze(count: number): bigint[];
156
+ clean(): void;
157
+ clone(): PoseidonSponge;
158
+ }
159
+ /** Options for the non-standard but commonly used Poseidon sponge wrapper. */
160
+ export type PoseidonSpongeOpts = Omit<PoseidonOpts, 't'> & {
161
+ /** Sponge rate. */
162
+ rate: number;
163
+ /** Sponge capacity. */
164
+ capacity: number;
165
+ };
166
+ /**
167
+ * The method is not defined in spec, but nevertheless used often.
168
+ * Check carefully for compatibility: there are many edge cases, like absorbing an empty array.
169
+ * We cross-test against:
170
+ * - {@link https://github.com/ProvableHQ/snarkVM/tree/staging/algorithms | snarkVM algorithms}
171
+ * - {@link https://github.com/arkworks-rs/crypto-primitives/tree/main | arkworks crypto-primitives}
172
+ * @param opts - Sponge options. See {@link PoseidonSpongeOpts}.
173
+ * @returns Factory for sponge instances.
174
+ * @throws If the sponge dimensions or backing permutation options are invalid. {@link Error}
175
+ * @example
176
+ * Use the sponge helper to absorb several field elements and squeeze one digest.
177
+ *
178
+ * ```ts
179
+ * import { grainGenConstants, poseidonSponge } from './poseidon';
180
+ * import { Field } from './modular';
181
+ * const Fp = Field(17n);
182
+ * const constants = grainGenConstants({ Fp, t: 2, roundsFull: 8, roundsPartial: 8 });
183
+ * const makeSponge = poseidonSponge({
184
+ * ...constants,
185
+ * Fp,
186
+ * rate: 1,
187
+ * capacity: 1,
188
+ * roundsFull: 8,
189
+ * roundsPartial: 8,
190
+ * sboxPower: 3,
191
+ * });
192
+ * const sponge = makeSponge();
193
+ * sponge.absorb([1n]);
194
+ * const out = sponge.squeeze(1);
195
+ * ```
196
+ */
197
+ export declare function poseidonSponge(opts: TArg<PoseidonSpongeOpts>): TRet<() => PoseidonSponge>;
198
+ export {};