@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.
- package/LICENSE +21 -0
- package/README.md +75 -0
- package/abstract/bls.d.ts +410 -0
- package/abstract/bls.js +433 -0
- package/abstract/curve.d.ts +441 -0
- package/abstract/curve.js +622 -0
- package/abstract/edwards.d.ts +319 -0
- package/abstract/edwards.js +697 -0
- package/abstract/fft.d.ts +438 -0
- package/abstract/fft.js +580 -0
- package/abstract/frost.d.ts +292 -0
- package/abstract/frost.js +705 -0
- package/abstract/hash-to-curve.d.ts +238 -0
- package/abstract/hash-to-curve.js +353 -0
- package/abstract/modular.d.ts +550 -0
- package/abstract/modular.js +872 -0
- package/abstract/montgomery.d.ts +95 -0
- package/abstract/montgomery.js +180 -0
- package/abstract/oprf.d.ts +354 -0
- package/abstract/oprf.js +358 -0
- package/abstract/poseidon.d.ts +198 -0
- package/abstract/poseidon.js +471 -0
- package/abstract/tower.d.ts +213 -0
- package/abstract/tower.js +963 -0
- package/abstract/weierstrass.d.ts +587 -0
- package/abstract/weierstrass.js +1421 -0
- package/bls12-381.d.ts +23 -0
- package/bls12-381.js +680 -0
- package/bn254.d.ts +74 -0
- package/bn254.js +248 -0
- package/ed25519.d.ts +211 -0
- package/ed25519.js +626 -0
- package/ed448.d.ts +184 -0
- package/ed448.js +596 -0
- package/esm/abstract/bls.js +429 -0
- package/esm/abstract/curve.js +610 -0
- package/esm/abstract/edwards.js +691 -0
- package/esm/abstract/fft.js +567 -0
- package/esm/abstract/frost.js +702 -0
- package/esm/abstract/hash-to-curve.js +345 -0
- package/esm/abstract/modular.js +849 -0
- package/esm/abstract/montgomery.js +177 -0
- package/esm/abstract/oprf.js +355 -0
- package/esm/abstract/poseidon.js +462 -0
- package/esm/abstract/tower.js +925 -0
- package/esm/abstract/weierstrass.js +1411 -0
- package/esm/bls12-381.js +677 -0
- package/esm/bn254.js +244 -0
- package/esm/ed25519.js +622 -0
- package/esm/ed448.js +593 -0
- package/esm/index.js +38 -0
- package/esm/misc.js +211 -0
- package/esm/nist.js +266 -0
- package/esm/secp256k1.js +465 -0
- package/esm/utils.js +597 -0
- package/esm/webcrypto.js +362 -0
- package/index.d.ts +0 -0
- package/index.js +38 -0
- package/misc.d.ts +113 -0
- package/misc.js +216 -0
- package/nist.d.ts +136 -0
- package/nist.js +269 -0
- package/package.json +46 -0
- package/secp256k1.d.ts +152 -0
- package/secp256k1.js +468 -0
- package/utils.d.ts +535 -0
- package/utils.js +626 -0
- package/webcrypto.d.ts +240 -0
- package/webcrypto.js +365 -0
|
@@ -0,0 +1,462 @@
|
|
|
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 { asafenumber, bitGet, validateObject } from '../utils';
|
|
11
|
+
import { FpInvertBatch, FpPow, validateField } from './modular';
|
|
12
|
+
// Grain LFSR (Linear-Feedback Shift Register): https://eprint.iacr.org/2009/109.pdf
|
|
13
|
+
function grainLFSR(state) {
|
|
14
|
+
// Advances the caller-provided 80-entry state array in place; only the length
|
|
15
|
+
// is checked here, so entries are assumed to already be bits.
|
|
16
|
+
let pos = 0;
|
|
17
|
+
if (state.length !== 80)
|
|
18
|
+
throw new Error('grainLFRS: wrong state length, should be 80 bits');
|
|
19
|
+
const getBit = () => {
|
|
20
|
+
const r = (offset) => state[(pos + offset) % 80];
|
|
21
|
+
const bit = r(62) ^ r(51) ^ r(38) ^ r(23) ^ r(13) ^ r(0);
|
|
22
|
+
state[pos] = bit;
|
|
23
|
+
pos = ++pos % 80;
|
|
24
|
+
return !!bit;
|
|
25
|
+
};
|
|
26
|
+
for (let i = 0; i < 160; i++)
|
|
27
|
+
getBit();
|
|
28
|
+
return () => {
|
|
29
|
+
// https://en.wikipedia.org/wiki/Shrinking_generator
|
|
30
|
+
while (true) {
|
|
31
|
+
const b1 = getBit();
|
|
32
|
+
const b2 = getBit();
|
|
33
|
+
if (!b1)
|
|
34
|
+
continue;
|
|
35
|
+
return b2;
|
|
36
|
+
}
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
function assertValidPosOpts(opts) {
|
|
40
|
+
const { Fp, roundsFull } = opts;
|
|
41
|
+
validateField(Fp);
|
|
42
|
+
validateObject(opts, {
|
|
43
|
+
t: 'number',
|
|
44
|
+
roundsFull: 'number',
|
|
45
|
+
roundsPartial: 'number',
|
|
46
|
+
}, {
|
|
47
|
+
isSboxInverse: 'boolean',
|
|
48
|
+
});
|
|
49
|
+
for (const k of ['t', 'roundsFull', 'roundsPartial']) {
|
|
50
|
+
asafenumber(opts[k], k);
|
|
51
|
+
if (opts[k] < 1)
|
|
52
|
+
throw new Error('invalid number ' + k);
|
|
53
|
+
}
|
|
54
|
+
// Poseidon splits full rounds as `R_F / 2`, then partial rounds, then `R_F / 2` again.
|
|
55
|
+
if (roundsFull & 1)
|
|
56
|
+
throw new Error('roundsFull is not even' + roundsFull);
|
|
57
|
+
}
|
|
58
|
+
function poseidonGrain(opts) {
|
|
59
|
+
assertValidPosOpts(opts);
|
|
60
|
+
const { Fp } = opts;
|
|
61
|
+
const state = Array(80).fill(1);
|
|
62
|
+
let pos = 0;
|
|
63
|
+
const writeBits = (value, bitCount) => {
|
|
64
|
+
for (let i = bitCount - 1; i >= 0; i--)
|
|
65
|
+
state[pos++] = Number(bitGet(value, i));
|
|
66
|
+
};
|
|
67
|
+
const _0n = BigInt(0);
|
|
68
|
+
const _1n = BigInt(1);
|
|
69
|
+
// The Grain seed layout is fixed-width: `Fp.BITS` and `t` use 12 bits,
|
|
70
|
+
// `roundsFull` and `roundsPartial` use 10, so larger values are truncated here.
|
|
71
|
+
// This is intentional for compatibility with snarkVM / arkworks PoseidonGrainLFSR:
|
|
72
|
+
// they write the same fixed-width seed fields without range checks, then still consume
|
|
73
|
+
// the LFSR using the caller-provided round count for ARK/MDS generation.
|
|
74
|
+
// Normalizing or rejecting here would diverge from those implementations.
|
|
75
|
+
writeBits(_1n, 2); // prime field
|
|
76
|
+
writeBits(opts.isSboxInverse ? _1n : _0n, 4); // b2..b5
|
|
77
|
+
writeBits(BigInt(Fp.BITS), 12); // b6..b17
|
|
78
|
+
writeBits(BigInt(opts.t), 12); // b18..b29
|
|
79
|
+
writeBits(BigInt(opts.roundsFull), 10); // b30..b39
|
|
80
|
+
writeBits(BigInt(opts.roundsPartial), 10); // b40..b49
|
|
81
|
+
const getBit = grainLFSR(state);
|
|
82
|
+
return (count, reject) => {
|
|
83
|
+
const res = [];
|
|
84
|
+
for (let i = 0; i < count; i++) {
|
|
85
|
+
while (true) {
|
|
86
|
+
let num = _0n;
|
|
87
|
+
for (let i = 0; i < Fp.BITS; i++) {
|
|
88
|
+
num <<= _1n;
|
|
89
|
+
if (getBit())
|
|
90
|
+
num |= _1n;
|
|
91
|
+
}
|
|
92
|
+
if (reject && num >= Fp.ORDER)
|
|
93
|
+
continue; // rejection sampling
|
|
94
|
+
res.push(Fp.create(num));
|
|
95
|
+
break;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
return res;
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
// NOTE: this is not standard but used often for constant generation for poseidon
|
|
102
|
+
// (grain LFRS-like structure)
|
|
103
|
+
/**
|
|
104
|
+
* @param opts - Poseidon grain options. See {@link PoseidonGrainOpts}.
|
|
105
|
+
* @param skipMDS - Number of MDS samples to skip.
|
|
106
|
+
* @returns Generated constants.
|
|
107
|
+
* @throws If the generated MDS matrix contains a zero denominator. {@link Error}
|
|
108
|
+
* @example
|
|
109
|
+
* Generate Poseidon round constants and an MDS matrix from the Grain LFSR.
|
|
110
|
+
*
|
|
111
|
+
* ```ts
|
|
112
|
+
* import { grainGenConstants } from './poseidon';
|
|
113
|
+
* import { Field } from './modular';
|
|
114
|
+
* const Fp = Field(17n);
|
|
115
|
+
* const constants = grainGenConstants({ Fp, t: 2, roundsFull: 8, roundsPartial: 8 });
|
|
116
|
+
* ```
|
|
117
|
+
*/
|
|
118
|
+
export function grainGenConstants(opts, skipMDS = 0) {
|
|
119
|
+
const { Fp, t, roundsFull, roundsPartial } = opts;
|
|
120
|
+
// `skipMDS` counts how many candidate matrices to discard before taking one.
|
|
121
|
+
asafenumber(skipMDS, 'skipMDS');
|
|
122
|
+
if (skipMDS < 0)
|
|
123
|
+
throw new Error('invalid number skipMDS');
|
|
124
|
+
const rounds = roundsFull + roundsPartial;
|
|
125
|
+
// `sboxPower` is carried in the opts shape for Poseidon compatibility, but
|
|
126
|
+
// Grain constant generation here only depends on field/size/round counts/inverse flag.
|
|
127
|
+
const sample = poseidonGrain(opts);
|
|
128
|
+
const roundConstants = [];
|
|
129
|
+
for (let r = 0; r < rounds; r++)
|
|
130
|
+
roundConstants.push(sample(t, true));
|
|
131
|
+
if (skipMDS > 0)
|
|
132
|
+
for (let i = 0; i < skipMDS; i++)
|
|
133
|
+
sample(2 * t, false);
|
|
134
|
+
const xs = sample(t, false);
|
|
135
|
+
const ys = sample(t, false);
|
|
136
|
+
// Construct MDS Matrix M[i][j] = 1 / (xs[i] + ys[j])
|
|
137
|
+
const mds = [];
|
|
138
|
+
for (let i = 0; i < t; i++) {
|
|
139
|
+
const row = [];
|
|
140
|
+
for (let j = 0; j < t; j++) {
|
|
141
|
+
const xy = Fp.add(xs[i], ys[j]);
|
|
142
|
+
if (Fp.is0(xy))
|
|
143
|
+
throw new Error(`Error generating MDS matrix: xs[${i}] + ys[${j}] resulted in zero.`);
|
|
144
|
+
row.push(xy);
|
|
145
|
+
}
|
|
146
|
+
mds.push(FpInvertBatch(Fp, row));
|
|
147
|
+
}
|
|
148
|
+
return { roundConstants, mds };
|
|
149
|
+
}
|
|
150
|
+
/**
|
|
151
|
+
* @param opts - Poseidon options. See {@link PoseidonOpts}.
|
|
152
|
+
* @returns Normalized poseidon options.
|
|
153
|
+
* @throws If the Poseidon options, constants, or MDS matrix are invalid. {@link Error}
|
|
154
|
+
* @example
|
|
155
|
+
* Validate generated constants before constructing a permutation.
|
|
156
|
+
*
|
|
157
|
+
* ```ts
|
|
158
|
+
* import { grainGenConstants, validateOpts } from './poseidon';
|
|
159
|
+
* import { Field } from './modular';
|
|
160
|
+
* const Fp = Field(17n);
|
|
161
|
+
* const constants = grainGenConstants({ Fp, t: 2, roundsFull: 8, roundsPartial: 8 });
|
|
162
|
+
* const opts = validateOpts({ ...constants, Fp, t: 2, roundsFull: 8, roundsPartial: 8, sboxPower: 3 });
|
|
163
|
+
* ```
|
|
164
|
+
*/
|
|
165
|
+
export function validateOpts(opts) {
|
|
166
|
+
// This only normalizes shapes and field membership for the provided constants;
|
|
167
|
+
// it does not prove the stronger MDS/security criteria discussed in the specs.
|
|
168
|
+
assertValidPosOpts(opts);
|
|
169
|
+
const { Fp, mds, reversePartialPowIdx: rev, roundConstants: rc } = opts;
|
|
170
|
+
const { roundsFull, roundsPartial, sboxPower, t } = opts;
|
|
171
|
+
// MDS is TxT matrix
|
|
172
|
+
if (!Array.isArray(mds) || mds.length !== t)
|
|
173
|
+
throw new Error('Poseidon: invalid MDS matrix');
|
|
174
|
+
const _mds = mds.map((mdsRow) => {
|
|
175
|
+
if (!Array.isArray(mdsRow) || mdsRow.length !== t)
|
|
176
|
+
throw new Error('invalid MDS matrix row: ' + mdsRow);
|
|
177
|
+
return mdsRow.map((i) => {
|
|
178
|
+
if (typeof i !== 'bigint')
|
|
179
|
+
throw new Error('invalid MDS matrix bigint: ' + i);
|
|
180
|
+
// Hardcoded Poseidon MDS matrices often use signed entries like `-1`;
|
|
181
|
+
// accept bigint representatives here and reduce them into the field.
|
|
182
|
+
return Fp.create(i);
|
|
183
|
+
});
|
|
184
|
+
});
|
|
185
|
+
if (rev !== undefined && typeof rev !== 'boolean')
|
|
186
|
+
throw new Error('invalid param reversePartialPowIdx=' + rev);
|
|
187
|
+
if (roundsFull & 1)
|
|
188
|
+
throw new Error('roundsFull is not even' + roundsFull);
|
|
189
|
+
const rounds = roundsFull + roundsPartial;
|
|
190
|
+
if (!Array.isArray(rc) || rc.length !== rounds)
|
|
191
|
+
throw new Error('Poseidon: invalid round constants');
|
|
192
|
+
const roundConstants = rc.map((rc) => {
|
|
193
|
+
if (!Array.isArray(rc) || rc.length !== t)
|
|
194
|
+
throw new Error('invalid round constants');
|
|
195
|
+
return rc.map((i) => {
|
|
196
|
+
if (typeof i !== 'bigint' || !Fp.isValid(i))
|
|
197
|
+
throw new Error('invalid round constant');
|
|
198
|
+
return Fp.create(i);
|
|
199
|
+
});
|
|
200
|
+
});
|
|
201
|
+
// Freeze nested constants so exported handles cannot retune a live permutation instance.
|
|
202
|
+
const freezeRows = (rows) => Object.freeze(rows.map((row) => Object.freeze(row)));
|
|
203
|
+
if (!sboxPower || ![3, 5, 7, 17].includes(sboxPower))
|
|
204
|
+
throw new Error('invalid sboxPower');
|
|
205
|
+
const _sboxPower = BigInt(sboxPower);
|
|
206
|
+
let sboxFn = (n) => FpPow(Fp, n, _sboxPower);
|
|
207
|
+
// Unwrapped sbox power for common cases (195->142μs)
|
|
208
|
+
if (sboxPower === 3)
|
|
209
|
+
sboxFn = (n) => Fp.mul(Fp.sqrN(n), n);
|
|
210
|
+
else if (sboxPower === 5)
|
|
211
|
+
sboxFn = (n) => Fp.mul(Fp.sqrN(Fp.sqrN(n)), n);
|
|
212
|
+
return Object.freeze({
|
|
213
|
+
...opts,
|
|
214
|
+
rounds,
|
|
215
|
+
sboxFn,
|
|
216
|
+
roundConstants: freezeRows(roundConstants),
|
|
217
|
+
mds: freezeRows(_mds),
|
|
218
|
+
});
|
|
219
|
+
}
|
|
220
|
+
/**
|
|
221
|
+
* @param rc - Flattened round constants.
|
|
222
|
+
* @param t - Poseidon width.
|
|
223
|
+
* @returns Constants grouped by round.
|
|
224
|
+
* @throws If the width or flattened constant array is invalid. {@link Error}
|
|
225
|
+
* @example
|
|
226
|
+
* Regroup a flat constant list into per-round chunks.
|
|
227
|
+
*
|
|
228
|
+
* ```ts
|
|
229
|
+
* const rounds = splitConstants([1n, 2n, 3n, 4n], 2);
|
|
230
|
+
* ```
|
|
231
|
+
*/
|
|
232
|
+
export function splitConstants(rc, t) {
|
|
233
|
+
asafenumber(t, 't');
|
|
234
|
+
if (t < 1)
|
|
235
|
+
throw new Error('poseidonSplitConstants: invalid t');
|
|
236
|
+
if (!Array.isArray(rc) || rc.length % t)
|
|
237
|
+
throw new Error('poseidonSplitConstants: invalid rc');
|
|
238
|
+
const res = [];
|
|
239
|
+
let tmp = [];
|
|
240
|
+
for (let i = 0; i < rc.length; i++) {
|
|
241
|
+
const c = rc[i];
|
|
242
|
+
if (typeof c !== 'bigint')
|
|
243
|
+
throw new Error('invalid bigint=' + c);
|
|
244
|
+
tmp.push(c);
|
|
245
|
+
if (tmp.length === t) {
|
|
246
|
+
res.push(tmp);
|
|
247
|
+
tmp = [];
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
return res;
|
|
251
|
+
}
|
|
252
|
+
/** Poseidon NTT-friendly hash. */
|
|
253
|
+
/**
|
|
254
|
+
* @param opts - Poseidon options. See {@link PoseidonOpts}.
|
|
255
|
+
* @returns Poseidon permutation.
|
|
256
|
+
* @throws If the Poseidon options or state vector are invalid. {@link Error}
|
|
257
|
+
* @example
|
|
258
|
+
* Build a Poseidon permutation from validated parameters and constants.
|
|
259
|
+
*
|
|
260
|
+
* ```ts
|
|
261
|
+
* import { grainGenConstants, poseidon } from './poseidon';
|
|
262
|
+
* import { Field } from './modular';
|
|
263
|
+
* const Fp = Field(17n);
|
|
264
|
+
* const constants = grainGenConstants({ Fp, t: 2, roundsFull: 8, roundsPartial: 8 });
|
|
265
|
+
* const hash = poseidon({ ...constants, Fp, t: 2, roundsFull: 8, roundsPartial: 8, sboxPower: 3 });
|
|
266
|
+
* const state = hash([1n, 2n]);
|
|
267
|
+
* ```
|
|
268
|
+
*/
|
|
269
|
+
export function poseidon(opts) {
|
|
270
|
+
const _opts = validateOpts(opts);
|
|
271
|
+
const { Fp, mds, roundConstants, rounds: totalRounds, roundsPartial, sboxFn, t } = _opts;
|
|
272
|
+
const halfRoundsFull = _opts.roundsFull / 2;
|
|
273
|
+
const partialIdx = _opts.reversePartialPowIdx ? t - 1 : 0;
|
|
274
|
+
const poseidonRound = (values, isFull, idx) => {
|
|
275
|
+
values = values.map((i, j) => Fp.add(i, roundConstants[idx][j]));
|
|
276
|
+
if (isFull)
|
|
277
|
+
values = values.map((i) => sboxFn(i));
|
|
278
|
+
else
|
|
279
|
+
values[partialIdx] = sboxFn(values[partialIdx]);
|
|
280
|
+
// Matrix multiplication
|
|
281
|
+
values = mds.map((i) => i.reduce((acc, i, j) => Fp.add(acc, Fp.mulN(i, values[j])), Fp.ZERO));
|
|
282
|
+
return values;
|
|
283
|
+
};
|
|
284
|
+
const poseidonHash = function poseidonHash(values) {
|
|
285
|
+
if (!Array.isArray(values) || values.length !== t)
|
|
286
|
+
throw new Error('invalid values, expected array of bigints with length ' + t);
|
|
287
|
+
// `.map()` skips sparse holes, which would leak `undefined` into round math below.
|
|
288
|
+
values = values.slice();
|
|
289
|
+
for (let j = 0; j < values.length; j++) {
|
|
290
|
+
const i = values[j];
|
|
291
|
+
if (typeof i !== 'bigint')
|
|
292
|
+
throw new Error('invalid bigint=' + i);
|
|
293
|
+
values[j] = Fp.create(i);
|
|
294
|
+
}
|
|
295
|
+
let lastRound = 0;
|
|
296
|
+
// Apply r_f/2 full rounds.
|
|
297
|
+
for (let i = 0; i < halfRoundsFull; i++)
|
|
298
|
+
values = poseidonRound(values, true, lastRound++);
|
|
299
|
+
// Apply r_p partial rounds.
|
|
300
|
+
for (let i = 0; i < roundsPartial; i++)
|
|
301
|
+
values = poseidonRound(values, false, lastRound++);
|
|
302
|
+
// Apply r_f/2 full rounds.
|
|
303
|
+
for (let i = 0; i < halfRoundsFull; i++)
|
|
304
|
+
values = poseidonRound(values, true, lastRound++);
|
|
305
|
+
if (lastRound !== totalRounds)
|
|
306
|
+
throw new Error('invalid number of rounds');
|
|
307
|
+
return values;
|
|
308
|
+
};
|
|
309
|
+
// For verification in tests
|
|
310
|
+
Object.defineProperty(poseidonHash, 'roundConstants', {
|
|
311
|
+
value: roundConstants,
|
|
312
|
+
enumerable: true,
|
|
313
|
+
});
|
|
314
|
+
return poseidonHash;
|
|
315
|
+
}
|
|
316
|
+
/**
|
|
317
|
+
* @param Fp - Field implementation.
|
|
318
|
+
* @param rate - Sponge rate.
|
|
319
|
+
* @param capacity - Sponge capacity.
|
|
320
|
+
* @param hash - Poseidon permutation.
|
|
321
|
+
* @example
|
|
322
|
+
* Wrap one Poseidon permutation in a sponge interface.
|
|
323
|
+
*
|
|
324
|
+
* ```ts
|
|
325
|
+
* import { PoseidonSponge, grainGenConstants, poseidon } from './poseidon';
|
|
326
|
+
* import { Field } from './modular';
|
|
327
|
+
* const Fp = Field(17n);
|
|
328
|
+
* const constants = grainGenConstants({ Fp, t: 2, roundsFull: 8, roundsPartial: 8 });
|
|
329
|
+
* const hash = poseidon({ ...constants, Fp, t: 2, roundsFull: 8, roundsPartial: 8, sboxPower: 3 });
|
|
330
|
+
* const sponge = new PoseidonSponge(Fp, 1, 1, hash);
|
|
331
|
+
* sponge.absorb([1n]);
|
|
332
|
+
* const out = sponge.squeeze(1);
|
|
333
|
+
* ```
|
|
334
|
+
*/
|
|
335
|
+
export class PoseidonSponge {
|
|
336
|
+
Fp;
|
|
337
|
+
rate;
|
|
338
|
+
capacity;
|
|
339
|
+
hash;
|
|
340
|
+
state; // [...capacity, ...rate]
|
|
341
|
+
pos = 0;
|
|
342
|
+
isAbsorbing = true;
|
|
343
|
+
constructor(Fp, rate, capacity, hash) {
|
|
344
|
+
const width = spongeShape(rate, capacity);
|
|
345
|
+
// The direct constructor accepts an arbitrary permutation hook, but callers still
|
|
346
|
+
// need to preserve the `PoseidonFn.roundConstants` width metadata. Reject width
|
|
347
|
+
// mismatches here instead of deferring them until the first `process()` call.
|
|
348
|
+
if (width !== hash.roundConstants[0]?.length)
|
|
349
|
+
throw new Error(`invalid sponge width: expected ${hash.roundConstants[0]?.length}, got ${width}`);
|
|
350
|
+
this.Fp = Fp;
|
|
351
|
+
this.hash = hash;
|
|
352
|
+
this.rate = rate;
|
|
353
|
+
this.capacity = capacity;
|
|
354
|
+
this.state = new Array(width);
|
|
355
|
+
this.clean();
|
|
356
|
+
}
|
|
357
|
+
process() {
|
|
358
|
+
// The permutation is expected to return an owned state array. If callers inject a custom
|
|
359
|
+
// hook that reuses external storage, `clean()` will zero that shared buffer too.
|
|
360
|
+
this.state = this.hash(this.state);
|
|
361
|
+
}
|
|
362
|
+
absorb(input) {
|
|
363
|
+
for (const i of input)
|
|
364
|
+
if (typeof i !== 'bigint' || !this.Fp.isValid(i))
|
|
365
|
+
throw new Error('invalid input: ' + i);
|
|
366
|
+
for (let i = 0; i < input.length;) {
|
|
367
|
+
if (!this.isAbsorbing || this.pos === this.rate) {
|
|
368
|
+
this.process();
|
|
369
|
+
this.pos = 0;
|
|
370
|
+
this.isAbsorbing = true;
|
|
371
|
+
}
|
|
372
|
+
const chunk = Math.min(this.rate - this.pos, input.length - i);
|
|
373
|
+
for (let j = 0; j < chunk; j++) {
|
|
374
|
+
const idx = this.capacity + this.pos++;
|
|
375
|
+
this.state[idx] = this.Fp.add(this.state[idx], input[i++]);
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
squeeze(count) {
|
|
380
|
+
// Rust oracles use unsigned counts. In JS we keep `squeeze(0) => []` for
|
|
381
|
+
// compatibility, but still reject negative/fractional counts explicitly.
|
|
382
|
+
asafenumber(count, 'count');
|
|
383
|
+
if (count < 0)
|
|
384
|
+
throw new Error('invalid number count');
|
|
385
|
+
const res = [];
|
|
386
|
+
while (res.length < count) {
|
|
387
|
+
if (this.isAbsorbing || this.pos === this.rate) {
|
|
388
|
+
this.process();
|
|
389
|
+
this.pos = 0;
|
|
390
|
+
this.isAbsorbing = false;
|
|
391
|
+
}
|
|
392
|
+
const chunk = Math.min(this.rate - this.pos, count - res.length);
|
|
393
|
+
for (let i = 0; i < chunk; i++)
|
|
394
|
+
res.push(this.state[this.capacity + this.pos++]);
|
|
395
|
+
}
|
|
396
|
+
return res;
|
|
397
|
+
}
|
|
398
|
+
clean() {
|
|
399
|
+
this.state.fill(this.Fp.ZERO);
|
|
400
|
+
this.isAbsorbing = true;
|
|
401
|
+
this.pos = 0;
|
|
402
|
+
}
|
|
403
|
+
clone() {
|
|
404
|
+
const c = new PoseidonSponge(this.Fp, this.rate, this.capacity, this.hash);
|
|
405
|
+
c.pos = this.pos;
|
|
406
|
+
c.isAbsorbing = this.isAbsorbing;
|
|
407
|
+
c.state = [...this.state];
|
|
408
|
+
return c;
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
const spongeShape = (rate, capacity) => {
|
|
412
|
+
asafenumber(rate, 'rate');
|
|
413
|
+
asafenumber(capacity, 'capacity');
|
|
414
|
+
// A sponge with zero rate cannot absorb or squeeze any field elements.
|
|
415
|
+
if (rate < 1)
|
|
416
|
+
throw new Error('invalid number rate');
|
|
417
|
+
// Negative capacity can accidentally keep `rate + capacity` coherent while still
|
|
418
|
+
// producing a nonsensical sponge shape.
|
|
419
|
+
if (capacity < 0)
|
|
420
|
+
throw new Error('invalid number capacity');
|
|
421
|
+
return rate + capacity;
|
|
422
|
+
};
|
|
423
|
+
/**
|
|
424
|
+
* The method is not defined in spec, but nevertheless used often.
|
|
425
|
+
* Check carefully for compatibility: there are many edge cases, like absorbing an empty array.
|
|
426
|
+
* We cross-test against:
|
|
427
|
+
* - {@link https://github.com/ProvableHQ/snarkVM/tree/staging/algorithms | snarkVM algorithms}
|
|
428
|
+
* - {@link https://github.com/arkworks-rs/crypto-primitives/tree/main | arkworks crypto-primitives}
|
|
429
|
+
* @param opts - Sponge options. See {@link PoseidonSpongeOpts}.
|
|
430
|
+
* @returns Factory for sponge instances.
|
|
431
|
+
* @throws If the sponge dimensions or backing permutation options are invalid. {@link Error}
|
|
432
|
+
* @example
|
|
433
|
+
* Use the sponge helper to absorb several field elements and squeeze one digest.
|
|
434
|
+
*
|
|
435
|
+
* ```ts
|
|
436
|
+
* import { grainGenConstants, poseidonSponge } from './poseidon';
|
|
437
|
+
* import { Field } from './modular';
|
|
438
|
+
* const Fp = Field(17n);
|
|
439
|
+
* const constants = grainGenConstants({ Fp, t: 2, roundsFull: 8, roundsPartial: 8 });
|
|
440
|
+
* const makeSponge = poseidonSponge({
|
|
441
|
+
* ...constants,
|
|
442
|
+
* Fp,
|
|
443
|
+
* rate: 1,
|
|
444
|
+
* capacity: 1,
|
|
445
|
+
* roundsFull: 8,
|
|
446
|
+
* roundsPartial: 8,
|
|
447
|
+
* sboxPower: 3,
|
|
448
|
+
* });
|
|
449
|
+
* const sponge = makeSponge();
|
|
450
|
+
* sponge.absorb([1n]);
|
|
451
|
+
* const out = sponge.squeeze(1);
|
|
452
|
+
* ```
|
|
453
|
+
*/
|
|
454
|
+
export function poseidonSponge(opts) {
|
|
455
|
+
const { rate, capacity } = opts;
|
|
456
|
+
const t = spongeShape(rate, capacity);
|
|
457
|
+
// Re-use one hash instance between sponge instances; isolation depends on
|
|
458
|
+
// poseidon(...) itself staying immutable and not carrying mutable call state.
|
|
459
|
+
const hash = poseidon({ ...opts, t });
|
|
460
|
+
const { Fp } = opts;
|
|
461
|
+
return (() => new PoseidonSponge(Fp, rate, capacity, hash));
|
|
462
|
+
}
|