@crisp-e3/contracts 0.15.0 → 0.17.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.
@@ -0,0 +1,2493 @@
1
+ // SPDX-License-Identifier: LGPL-3.0-only
2
+ //
3
+ // This file is provided WITHOUT ANY WARRANTY;
4
+ // without even the implied warranty of MERCHANTABILITY
5
+ // or FITNESS FOR A PARTICULAR PURPOSE.
6
+ pragma solidity >=0.8.21;
7
+
8
+ uint256 constant N = 2097152;
9
+ uint256 constant LOG_N = 21;
10
+ uint256 constant NUMBER_OF_PUBLIC_INPUTS = 17;
11
+ uint256 constant VK_HASH = 0x0b1a8d6509209282299c53d628ce472a47ef437bdb6799ccbc0423372bb530d4;
12
+ library HonkVerificationKey {
13
+ function loadVerificationKey() internal pure returns (Honk.VerificationKey memory) {
14
+ Honk.VerificationKey memory vk = Honk.VerificationKey({
15
+ circuitSize: uint256(2097152),
16
+ logCircuitSize: uint256(21),
17
+ publicInputsSize: uint256(17),
18
+ ql: Honk.G1Point({
19
+ x: uint256(0x2089549d27c8b4fa58dd4ed5276c42ccc9830ee5cd64cf877df0301a02d54e62),
20
+ y: uint256(0x01137e39f6b1ec6101fad7a4472102bfe11e7534e55e58109734c4b927efe6a6)
21
+ }),
22
+ qr: Honk.G1Point({
23
+ x: uint256(0x289b159ca7e4437437f18d73d2b649c2043fa68dfcf97dbfeedf6f1b424d068b),
24
+ y: uint256(0x28ed000f4b9a44c36695072beaab8802db7f39473ce933426e62ee4f817e0899)
25
+ }),
26
+ qo: Honk.G1Point({
27
+ x: uint256(0x18424976826978ddb710bfdc21c64a296884c27b0d8dadf6ac7681445dde8d8c),
28
+ y: uint256(0x1690625dd2a2a6afa259cfe9dc7601058bd3275e8fcea82e008caa319c2710b4)
29
+ }),
30
+ q4: Honk.G1Point({
31
+ x: uint256(0x025aeec2f923a237df2c5ddfe9bc1af74bdaf41d2fe47aa4c0cb12dc4cafac76),
32
+ y: uint256(0x0a3ecdb966ed757ad3acc3e2ad670b804b582686b85bdad85ebe18713cddd85e)
33
+ }),
34
+ qm: Honk.G1Point({
35
+ x: uint256(0x1b562d7113fa8ac2dec528dfcec26f0c0b1290f9a0fa7cd08ee8492b7f8ed657),
36
+ y: uint256(0x188c0bdd795dda2f441f73f4a93919cf28417e039c491966c4305582edfcf63f)
37
+ }),
38
+ qc: Honk.G1Point({
39
+ x: uint256(0x0b824186ff62956e929ad489895b6f94e44fedde51b9c7ada98f43339fa875e2),
40
+ y: uint256(0x288402862aac013f44d9af847a2a1b318e8f3c026d50818ed5467c252505f8b8)
41
+ }),
42
+ qLookup: Honk.G1Point({
43
+ x: uint256(0x0000000000000000000000000000000000000000000000000000000000000000),
44
+ y: uint256(0x0000000000000000000000000000000000000000000000000000000000000000)
45
+ }),
46
+ qArith: Honk.G1Point({
47
+ x: uint256(0x1eec43a65b0287ccdadfdee7b5c7f1edd764f78af3be146380f9285dc23935ac),
48
+ y: uint256(0x00334d21a1e3fdb81573ecfedf177b7a266b994f7c03e603d22c1d50a14c1177)
49
+ }),
50
+ qDeltaRange: Honk.G1Point({
51
+ x: uint256(0x1fbf72c051dd975693c7581ba456e27c8779526d6226300b89fdcb2f46236846),
52
+ y: uint256(0x15c7e84bd025a07f602a5ced777d9a6dc519fa77e263fd6ae739a872ced3403b)
53
+ }),
54
+ qElliptic: Honk.G1Point({
55
+ x: uint256(0x0000000000000000000000000000000000000000000000000000000000000000),
56
+ y: uint256(0x0000000000000000000000000000000000000000000000000000000000000000)
57
+ }),
58
+ qMemory: Honk.G1Point({
59
+ x: uint256(0x047852a9a4fee8460c8a70000bd59b1e9fa7b3a8ebe89a4a9bd74f8b667ec0e3),
60
+ y: uint256(0x206a2850fbba93adfaaf19b47f64be4050e7e3d0934e3bb3c152c6d0ebf9bc6e)
61
+ }),
62
+ qNnf: Honk.G1Point({
63
+ x: uint256(0x1bbbf2123e3d8fb40a55063fc262031ed631ba08b2403fc66be28284d8bf81f0),
64
+ y: uint256(0x22ed7e7b495a40b67a9131d0ec78104425c718cfcb4a1d539cc0efb438863481)
65
+ }),
66
+ qPoseidon2External: Honk.G1Point({
67
+ x: uint256(0x0545a1bebaefe1aed53b541c02ff5f8dc6ea9fcf3790df43723cec27fad71211),
68
+ y: uint256(0x0f6e3454a6b2e0f9ef6e3c3c420d2212f9b9611dcc56c93cb3f7b3a843b8b061)
69
+ }),
70
+ qPoseidon2Internal: Honk.G1Point({
71
+ x: uint256(0x1dc8084a81e94401164ab0cc7dd600fdcccf393611a00c881b100f125a7c2cae),
72
+ y: uint256(0x1b45db8582b61bd1f9938b966fd2c62007a4e6b29bd12d93300fc87fc248541c)
73
+ }),
74
+ s1: Honk.G1Point({
75
+ x: uint256(0x0055c092383ecaa42ba772ccd0dc288af43851c2230e18ce204b0b921c565ebb),
76
+ y: uint256(0x29586aa1c092712c4d7337d3017e2ca1c0b460b5020366e3a218f5dbdb65dac3)
77
+ }),
78
+ s2: Honk.G1Point({
79
+ x: uint256(0x03c15d176f3295a287398c9bd47ebcbae4206b787ae7f99a0b4b845ba42c5b8f),
80
+ y: uint256(0x06046a4ecd73c3a079fdd9b1aadb3ec8a10d81bbdfff4fe64491b5d73850c951)
81
+ }),
82
+ s3: Honk.G1Point({
83
+ x: uint256(0x2ab36d90282916edcc8344a83329989d6ab32ce72e50a8c5fb71bdc96cc13bba),
84
+ y: uint256(0x1f91bde663a11f2dd1c2189801544154219b96fc15c228a2afaf94c2fd525614)
85
+ }),
86
+ s4: Honk.G1Point({
87
+ x: uint256(0x20e8b44228a8581f3b89daf0afd122fb5eb9b54235e5f3006f4da3ced24a4bff),
88
+ y: uint256(0x121da33cdfeb99d9117a23a70ca53f0409a753f28e8217d6297f2d890507fa06)
89
+ }),
90
+ t1: Honk.G1Point({
91
+ x: uint256(0x0000000000000000000000000000000000000000000000000000000000000000),
92
+ y: uint256(0x0000000000000000000000000000000000000000000000000000000000000000)
93
+ }),
94
+ t2: Honk.G1Point({
95
+ x: uint256(0x0000000000000000000000000000000000000000000000000000000000000000),
96
+ y: uint256(0x0000000000000000000000000000000000000000000000000000000000000000)
97
+ }),
98
+ t3: Honk.G1Point({
99
+ x: uint256(0x0000000000000000000000000000000000000000000000000000000000000000),
100
+ y: uint256(0x0000000000000000000000000000000000000000000000000000000000000000)
101
+ }),
102
+ t4: Honk.G1Point({
103
+ x: uint256(0x0000000000000000000000000000000000000000000000000000000000000000),
104
+ y: uint256(0x0000000000000000000000000000000000000000000000000000000000000000)
105
+ }),
106
+ id1: Honk.G1Point({
107
+ x: uint256(0x165a0d0053cad2cfaf860a8dffc7b857ae52a0830a5d0ff389f126736c8a68af),
108
+ y: uint256(0x1230c74e80658090adff46f20a5ba230b00a36fa1647bbee26dcd4f61c81ac74)
109
+ }),
110
+ id2: Honk.G1Point({
111
+ x: uint256(0x0cde9685338036c896bf8031dfb4a27df07170d25a17a6f3487ff9dbc2d58d97),
112
+ y: uint256(0x2ba321fb18bb8416deb007188ba7eaf7d9acc32649feb97b99b61a385503e561)
113
+ }),
114
+ id3: Honk.G1Point({
115
+ x: uint256(0x1803faf5351782f647e62d18cffbd667c89844b034d38e49c4317b6c6c262efc),
116
+ y: uint256(0x00d296c60b3f1ad4f263c6c0cf1c931573e621b89604b5a18add83543af491fb)
117
+ }),
118
+ id4: Honk.G1Point({
119
+ x: uint256(0x22136f96d01a39d6cd8808212c2d90f8f539d0c302bbfbe0856ec5858d14026e),
120
+ y: uint256(0x0c8e6eb560ae1fe67f9341f70bc50ad204ee5da5814a40a811d777be4d796ad7)
121
+ }),
122
+ lagrangeFirst: Honk.G1Point({
123
+ x: uint256(0x2a56ce41f6b0be13b9c26747621b821eee81b23a887f299049b14c11e98460d6),
124
+ y: uint256(0x1aa98f2de3ddda547d8f6de4e725ded5827d6338c78656c0d12ca1aea6ef2c7c)
125
+ }),
126
+ lagrangeLast: Honk.G1Point({
127
+ x: uint256(0x054b6343cdc2405ed0b8e6603bd33aad161e52d8b252ff7916e72f9474fb5c92),
128
+ y: uint256(0x0d9a27acd4b305126491136fbce26d1bc29ecf5b067fe121b87d7347cdf3baf0)
129
+ })
130
+ });
131
+ return vk;
132
+ }
133
+ }
134
+
135
+ pragma solidity ^0.8.27;
136
+
137
+ interface IVerifier {
138
+ function verify(bytes calldata _proof, bytes32[] calldata _publicInputs) external view returns (bool);
139
+ }
140
+
141
+ /**
142
+ * @notice Library of error codes
143
+ * @dev You can run `forge inspect Errors errors` to get the selectors for the optimised verifier
144
+ */
145
+ library Errors {
146
+ error ValueGeLimbMax();
147
+ error ValueGeGroupOrder();
148
+ error ValueGeFieldOrder();
149
+
150
+ error InvertOfZero();
151
+ error NotPowerOfTwo();
152
+ error ModExpFailed();
153
+
154
+ error ProofLengthWrong();
155
+ error ProofLengthWrongWithLogN(uint256 logN, uint256 actualLength, uint256 expectedLength);
156
+ error PublicInputsLengthWrong();
157
+ error SumcheckFailed();
158
+ error ShpleminiFailed();
159
+
160
+ error PointAtInfinity();
161
+
162
+ error ConsistencyCheckFailed();
163
+ error VerificationKeyConfigurationMismatch();
164
+ error GeminiChallengeInSubgroup();
165
+ }
166
+
167
+ type Fr is uint256;
168
+
169
+ using { add as + } for Fr global;
170
+ using { sub as - } for Fr global;
171
+ using { mul as * } for Fr global;
172
+
173
+ using { notEqual as != } for Fr global;
174
+ using { equal as == } for Fr global;
175
+
176
+ uint256 constant SUBGROUP_SIZE = 256;
177
+ uint256 constant MODULUS = 21888242871839275222246405745257275088548364400416034343698204186575808495617; // Prime field order
178
+ uint256 constant P = MODULUS;
179
+ Fr constant SUBGROUP_GENERATOR = Fr.wrap(0x07b0c561a6148404f086204a9f36ffb0617942546750f230c893619174a57a76);
180
+ Fr constant SUBGROUP_GENERATOR_INVERSE = Fr.wrap(0x204bd3277422fad364751ad938e2b5e6a54cf8c68712848a692c553d0329f5d6);
181
+ Fr constant MINUS_ONE = Fr.wrap(MODULUS - 1);
182
+ Fr constant ONE = Fr.wrap(1);
183
+ Fr constant ZERO = Fr.wrap(0);
184
+
185
+ // SmallSubgroupIPA opening-claim layout — mirrors SMALL_IPA_CLAIMS in
186
+ // barretenberg/cpp/src/barretenberg/commitment_schemes/small_subgroup_ipa/small_subgroup_ipa_utils.hpp.
187
+ uint256 constant NUM_SMALL_IPA_OPENING_CLAIMS = 5;
188
+ uint256 constant SMALL_IPA_BOUNDARY_OPENING_IDX = 3;
189
+ uint256 constant NUM_SMALL_IPA_TRANSCRIPT_EVALS = 4;
190
+ // Instantiation
191
+
192
+ library FrLib {
193
+ bytes4 internal constant FRLIB_MODEXP_FAILED_SELECTOR = 0x1f7ec5f0;
194
+
195
+ function invert(Fr value) internal view returns (Fr) {
196
+ uint256 v = Fr.unwrap(value);
197
+ require(v != 0, Errors.InvertOfZero());
198
+
199
+ uint256 result;
200
+
201
+ // Call the modexp precompile to invert in the field
202
+ assembly {
203
+ let free := mload(0x40)
204
+ mstore(free, 0x20)
205
+ mstore(add(free, 0x20), 0x20)
206
+ mstore(add(free, 0x40), 0x20)
207
+ mstore(add(free, 0x60), v)
208
+ mstore(add(free, 0x80), sub(MODULUS, 2))
209
+ mstore(add(free, 0xa0), MODULUS)
210
+ let success := staticcall(gas(), 0x05, free, 0xc0, 0x00, 0x20)
211
+ if iszero(success) {
212
+ mstore(0x00, FRLIB_MODEXP_FAILED_SELECTOR)
213
+ revert(0, 0x04)
214
+ }
215
+ result := mload(0x00)
216
+ mstore(0x40, add(free, 0xc0))
217
+ }
218
+
219
+ return Fr.wrap(result);
220
+ }
221
+
222
+ function pow(Fr base, uint256 v) internal view returns (Fr) {
223
+ uint256 b = Fr.unwrap(base);
224
+ // Only works for power of 2
225
+ require(v > 0 && (v & (v - 1)) == 0, Errors.NotPowerOfTwo());
226
+ uint256 result;
227
+
228
+ // Call the modexp precompile to invert in the field
229
+ assembly {
230
+ let free := mload(0x40)
231
+ mstore(free, 0x20)
232
+ mstore(add(free, 0x20), 0x20)
233
+ mstore(add(free, 0x40), 0x20)
234
+ mstore(add(free, 0x60), b)
235
+ mstore(add(free, 0x80), v)
236
+ mstore(add(free, 0xa0), MODULUS)
237
+ let success := staticcall(gas(), 0x05, free, 0xc0, 0x00, 0x20)
238
+ if iszero(success) {
239
+ mstore(0x00, FRLIB_MODEXP_FAILED_SELECTOR)
240
+ revert(0, 0x04)
241
+ }
242
+ result := mload(0x00)
243
+ mstore(0x40, add(free, 0xc0))
244
+ }
245
+
246
+ return Fr.wrap(result);
247
+ }
248
+
249
+ function div(Fr numerator, Fr denominator) internal view returns (Fr) {
250
+ unchecked {
251
+ return numerator * invert(denominator);
252
+ }
253
+ }
254
+
255
+ function sqr(Fr value) internal pure returns (Fr) {
256
+ unchecked {
257
+ return value * value;
258
+ }
259
+ }
260
+
261
+ function unwrap(Fr value) internal pure returns (uint256) {
262
+ unchecked {
263
+ return Fr.unwrap(value);
264
+ }
265
+ }
266
+
267
+ function neg(Fr value) internal pure returns (Fr) {
268
+ unchecked {
269
+ return Fr.wrap(MODULUS - Fr.unwrap(value));
270
+ }
271
+ }
272
+
273
+ function from(uint256 value) internal pure returns (Fr) {
274
+ unchecked {
275
+ require(value < MODULUS, Errors.ValueGeFieldOrder());
276
+ return Fr.wrap(value);
277
+ }
278
+ }
279
+
280
+ function fromBytes32(bytes32 value) internal pure returns (Fr) {
281
+ unchecked {
282
+ uint256 v = uint256(value);
283
+ require(v < MODULUS, Errors.ValueGeFieldOrder());
284
+ return Fr.wrap(v);
285
+ }
286
+ }
287
+
288
+ function toBytes32(Fr value) internal pure returns (bytes32) {
289
+ unchecked {
290
+ return bytes32(Fr.unwrap(value));
291
+ }
292
+ }
293
+ }
294
+
295
+ // Free functions
296
+ function add(Fr a, Fr b) pure returns (Fr) {
297
+ unchecked {
298
+ return Fr.wrap(addmod(Fr.unwrap(a), Fr.unwrap(b), MODULUS));
299
+ }
300
+ }
301
+
302
+ function mul(Fr a, Fr b) pure returns (Fr) {
303
+ unchecked {
304
+ return Fr.wrap(mulmod(Fr.unwrap(a), Fr.unwrap(b), MODULUS));
305
+ }
306
+ }
307
+
308
+ function sub(Fr a, Fr b) pure returns (Fr) {
309
+ unchecked {
310
+ return Fr.wrap(addmod(Fr.unwrap(a), MODULUS - Fr.unwrap(b), MODULUS));
311
+ }
312
+ }
313
+
314
+ function notEqual(Fr a, Fr b) pure returns (bool) {
315
+ unchecked {
316
+ return Fr.unwrap(a) != Fr.unwrap(b);
317
+ }
318
+ }
319
+
320
+ function equal(Fr a, Fr b) pure returns (bool) {
321
+ unchecked {
322
+ return Fr.unwrap(a) == Fr.unwrap(b);
323
+ }
324
+ }
325
+
326
+ uint256 constant CONST_PROOF_SIZE_LOG_N = 25;
327
+
328
+ uint256 constant NUMBER_OF_SUBRELATIONS = 29;
329
+ uint256 constant BATCHED_RELATION_PARTIAL_LENGTH = 8;
330
+ uint256 constant ZK_BATCHED_RELATION_PARTIAL_LENGTH = 9;
331
+ uint256 constant NUMBER_OF_ENTITIES = 41;
332
+ // The number of entities added for ZK (gemini_masking_poly)
333
+ uint256 constant NUM_MASKING_POLYNOMIALS = 1;
334
+ uint256 constant NUMBER_OF_ENTITIES_ZK = NUMBER_OF_ENTITIES + NUM_MASKING_POLYNOMIALS;
335
+ uint256 constant NUMBER_UNSHIFTED = 36;
336
+ uint256 constant NUMBER_UNSHIFTED_ZK = NUMBER_UNSHIFTED + NUM_MASKING_POLYNOMIALS;
337
+ uint256 constant NUMBER_TO_BE_SHIFTED = 5;
338
+ uint256 constant PAIRING_POINTS_SIZE = 8;
339
+
340
+ uint256 constant FIELD_ELEMENT_SIZE = 0x20;
341
+ uint256 constant GROUP_ELEMENT_SIZE = 0x40;
342
+
343
+ // Powers of alpha used to batch subrelations (alpha, alpha^2, ..., alpha^(NUM_SUBRELATIONS-1))
344
+ uint256 constant NUMBER_OF_ALPHAS = NUMBER_OF_SUBRELATIONS - 1;
345
+
346
+ // Must match UltraFlavor_Generated::EntityId order.
347
+ enum WIRE {
348
+ SIGMA_1,
349
+ SIGMA_2,
350
+ SIGMA_3,
351
+ SIGMA_4,
352
+ ID_1,
353
+ ID_2,
354
+ ID_3,
355
+ ID_4,
356
+ LAGRANGE_FIRST,
357
+ LAGRANGE_LAST,
358
+ Q_LOOKUP,
359
+ TABLE_1,
360
+ TABLE_2,
361
+ TABLE_3,
362
+ TABLE_4,
363
+ Q_M,
364
+ Q_R,
365
+ Q_O,
366
+ Q_C,
367
+ Q_L,
368
+ Q_4,
369
+ Q_ARITH,
370
+ Q_RANGE,
371
+ Q_ELLIPTIC,
372
+ Q_MEMORY,
373
+ Q_NNF,
374
+ Q_POSEIDON2_EXTERNAL,
375
+ Q_POSEIDON2_INTERNAL,
376
+ W_L,
377
+ W_R,
378
+ W_O,
379
+ W_4,
380
+ Z_PERM,
381
+ LOOKUP_INVERSES,
382
+ LOOKUP_READ_COUNTS,
383
+ LOOKUP_READ_TAGS,
384
+ W_L_SHIFT,
385
+ W_R_SHIFT,
386
+ W_O_SHIFT,
387
+ W_4_SHIFT,
388
+ Z_PERM_SHIFT
389
+ }
390
+
391
+ library Honk {
392
+ struct G1Point {
393
+ uint256 x;
394
+ uint256 y;
395
+ }
396
+
397
+ struct VerificationKey {
398
+ // Misc Params
399
+ uint256 circuitSize;
400
+ uint256 logCircuitSize;
401
+ uint256 publicInputsSize;
402
+ // Selectors
403
+ G1Point qm;
404
+ G1Point qc;
405
+ G1Point ql;
406
+ G1Point qr;
407
+ G1Point qo;
408
+ G1Point q4;
409
+ G1Point qLookup; // Lookup
410
+ G1Point qArith; // Arithmetic widget
411
+ G1Point qDeltaRange; // Delta Range sort
412
+ G1Point qMemory; // Memory
413
+ G1Point qNnf; // Non-native Field
414
+ G1Point qElliptic; // Auxillary
415
+ G1Point qPoseidon2External;
416
+ G1Point qPoseidon2Internal;
417
+ // Copy constraints
418
+ G1Point s1;
419
+ G1Point s2;
420
+ G1Point s3;
421
+ G1Point s4;
422
+ // Copy identity
423
+ G1Point id1;
424
+ G1Point id2;
425
+ G1Point id3;
426
+ G1Point id4;
427
+ // Precomputed lookup table
428
+ G1Point t1;
429
+ G1Point t2;
430
+ G1Point t3;
431
+ G1Point t4;
432
+ // Fixed first and last
433
+ G1Point lagrangeFirst;
434
+ G1Point lagrangeLast;
435
+ }
436
+
437
+ struct RelationParameters {
438
+ // challenges
439
+ Fr eta;
440
+ Fr beta;
441
+ Fr gamma;
442
+ // derived
443
+ Fr publicInputsDelta;
444
+ }
445
+
446
+ struct Proof {
447
+ // Pairing point object
448
+ Fr[PAIRING_POINTS_SIZE] pairingPointObject;
449
+ // Free wires
450
+ G1Point w1;
451
+ G1Point w2;
452
+ G1Point w3;
453
+ G1Point w4;
454
+ // Lookup helpers - Permutations
455
+ G1Point zPerm;
456
+ // Lookup helpers - logup
457
+ G1Point lookupReadCounts;
458
+ G1Point lookupReadTags;
459
+ G1Point lookupInverses;
460
+ // Sumcheck
461
+ Fr[BATCHED_RELATION_PARTIAL_LENGTH][CONST_PROOF_SIZE_LOG_N] sumcheckUnivariates;
462
+ Fr[NUMBER_OF_ENTITIES] sumcheckEvaluations;
463
+ // Shplemini
464
+ G1Point[CONST_PROOF_SIZE_LOG_N - 1] geminiFoldComms;
465
+ Fr[CONST_PROOF_SIZE_LOG_N] geminiAEvaluations;
466
+ G1Point shplonkQ;
467
+ G1Point kzgQuotient;
468
+ }
469
+
470
+ /// forge-lint: disable-next-item(pascal-case-struct)
471
+ struct ZKProof {
472
+ // Pairing point object
473
+ Fr[PAIRING_POINTS_SIZE] pairingPointObject;
474
+ // ZK: Gemini masking polynomial commitment (sent first, right after public inputs)
475
+ G1Point geminiMaskingPoly;
476
+ // Commitments to wire polynomials
477
+ G1Point w1;
478
+ G1Point w2;
479
+ G1Point w3;
480
+ G1Point w4;
481
+ // Commitments to logup witness polynomials
482
+ G1Point lookupReadCounts;
483
+ G1Point lookupReadTags;
484
+ G1Point lookupInverses;
485
+ // Commitment to grand permutation polynomial
486
+ G1Point zPerm;
487
+ G1Point[3] libraCommitments;
488
+ // Sumcheck
489
+ Fr libraSum;
490
+ Fr[ZK_BATCHED_RELATION_PARTIAL_LENGTH][CONST_PROOF_SIZE_LOG_N] sumcheckUnivariates;
491
+ Fr libraEvaluation;
492
+ Fr[NUMBER_OF_ENTITIES_ZK] sumcheckEvaluations; // Includes gemini_masking_poly eval at index 0 (first position)
493
+ // Shplemini
494
+ G1Point[CONST_PROOF_SIZE_LOG_N - 1] geminiFoldComms;
495
+ Fr[CONST_PROOF_SIZE_LOG_N] geminiAEvaluations;
496
+ Fr[4] libraPolyEvals;
497
+ G1Point shplonkQ;
498
+ G1Point kzgQuotient;
499
+ }
500
+ }
501
+
502
+ // ZKTranscript library to generate fiat shamir challenges, the ZK transcript only differest
503
+ /// forge-lint: disable-next-item(pascal-case-struct)
504
+ struct ZKTranscript {
505
+ // Oink
506
+ Honk.RelationParameters relationParameters;
507
+ Fr[NUMBER_OF_ALPHAS] alphas; // Powers of alpha: [alpha, alpha^2, ..., alpha^(NUM_SUBRELATIONS-1)]
508
+ Fr[CONST_PROOF_SIZE_LOG_N] gateChallenges;
509
+ // Sumcheck
510
+ Fr libraChallenge;
511
+ Fr[CONST_PROOF_SIZE_LOG_N] sumCheckUChallenges;
512
+ // Shplemini
513
+ Fr rho;
514
+ Fr geminiR;
515
+ Fr shplonkNu;
516
+ Fr shplonkZ;
517
+ // Derived
518
+ Fr publicInputsDelta;
519
+ }
520
+
521
+ library ZKTranscriptLib {
522
+ function generateTranscript(
523
+ Honk.ZKProof memory proof,
524
+ bytes32[] calldata publicInputs,
525
+ uint256 vkHash,
526
+ uint256 publicInputsSize,
527
+ uint256 logN
528
+ ) external pure returns (ZKTranscript memory t) {
529
+ Fr previousChallenge;
530
+ (t.relationParameters, previousChallenge) = generateRelationParametersChallenges(
531
+ proof,
532
+ publicInputs,
533
+ vkHash,
534
+ publicInputsSize,
535
+ previousChallenge
536
+ );
537
+
538
+ (t.alphas, previousChallenge) = generateAlphaChallenges(previousChallenge, proof);
539
+
540
+ (t.gateChallenges, previousChallenge) = generateGateChallenges(previousChallenge, logN);
541
+ (t.libraChallenge, previousChallenge) = generateLibraChallenge(previousChallenge, proof);
542
+ (t.sumCheckUChallenges, previousChallenge) = generateSumcheckChallenges(proof, previousChallenge, logN);
543
+
544
+ (t.rho, previousChallenge) = generateRhoChallenge(proof, previousChallenge);
545
+
546
+ (t.geminiR, previousChallenge) = generateGeminiRChallenge(proof, previousChallenge, logN);
547
+
548
+ (t.shplonkNu, previousChallenge) = generateShplonkNuChallenge(proof, previousChallenge, logN);
549
+
550
+ (t.shplonkZ, previousChallenge) = generateShplonkZChallenge(proof, previousChallenge);
551
+ return t;
552
+ }
553
+
554
+ function splitChallenge(Fr challenge) internal pure returns (Fr first, Fr second) {
555
+ uint256 challengeU256 = uint256(Fr.unwrap(challenge));
556
+ // Split into two equal 127-bit chunks (254/2)
557
+ uint256 lo = challengeU256 & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; // 127 bits
558
+ uint256 hi = challengeU256 >> 127;
559
+ first = FrLib.from(lo);
560
+ second = FrLib.from(hi);
561
+ }
562
+
563
+ function generateRelationParametersChallenges(
564
+ Honk.ZKProof memory proof,
565
+ bytes32[] calldata publicInputs,
566
+ uint256 vkHash,
567
+ uint256 publicInputsSize,
568
+ Fr previousChallenge
569
+ ) internal pure returns (Honk.RelationParameters memory rp, Fr nextPreviousChallenge) {
570
+ (rp.eta, previousChallenge) = generateEtaChallenge(proof, publicInputs, vkHash, publicInputsSize);
571
+
572
+ (rp.beta, rp.gamma, nextPreviousChallenge) = generateBetaGammaChallenges(previousChallenge, proof);
573
+ }
574
+
575
+ function generateEtaChallenge(
576
+ Honk.ZKProof memory proof,
577
+ bytes32[] calldata publicInputs,
578
+ uint256 vkHash,
579
+ uint256 publicInputsSize
580
+ ) internal pure returns (Fr eta, Fr previousChallenge) {
581
+ // Size: 1 (vkHash) + publicInputsSize + 8 (geminiMask(2) + 3 wires(6))
582
+ bytes32[] memory round0 = new bytes32[](1 + publicInputsSize + 8);
583
+ round0[0] = bytes32(vkHash);
584
+
585
+ for (uint256 i = 0; i < publicInputsSize - PAIRING_POINTS_SIZE; i++) {
586
+ require(uint256(publicInputs[i]) < P, Errors.ValueGeFieldOrder());
587
+ round0[1 + i] = publicInputs[i];
588
+ }
589
+ for (uint256 i = 0; i < PAIRING_POINTS_SIZE; i++) {
590
+ round0[1 + publicInputsSize - PAIRING_POINTS_SIZE + i] = FrLib.toBytes32(proof.pairingPointObject[i]);
591
+ }
592
+
593
+ // For ZK flavors: hash the gemini masking poly commitment (sent right after public inputs)
594
+ round0[1 + publicInputsSize] = bytes32(proof.geminiMaskingPoly.x);
595
+ round0[1 + publicInputsSize + 1] = bytes32(proof.geminiMaskingPoly.y);
596
+
597
+ // Create the first challenge
598
+ // Note: w4 is added to the challenge later on
599
+ round0[1 + publicInputsSize + 2] = bytes32(proof.w1.x);
600
+ round0[1 + publicInputsSize + 3] = bytes32(proof.w1.y);
601
+ round0[1 + publicInputsSize + 4] = bytes32(proof.w2.x);
602
+ round0[1 + publicInputsSize + 5] = bytes32(proof.w2.y);
603
+ round0[1 + publicInputsSize + 6] = bytes32(proof.w3.x);
604
+ round0[1 + publicInputsSize + 7] = bytes32(proof.w3.y);
605
+
606
+ previousChallenge = FrLib.from(uint256(keccak256(abi.encodePacked(round0))) % P);
607
+ (eta, ) = splitChallenge(previousChallenge);
608
+ }
609
+
610
+ function generateBetaGammaChallenges(
611
+ Fr previousChallenge,
612
+ Honk.ZKProof memory proof
613
+ ) internal pure returns (Fr beta, Fr gamma, Fr nextPreviousChallenge) {
614
+ bytes32[7] memory round1;
615
+ round1[0] = FrLib.toBytes32(previousChallenge);
616
+ round1[1] = bytes32(proof.lookupReadCounts.x);
617
+ round1[2] = bytes32(proof.lookupReadCounts.y);
618
+ round1[3] = bytes32(proof.lookupReadTags.x);
619
+ round1[4] = bytes32(proof.lookupReadTags.y);
620
+ round1[5] = bytes32(proof.w4.x);
621
+ round1[6] = bytes32(proof.w4.y);
622
+
623
+ nextPreviousChallenge = FrLib.from(uint256(keccak256(abi.encodePacked(round1))) % P);
624
+ (beta, gamma) = splitChallenge(nextPreviousChallenge);
625
+ }
626
+
627
+ // Alpha challenges non-linearise the gate contributions
628
+ function generateAlphaChallenges(
629
+ Fr previousChallenge,
630
+ Honk.ZKProof memory proof
631
+ ) internal pure returns (Fr[NUMBER_OF_ALPHAS] memory alphas, Fr nextPreviousChallenge) {
632
+ // Generate the original sumcheck alpha 0 by hashing zPerm and zLookup
633
+ uint256[5] memory alpha0;
634
+ alpha0[0] = Fr.unwrap(previousChallenge);
635
+ alpha0[1] = proof.lookupInverses.x;
636
+ alpha0[2] = proof.lookupInverses.y;
637
+ alpha0[3] = proof.zPerm.x;
638
+ alpha0[4] = proof.zPerm.y;
639
+
640
+ nextPreviousChallenge = FrLib.from(uint256(keccak256(abi.encodePacked(alpha0))) % P);
641
+ Fr alpha;
642
+ (alpha, ) = splitChallenge(nextPreviousChallenge);
643
+
644
+ // Compute powers of alpha for batching subrelations
645
+ alphas[0] = alpha;
646
+ for (uint256 i = 1; i < NUMBER_OF_ALPHAS; i++) {
647
+ alphas[i] = alphas[i - 1] * alpha;
648
+ }
649
+ }
650
+
651
+ function generateGateChallenges(
652
+ Fr previousChallenge,
653
+ uint256 logN
654
+ ) internal pure returns (Fr[CONST_PROOF_SIZE_LOG_N] memory gateChallenges, Fr nextPreviousChallenge) {
655
+ previousChallenge = FrLib.from(uint256(keccak256(abi.encodePacked(Fr.unwrap(previousChallenge)))) % P);
656
+ (gateChallenges[0], ) = splitChallenge(previousChallenge);
657
+ for (uint256 i = 1; i < logN; i++) {
658
+ gateChallenges[i] = gateChallenges[i - 1] * gateChallenges[i - 1];
659
+ }
660
+ nextPreviousChallenge = previousChallenge;
661
+ }
662
+
663
+ function generateLibraChallenge(
664
+ Fr previousChallenge,
665
+ Honk.ZKProof memory proof
666
+ ) internal pure returns (Fr libraChallenge, Fr nextPreviousChallenge) {
667
+ // 2 comm, 1 sum, 1 challenge
668
+ uint256[4] memory challengeData;
669
+ challengeData[0] = Fr.unwrap(previousChallenge);
670
+ challengeData[1] = proof.libraCommitments[0].x;
671
+ challengeData[2] = proof.libraCommitments[0].y;
672
+ challengeData[3] = Fr.unwrap(proof.libraSum);
673
+ nextPreviousChallenge = FrLib.from(uint256(keccak256(abi.encodePacked(challengeData))) % P);
674
+ (libraChallenge, ) = splitChallenge(nextPreviousChallenge);
675
+ }
676
+
677
+ function generateSumcheckChallenges(
678
+ Honk.ZKProof memory proof,
679
+ Fr prevChallenge,
680
+ uint256 logN
681
+ ) internal pure returns (Fr[CONST_PROOF_SIZE_LOG_N] memory sumcheckChallenges, Fr nextPreviousChallenge) {
682
+ for (uint256 i = 0; i < logN; i++) {
683
+ Fr[ZK_BATCHED_RELATION_PARTIAL_LENGTH + 1] memory univariateChal;
684
+ univariateChal[0] = prevChallenge;
685
+
686
+ for (uint256 j = 0; j < ZK_BATCHED_RELATION_PARTIAL_LENGTH; j++) {
687
+ univariateChal[j + 1] = proof.sumcheckUnivariates[i][j];
688
+ }
689
+ prevChallenge = FrLib.from(uint256(keccak256(abi.encodePacked(univariateChal))) % P);
690
+
691
+ (sumcheckChallenges[i], ) = splitChallenge(prevChallenge);
692
+ }
693
+ nextPreviousChallenge = prevChallenge;
694
+ }
695
+
696
+ // We add Libra claimed eval + 2 libra commitments (grand_sum, quotient)
697
+ function generateRhoChallenge(Honk.ZKProof memory proof, Fr prevChallenge) internal pure returns (Fr rho, Fr nextPreviousChallenge) {
698
+ uint256[NUMBER_OF_ENTITIES_ZK + 6] memory rhoChallengeElements;
699
+ rhoChallengeElements[0] = Fr.unwrap(prevChallenge);
700
+ uint256 i;
701
+ for (i = 1; i <= NUMBER_OF_ENTITIES_ZK; i++) {
702
+ rhoChallengeElements[i] = Fr.unwrap(proof.sumcheckEvaluations[i - 1]);
703
+ }
704
+ rhoChallengeElements[i] = Fr.unwrap(proof.libraEvaluation);
705
+ i += 1;
706
+ rhoChallengeElements[i] = proof.libraCommitments[1].x;
707
+ rhoChallengeElements[i + 1] = proof.libraCommitments[1].y;
708
+ i += 2;
709
+ rhoChallengeElements[i] = proof.libraCommitments[2].x;
710
+ rhoChallengeElements[i + 1] = proof.libraCommitments[2].y;
711
+
712
+ nextPreviousChallenge = FrLib.from(uint256(keccak256(abi.encodePacked(rhoChallengeElements))) % P);
713
+ (rho, ) = splitChallenge(nextPreviousChallenge);
714
+ }
715
+
716
+ function generateGeminiRChallenge(
717
+ Honk.ZKProof memory proof,
718
+ Fr prevChallenge,
719
+ uint256 logN
720
+ ) internal pure returns (Fr geminiR, Fr nextPreviousChallenge) {
721
+ uint256[] memory gR = new uint256[]((logN - 1) * 2 + 1);
722
+ gR[0] = Fr.unwrap(prevChallenge);
723
+
724
+ for (uint256 i = 0; i < logN - 1; i++) {
725
+ gR[1 + i * 2] = proof.geminiFoldComms[i].x;
726
+ gR[2 + i * 2] = proof.geminiFoldComms[i].y;
727
+ }
728
+
729
+ nextPreviousChallenge = FrLib.from(uint256(keccak256(abi.encodePacked(gR))) % P);
730
+
731
+ (geminiR, ) = splitChallenge(nextPreviousChallenge);
732
+ }
733
+
734
+ function generateShplonkNuChallenge(
735
+ Honk.ZKProof memory proof,
736
+ Fr prevChallenge,
737
+ uint256 logN
738
+ ) internal pure returns (Fr shplonkNu, Fr nextPreviousChallenge) {
739
+ uint256[] memory shplonkNuChallengeElements = new uint256[](logN + 1 + 4);
740
+ shplonkNuChallengeElements[0] = Fr.unwrap(prevChallenge);
741
+
742
+ for (uint256 i = 1; i <= logN; i++) {
743
+ shplonkNuChallengeElements[i] = Fr.unwrap(proof.geminiAEvaluations[i - 1]);
744
+ }
745
+
746
+ uint256 libraIdx = 0;
747
+ for (uint256 i = logN + 1; i <= logN + 4; i++) {
748
+ shplonkNuChallengeElements[i] = Fr.unwrap(proof.libraPolyEvals[libraIdx]);
749
+ libraIdx++;
750
+ }
751
+
752
+ nextPreviousChallenge = FrLib.from(uint256(keccak256(abi.encodePacked(shplonkNuChallengeElements))) % P);
753
+ (shplonkNu, ) = splitChallenge(nextPreviousChallenge);
754
+ }
755
+
756
+ function generateShplonkZChallenge(
757
+ Honk.ZKProof memory proof,
758
+ Fr prevChallenge
759
+ ) internal pure returns (Fr shplonkZ, Fr nextPreviousChallenge) {
760
+ uint256[3] memory shplonkZChallengeElements;
761
+ shplonkZChallengeElements[0] = Fr.unwrap(prevChallenge);
762
+
763
+ shplonkZChallengeElements[1] = proof.shplonkQ.x;
764
+ shplonkZChallengeElements[2] = proof.shplonkQ.y;
765
+
766
+ nextPreviousChallenge = FrLib.from(uint256(keccak256(abi.encodePacked(shplonkZChallengeElements))) % P);
767
+ (shplonkZ, ) = splitChallenge(nextPreviousChallenge);
768
+ }
769
+
770
+ function loadProof(bytes calldata proof, uint256 logN) internal pure returns (Honk.ZKProof memory p) {
771
+ uint256 boundary = 0x0;
772
+
773
+ // Pairing point object
774
+ for (uint256 i = 0; i < PAIRING_POINTS_SIZE; i++) {
775
+ uint256 limb = uint256(bytes32(proof[boundary:boundary + FIELD_ELEMENT_SIZE]));
776
+ // lo limbs (even index) < 2^136, hi limbs (odd index) < 2^120
777
+ require(limb < 2 ** (i % 2 == 0 ? 136 : 120), Errors.ValueGeLimbMax());
778
+ p.pairingPointObject[i] = FrLib.from(limb);
779
+ boundary += FIELD_ELEMENT_SIZE;
780
+ }
781
+
782
+ // Gemini masking polynomial commitment (sent first in ZK flavors, right after pairing points)
783
+ p.geminiMaskingPoly = bytesToG1Point(proof[boundary:boundary + GROUP_ELEMENT_SIZE]);
784
+ boundary += GROUP_ELEMENT_SIZE;
785
+
786
+ // Commitments
787
+ p.w1 = bytesToG1Point(proof[boundary:boundary + GROUP_ELEMENT_SIZE]);
788
+ boundary += GROUP_ELEMENT_SIZE;
789
+ p.w2 = bytesToG1Point(proof[boundary:boundary + GROUP_ELEMENT_SIZE]);
790
+ boundary += GROUP_ELEMENT_SIZE;
791
+ p.w3 = bytesToG1Point(proof[boundary:boundary + GROUP_ELEMENT_SIZE]);
792
+ boundary += GROUP_ELEMENT_SIZE;
793
+
794
+ // Lookup / Permutation Helper Commitments
795
+ p.lookupReadCounts = bytesToG1Point(proof[boundary:boundary + GROUP_ELEMENT_SIZE]);
796
+ boundary += GROUP_ELEMENT_SIZE;
797
+ p.lookupReadTags = bytesToG1Point(proof[boundary:boundary + GROUP_ELEMENT_SIZE]);
798
+ boundary += GROUP_ELEMENT_SIZE;
799
+ p.w4 = bytesToG1Point(proof[boundary:boundary + GROUP_ELEMENT_SIZE]);
800
+ boundary += GROUP_ELEMENT_SIZE;
801
+ p.lookupInverses = bytesToG1Point(proof[boundary:boundary + GROUP_ELEMENT_SIZE]);
802
+ boundary += GROUP_ELEMENT_SIZE;
803
+ p.zPerm = bytesToG1Point(proof[boundary:boundary + GROUP_ELEMENT_SIZE]);
804
+ boundary += GROUP_ELEMENT_SIZE;
805
+ p.libraCommitments[0] = bytesToG1Point(proof[boundary:boundary + GROUP_ELEMENT_SIZE]);
806
+ boundary += GROUP_ELEMENT_SIZE;
807
+
808
+ p.libraSum = bytesToFr(proof[boundary:boundary + FIELD_ELEMENT_SIZE]);
809
+ boundary += FIELD_ELEMENT_SIZE;
810
+ // Sumcheck univariates
811
+ for (uint256 i = 0; i < logN; i++) {
812
+ for (uint256 j = 0; j < ZK_BATCHED_RELATION_PARTIAL_LENGTH; j++) {
813
+ p.sumcheckUnivariates[i][j] = bytesToFr(proof[boundary:boundary + FIELD_ELEMENT_SIZE]);
814
+ boundary += FIELD_ELEMENT_SIZE;
815
+ }
816
+ }
817
+
818
+ // Sumcheck evaluations (includes gemini_masking_poly eval at index 0 for ZK flavors)
819
+ for (uint256 i = 0; i < NUMBER_OF_ENTITIES_ZK; i++) {
820
+ p.sumcheckEvaluations[i] = bytesToFr(proof[boundary:boundary + FIELD_ELEMENT_SIZE]);
821
+ boundary += FIELD_ELEMENT_SIZE;
822
+ }
823
+
824
+ p.libraEvaluation = bytesToFr(proof[boundary:boundary + FIELD_ELEMENT_SIZE]);
825
+ boundary += FIELD_ELEMENT_SIZE;
826
+
827
+ p.libraCommitments[1] = bytesToG1Point(proof[boundary:boundary + GROUP_ELEMENT_SIZE]);
828
+ boundary += GROUP_ELEMENT_SIZE;
829
+ p.libraCommitments[2] = bytesToG1Point(proof[boundary:boundary + GROUP_ELEMENT_SIZE]);
830
+ boundary += GROUP_ELEMENT_SIZE;
831
+
832
+ // Gemini
833
+ // Read gemini fold univariates
834
+ for (uint256 i = 0; i < logN - 1; i++) {
835
+ p.geminiFoldComms[i] = bytesToG1Point(proof[boundary:boundary + GROUP_ELEMENT_SIZE]);
836
+ boundary += GROUP_ELEMENT_SIZE;
837
+ }
838
+
839
+ // Read gemini a evaluations
840
+ for (uint256 i = 0; i < logN; i++) {
841
+ p.geminiAEvaluations[i] = bytesToFr(proof[boundary:boundary + FIELD_ELEMENT_SIZE]);
842
+ boundary += FIELD_ELEMENT_SIZE;
843
+ }
844
+
845
+ for (uint256 i = 0; i < 4; i++) {
846
+ p.libraPolyEvals[i] = bytesToFr(proof[boundary:boundary + FIELD_ELEMENT_SIZE]);
847
+ boundary += FIELD_ELEMENT_SIZE;
848
+ }
849
+
850
+ // Shplonk
851
+ p.shplonkQ = bytesToG1Point(proof[boundary:boundary + GROUP_ELEMENT_SIZE]);
852
+ boundary += GROUP_ELEMENT_SIZE;
853
+ // KZG
854
+ p.kzgQuotient = bytesToG1Point(proof[boundary:boundary + GROUP_ELEMENT_SIZE]);
855
+ }
856
+ }
857
+
858
+ library RelationsLib {
859
+ struct EllipticParams {
860
+ // Points
861
+ Fr x_1;
862
+ Fr y_1;
863
+ Fr x_2;
864
+ Fr y_2;
865
+ Fr y_3;
866
+ Fr x_3;
867
+ // push accumulators into memory
868
+ Fr x_double_identity;
869
+ }
870
+
871
+ // Parameters used within the Memory Relation
872
+ // A struct is used to work around stack too deep. This relation has alot of variables
873
+ struct MemParams {
874
+ Fr memory_record_check;
875
+ Fr partial_record_check;
876
+ Fr next_gate_access_type;
877
+ Fr record_delta;
878
+ Fr index_delta;
879
+ Fr adjacent_values_match_if_adjacent_indices_match;
880
+ Fr adjacent_values_match_if_adjacent_indices_match_and_next_access_is_a_read_operation;
881
+ Fr access_check;
882
+ Fr next_gate_access_type_is_boolean;
883
+ Fr ROM_consistency_check_identity;
884
+ Fr RAM_consistency_check_identity;
885
+ Fr timestamp_delta;
886
+ Fr RAM_timestamp_check_identity;
887
+ Fr memory_identity;
888
+ Fr index_is_monotonically_increasing;
889
+ }
890
+
891
+ // Parameters used within the Non-Native Field Relation
892
+ // A struct is used to work around stack too deep. This relation has alot of variables
893
+ struct NnfParams {
894
+ Fr limb_subproduct;
895
+ Fr non_native_field_gate_1;
896
+ Fr non_native_field_gate_2;
897
+ Fr non_native_field_gate_3;
898
+ Fr limb_accumulator_1;
899
+ Fr limb_accumulator_2;
900
+ Fr nnf_identity;
901
+ }
902
+
903
+ struct PoseidonExternalParams {
904
+ Fr s1;
905
+ Fr s2;
906
+ Fr s3;
907
+ Fr s4;
908
+ Fr u1;
909
+ Fr u2;
910
+ Fr u3;
911
+ Fr u4;
912
+ Fr t0;
913
+ Fr t1;
914
+ Fr t2;
915
+ Fr t3;
916
+ Fr v1;
917
+ Fr v2;
918
+ Fr v3;
919
+ Fr v4;
920
+ Fr q_pos_by_scaling;
921
+ }
922
+
923
+ struct PoseidonInternalParams {
924
+ Fr u1;
925
+ Fr u2;
926
+ Fr u3;
927
+ Fr u4;
928
+ Fr u_sum;
929
+ Fr v1;
930
+ Fr v2;
931
+ Fr v3;
932
+ Fr v4;
933
+ Fr s1;
934
+ Fr q_pos_by_scaling;
935
+ }
936
+
937
+ Fr internal constant GRUMPKIN_CURVE_B_PARAMETER_NEGATED = Fr.wrap(17); // -(-17)
938
+ uint256 internal constant NEG_HALF_MODULO_P = 0x183227397098d014dc2822db40c0ac2e9419f4243cdcb848a1f0fac9f8000000;
939
+
940
+ // Constants for the Non-native Field relation
941
+ Fr internal constant LIMB_SIZE = Fr.wrap(uint256(1) << 68);
942
+ Fr internal constant SUBLIMB_SHIFT = Fr.wrap(uint256(1) << 14);
943
+
944
+ function accumulateRelationEvaluations(
945
+ Fr[NUMBER_OF_ENTITIES] memory purportedEvaluations,
946
+ Honk.RelationParameters memory rp,
947
+ Fr[NUMBER_OF_ALPHAS] memory subrelationChallenges,
948
+ Fr powPartialEval
949
+ ) external pure returns (Fr accumulator) {
950
+ Fr[NUMBER_OF_SUBRELATIONS] memory evaluations;
951
+
952
+ // Accumulate all relations in Ultra Honk - each with varying number of subrelations
953
+ accumulateArithmeticRelation(purportedEvaluations, evaluations, powPartialEval);
954
+ accumulatePermutationRelation(purportedEvaluations, rp, evaluations, powPartialEval);
955
+ accumulateLogDerivativeLookupRelation(purportedEvaluations, rp, evaluations, powPartialEval);
956
+ accumulateDeltaRangeRelation(purportedEvaluations, evaluations, powPartialEval);
957
+ accumulateEllipticRelation(purportedEvaluations, evaluations, powPartialEval);
958
+ accumulateMemoryRelation(purportedEvaluations, rp, evaluations, powPartialEval);
959
+ accumulateNnfRelation(purportedEvaluations, evaluations, powPartialEval);
960
+ accumulatePoseidonExternalRelation(purportedEvaluations, evaluations, powPartialEval);
961
+ accumulatePoseidonInternalRelation(purportedEvaluations, evaluations, powPartialEval);
962
+
963
+ // batch the subrelations with the precomputed alpha powers to obtain the full honk relation
964
+ accumulator = scaleAndBatchSubrelations(evaluations, subrelationChallenges);
965
+ }
966
+
967
+ /**
968
+ * Aesthetic helper function that is used to index by enum into proof.sumcheckEvaluations, it avoids
969
+ * the relation checking code being cluttered with uint256 type casting, which is often a different colour in code
970
+ * editors, and thus is noisy.
971
+ */
972
+ function wire(Fr[NUMBER_OF_ENTITIES] memory p, WIRE _wire) internal pure returns (Fr) {
973
+ return p[uint256(_wire)];
974
+ }
975
+
976
+ /**
977
+ * Ultra Arithmetic Relation
978
+ *
979
+ */
980
+ function accumulateArithmeticRelation(
981
+ Fr[NUMBER_OF_ENTITIES] memory p,
982
+ Fr[NUMBER_OF_SUBRELATIONS] memory evals,
983
+ Fr domainSep
984
+ ) internal pure {
985
+ // Relation 0
986
+ Fr q_arith = wire(p, WIRE.Q_ARITH);
987
+ {
988
+ Fr neg_half = Fr.wrap(NEG_HALF_MODULO_P);
989
+
990
+ Fr accum = (q_arith - Fr.wrap(3)) * (wire(p, WIRE.Q_M) * wire(p, WIRE.W_R) * wire(p, WIRE.W_L)) * neg_half;
991
+ accum =
992
+ accum +
993
+ (wire(p, WIRE.Q_L) * wire(p, WIRE.W_L)) +
994
+ (wire(p, WIRE.Q_R) * wire(p, WIRE.W_R)) +
995
+ (wire(p, WIRE.Q_O) * wire(p, WIRE.W_O)) +
996
+ (wire(p, WIRE.Q_4) * wire(p, WIRE.W_4)) +
997
+ wire(p, WIRE.Q_C);
998
+ accum = accum + (q_arith - ONE) * wire(p, WIRE.W_4_SHIFT);
999
+ accum = accum * q_arith;
1000
+ accum = accum * domainSep;
1001
+ evals[6] = accum;
1002
+ }
1003
+
1004
+ // Relation 1
1005
+ {
1006
+ Fr accum = wire(p, WIRE.W_L) + wire(p, WIRE.W_4) - wire(p, WIRE.W_L_SHIFT) + wire(p, WIRE.Q_M);
1007
+ accum = accum * (q_arith - Fr.wrap(2));
1008
+ accum = accum * (q_arith - ONE);
1009
+ accum = accum * q_arith;
1010
+ accum = accum * domainSep;
1011
+ evals[7] = accum;
1012
+ }
1013
+ }
1014
+
1015
+ function accumulatePermutationRelation(
1016
+ Fr[NUMBER_OF_ENTITIES] memory p,
1017
+ Honk.RelationParameters memory rp,
1018
+ Fr[NUMBER_OF_SUBRELATIONS] memory evals,
1019
+ Fr domainSep
1020
+ ) internal pure {
1021
+ Fr grand_product_numerator;
1022
+ Fr grand_product_denominator;
1023
+
1024
+ {
1025
+ Fr num = wire(p, WIRE.W_L) + wire(p, WIRE.ID_1) * rp.beta + rp.gamma;
1026
+ num = num * (wire(p, WIRE.W_R) + wire(p, WIRE.ID_2) * rp.beta + rp.gamma);
1027
+ num = num * (wire(p, WIRE.W_O) + wire(p, WIRE.ID_3) * rp.beta + rp.gamma);
1028
+ num = num * (wire(p, WIRE.W_4) + wire(p, WIRE.ID_4) * rp.beta + rp.gamma);
1029
+
1030
+ grand_product_numerator = num;
1031
+ }
1032
+ {
1033
+ Fr den = wire(p, WIRE.W_L) + wire(p, WIRE.SIGMA_1) * rp.beta + rp.gamma;
1034
+ den = den * (wire(p, WIRE.W_R) + wire(p, WIRE.SIGMA_2) * rp.beta + rp.gamma);
1035
+ den = den * (wire(p, WIRE.W_O) + wire(p, WIRE.SIGMA_3) * rp.beta + rp.gamma);
1036
+ den = den * (wire(p, WIRE.W_4) + wire(p, WIRE.SIGMA_4) * rp.beta + rp.gamma);
1037
+
1038
+ grand_product_denominator = den;
1039
+ }
1040
+
1041
+ // Contribution 2
1042
+ {
1043
+ Fr acc = (wire(p, WIRE.Z_PERM) + wire(p, WIRE.LAGRANGE_FIRST)) * grand_product_numerator;
1044
+
1045
+ acc = acc - ((wire(p, WIRE.Z_PERM_SHIFT) + (wire(p, WIRE.LAGRANGE_LAST) * rp.publicInputsDelta)) * grand_product_denominator);
1046
+ acc = acc * domainSep;
1047
+ evals[0] = acc;
1048
+ }
1049
+
1050
+ // Contribution 3
1051
+ {
1052
+ Fr acc = (wire(p, WIRE.LAGRANGE_LAST) * wire(p, WIRE.Z_PERM_SHIFT)) * domainSep;
1053
+ evals[1] = acc;
1054
+ }
1055
+
1056
+ // Contribution 4: z_perm initialization check (lagrange_first * z_perm = 0)
1057
+ {
1058
+ Fr acc = (wire(p, WIRE.LAGRANGE_FIRST) * wire(p, WIRE.Z_PERM)) * domainSep;
1059
+ evals[2] = acc;
1060
+ }
1061
+ }
1062
+
1063
+ function accumulateLogDerivativeLookupRelation(
1064
+ Fr[NUMBER_OF_ENTITIES] memory p,
1065
+ Honk.RelationParameters memory rp,
1066
+ Fr[NUMBER_OF_SUBRELATIONS] memory evals,
1067
+ Fr domainSep
1068
+ ) internal pure {
1069
+ Fr table_term;
1070
+ Fr lookup_term;
1071
+
1072
+ // Calculate the write term (the table accumulation)
1073
+ // table_term = table_1 + γ + table_2 * β + table_3 * β² + table_4 * β³
1074
+ {
1075
+ Fr beta_sqr = rp.beta * rp.beta;
1076
+ table_term =
1077
+ wire(p, WIRE.TABLE_1) +
1078
+ rp.gamma +
1079
+ (wire(p, WIRE.TABLE_2) * rp.beta) +
1080
+ (wire(p, WIRE.TABLE_3) * beta_sqr) +
1081
+ (wire(p, WIRE.TABLE_4) * beta_sqr * rp.beta);
1082
+ }
1083
+
1084
+ // Calculate the read term
1085
+ // lookup_term = derived_entry_1 + γ + derived_entry_2 * β + derived_entry_3 * β² + q_index * β³
1086
+ {
1087
+ Fr beta_sqr = rp.beta * rp.beta;
1088
+ Fr derived_entry_1 = wire(p, WIRE.W_L) + rp.gamma + (wire(p, WIRE.Q_R) * wire(p, WIRE.W_L_SHIFT));
1089
+ Fr derived_entry_2 = wire(p, WIRE.W_R) + wire(p, WIRE.Q_M) * wire(p, WIRE.W_R_SHIFT);
1090
+ Fr derived_entry_3 = wire(p, WIRE.W_O) + wire(p, WIRE.Q_C) * wire(p, WIRE.W_O_SHIFT);
1091
+
1092
+ lookup_term = derived_entry_1 + (derived_entry_2 * rp.beta) + (derived_entry_3 * beta_sqr) + (wire(p, WIRE.Q_O) * beta_sqr * rp.beta);
1093
+ }
1094
+
1095
+ Fr lookup_inverse = wire(p, WIRE.LOOKUP_INVERSES) * table_term;
1096
+ Fr table_inverse = wire(p, WIRE.LOOKUP_INVERSES) * lookup_term;
1097
+
1098
+ Fr inverse_exists_xor = wire(p, WIRE.LOOKUP_READ_TAGS) +
1099
+ wire(p, WIRE.Q_LOOKUP) -
1100
+ (wire(p, WIRE.LOOKUP_READ_TAGS) * wire(p, WIRE.Q_LOOKUP));
1101
+
1102
+ // Inverse calculated correctly relation
1103
+ Fr accumulatorNone = lookup_term * table_term * wire(p, WIRE.LOOKUP_INVERSES) - inverse_exists_xor;
1104
+ accumulatorNone = accumulatorNone * domainSep;
1105
+
1106
+ // Inverse
1107
+ Fr accumulatorOne = wire(p, WIRE.Q_LOOKUP) * lookup_inverse - wire(p, WIRE.LOOKUP_READ_COUNTS) * table_inverse;
1108
+
1109
+ Fr read_tag = wire(p, WIRE.LOOKUP_READ_TAGS);
1110
+
1111
+ Fr read_tag_boolean_relation = read_tag * read_tag - read_tag;
1112
+
1113
+ evals[3] = accumulatorNone;
1114
+ evals[4] = accumulatorOne;
1115
+ evals[5] = read_tag_boolean_relation * domainSep;
1116
+ }
1117
+
1118
+ function accumulateDeltaRangeRelation(
1119
+ Fr[NUMBER_OF_ENTITIES] memory p,
1120
+ Fr[NUMBER_OF_SUBRELATIONS] memory evals,
1121
+ Fr domainSep
1122
+ ) internal pure {
1123
+ Fr minus_one = ZERO - ONE;
1124
+ Fr minus_two = ZERO - Fr.wrap(2);
1125
+ Fr minus_three = ZERO - Fr.wrap(3);
1126
+
1127
+ // Compute wire differences
1128
+ Fr delta_1 = wire(p, WIRE.W_R) - wire(p, WIRE.W_L);
1129
+ Fr delta_2 = wire(p, WIRE.W_O) - wire(p, WIRE.W_R);
1130
+ Fr delta_3 = wire(p, WIRE.W_4) - wire(p, WIRE.W_O);
1131
+ Fr delta_4 = wire(p, WIRE.W_L_SHIFT) - wire(p, WIRE.W_4);
1132
+
1133
+ // Contribution 6
1134
+ {
1135
+ Fr acc = delta_1;
1136
+ acc = acc * (delta_1 + minus_one);
1137
+ acc = acc * (delta_1 + minus_two);
1138
+ acc = acc * (delta_1 + minus_three);
1139
+ acc = acc * wire(p, WIRE.Q_RANGE);
1140
+ acc = acc * domainSep;
1141
+ evals[8] = acc;
1142
+ }
1143
+
1144
+ // Contribution 7
1145
+ {
1146
+ Fr acc = delta_2;
1147
+ acc = acc * (delta_2 + minus_one);
1148
+ acc = acc * (delta_2 + minus_two);
1149
+ acc = acc * (delta_2 + minus_three);
1150
+ acc = acc * wire(p, WIRE.Q_RANGE);
1151
+ acc = acc * domainSep;
1152
+ evals[9] = acc;
1153
+ }
1154
+
1155
+ // Contribution 8
1156
+ {
1157
+ Fr acc = delta_3;
1158
+ acc = acc * (delta_3 + minus_one);
1159
+ acc = acc * (delta_3 + minus_two);
1160
+ acc = acc * (delta_3 + minus_three);
1161
+ acc = acc * wire(p, WIRE.Q_RANGE);
1162
+ acc = acc * domainSep;
1163
+ evals[10] = acc;
1164
+ }
1165
+
1166
+ // Contribution 9
1167
+ {
1168
+ Fr acc = delta_4;
1169
+ acc = acc * (delta_4 + minus_one);
1170
+ acc = acc * (delta_4 + minus_two);
1171
+ acc = acc * (delta_4 + minus_three);
1172
+ acc = acc * wire(p, WIRE.Q_RANGE);
1173
+ acc = acc * domainSep;
1174
+ evals[11] = acc;
1175
+ }
1176
+ }
1177
+
1178
+ function accumulateEllipticRelation(
1179
+ Fr[NUMBER_OF_ENTITIES] memory p,
1180
+ Fr[NUMBER_OF_SUBRELATIONS] memory evals,
1181
+ Fr domainSep
1182
+ ) internal pure {
1183
+ EllipticParams memory ep;
1184
+ ep.x_1 = wire(p, WIRE.W_R);
1185
+ ep.y_1 = wire(p, WIRE.W_O);
1186
+
1187
+ ep.x_2 = wire(p, WIRE.W_L_SHIFT);
1188
+ ep.y_2 = wire(p, WIRE.W_4_SHIFT);
1189
+ ep.y_3 = wire(p, WIRE.W_O_SHIFT);
1190
+ ep.x_3 = wire(p, WIRE.W_R_SHIFT);
1191
+
1192
+ Fr q_sign = wire(p, WIRE.Q_L);
1193
+ Fr q_is_double = wire(p, WIRE.Q_M);
1194
+
1195
+ // Contribution 10 point addition, x-coordinate check
1196
+ // q_elliptic * (x3 + x2 + x1)(x2 - x1)(x2 - x1) - y2^2 - y1^2 + 2(y2y1)*q_sign = 0
1197
+ Fr x_diff = (ep.x_2 - ep.x_1);
1198
+ Fr y1_sqr = (ep.y_1 * ep.y_1);
1199
+ {
1200
+ // Move to top
1201
+ Fr partialEval = domainSep;
1202
+
1203
+ Fr y2_sqr = (ep.y_2 * ep.y_2);
1204
+ Fr y1y2 = ep.y_1 * ep.y_2 * q_sign;
1205
+ Fr x_add_identity = (ep.x_3 + ep.x_2 + ep.x_1);
1206
+ x_add_identity = x_add_identity * x_diff * x_diff;
1207
+ x_add_identity = x_add_identity - y2_sqr - y1_sqr + y1y2 + y1y2;
1208
+
1209
+ evals[12] = x_add_identity * partialEval * wire(p, WIRE.Q_ELLIPTIC) * (ONE - q_is_double);
1210
+ }
1211
+
1212
+ // Contribution 11 point addition, x-coordinate check
1213
+ // q_elliptic * (q_sign * y1 + y3)(x2 - x1) + (x3 - x1)(y2 - q_sign * y1) = 0
1214
+ {
1215
+ Fr y1_plus_y3 = ep.y_1 + ep.y_3;
1216
+ Fr y_diff = ep.y_2 * q_sign - ep.y_1;
1217
+ Fr y_add_identity = y1_plus_y3 * x_diff + (ep.x_3 - ep.x_1) * y_diff;
1218
+ evals[13] = y_add_identity * domainSep * wire(p, WIRE.Q_ELLIPTIC) * (ONE - q_is_double);
1219
+ }
1220
+
1221
+ // Contribution 10 point doubling, x-coordinate check
1222
+ // (x3 + x1 + x1) (4y1*y1) - 9 * x1 * x1 * x1 * x1 = 0
1223
+ // N.B. we're using the equivalence x1*x1*x1 === y1*y1 - curve_b to reduce degree by 1
1224
+ {
1225
+ Fr x_pow_4 = (y1_sqr + GRUMPKIN_CURVE_B_PARAMETER_NEGATED) * ep.x_1;
1226
+ Fr y1_sqr_mul_4 = y1_sqr + y1_sqr;
1227
+ y1_sqr_mul_4 = y1_sqr_mul_4 + y1_sqr_mul_4;
1228
+ Fr x1_pow_4_mul_9 = x_pow_4 * Fr.wrap(9);
1229
+
1230
+ // NOTE: pushed into memory (stack >:'( )
1231
+ ep.x_double_identity = (ep.x_3 + ep.x_1 + ep.x_1) * y1_sqr_mul_4 - x1_pow_4_mul_9;
1232
+
1233
+ Fr acc = ep.x_double_identity * domainSep * wire(p, WIRE.Q_ELLIPTIC) * q_is_double;
1234
+ evals[12] = evals[12] + acc;
1235
+ }
1236
+
1237
+ // Contribution 11 point doubling, y-coordinate check
1238
+ // (y1 + y1) (2y1) - (3 * x1 * x1)(x1 - x3) = 0
1239
+ {
1240
+ Fr x1_sqr_mul_3 = (ep.x_1 + ep.x_1 + ep.x_1) * ep.x_1;
1241
+ Fr y_double_identity = x1_sqr_mul_3 * (ep.x_1 - ep.x_3) - (ep.y_1 + ep.y_1) * (ep.y_1 + ep.y_3);
1242
+ evals[13] = evals[13] + y_double_identity * domainSep * wire(p, WIRE.Q_ELLIPTIC) * q_is_double;
1243
+ }
1244
+ }
1245
+
1246
+ function accumulateMemoryRelation(
1247
+ Fr[NUMBER_OF_ENTITIES] memory p,
1248
+ Honk.RelationParameters memory rp,
1249
+ Fr[NUMBER_OF_SUBRELATIONS] memory evals,
1250
+ Fr domainSep
1251
+ ) internal pure {
1252
+ MemParams memory ap;
1253
+
1254
+ // Compute eta powers locally
1255
+ Fr eta_two = rp.eta * rp.eta;
1256
+ Fr eta_three = eta_two * rp.eta;
1257
+
1258
+ /**
1259
+ * MEMORY
1260
+ *
1261
+ * A RAM memory record contains a tuple of the following fields:
1262
+ * * i: `index` of memory cell being accessed
1263
+ * * t: `timestamp` of memory cell being accessed (used for RAM, set to 0 for ROM)
1264
+ * * v: `value` of memory cell being accessed
1265
+ * * a: `access` type of record. read: 0 = read, 1 = write
1266
+ * * r: `record` of memory cell. record = access + index * eta + timestamp * eta_two + value * eta_three
1267
+ *
1268
+ * A ROM memory record contains a tuple of the following fields:
1269
+ * * i: `index` of memory cell being accessed
1270
+ * * v: `value1` of memory cell being accessed (ROM tables can store up to 2 values per index)
1271
+ * * v2:`value2` of memory cell being accessed (ROM tables can store up to 2 values per index)
1272
+ * * r: `record` of memory cell. record = index * eta + value2 * eta_two + value1 * eta_three
1273
+ *
1274
+ * When performing a read/write access, the values of i, t, v, v2, a, r are stored in the following wires +
1275
+ * selectors, depending on whether the gate is a RAM read/write or a ROM read
1276
+ *
1277
+ * | gate type | i | v2/t | v | a | r |
1278
+ * | --------- | -- | ----- | -- | -- | -- |
1279
+ * | ROM | w1 | w2 | w3 | -- | w4 |
1280
+ * | RAM | w1 | w2 | w3 | qc | w4 |
1281
+ *
1282
+ * (for accesses where `index` is a circuit constant, it is assumed the circuit will apply a copy constraint on
1283
+ * `w2` to fix its value)
1284
+ *
1285
+ *
1286
+ */
1287
+
1288
+ /**
1289
+ * Memory Record Check
1290
+ * Partial degree: 1
1291
+ * Total degree: 4
1292
+ *
1293
+ * A ROM/ROM access gate can be evaluated with the identity:
1294
+ *
1295
+ * qc + w1 \eta + w2 \eta_two + w3 \eta_three - w4 = 0
1296
+ *
1297
+ * For ROM gates, qc = 0
1298
+ */
1299
+ ap.memory_record_check = wire(p, WIRE.W_O) * eta_three;
1300
+ ap.memory_record_check = ap.memory_record_check + (wire(p, WIRE.W_R) * eta_two);
1301
+ ap.memory_record_check = ap.memory_record_check + (wire(p, WIRE.W_L) * rp.eta);
1302
+ ap.memory_record_check = ap.memory_record_check + wire(p, WIRE.Q_C);
1303
+ ap.partial_record_check = ap.memory_record_check; // used in RAM consistency check; deg 1 or 4
1304
+ ap.memory_record_check = ap.memory_record_check - wire(p, WIRE.W_4);
1305
+
1306
+ /**
1307
+ * Contribution 13 & 14
1308
+ * ROM Consistency Check
1309
+ * Partial degree: 1
1310
+ * Total degree: 4
1311
+ *
1312
+ * For every ROM read, a set equivalence check is applied between the record witnesses, and a second set of
1313
+ * records that are sorted.
1314
+ *
1315
+ * We apply the following checks for the sorted records:
1316
+ *
1317
+ * 1. w1, w2, w3 correctly map to 'index', 'v1, 'v2' for a given record value at w4
1318
+ * 2. index values for adjacent records are monotonically increasing
1319
+ * 3. if, at gate i, index_i == index_{i + 1}, then value1_i == value1_{i + 1} and value2_i == value2_{i + 1}
1320
+ *
1321
+ */
1322
+ ap.index_delta = wire(p, WIRE.W_L_SHIFT) - wire(p, WIRE.W_L);
1323
+ ap.record_delta = wire(p, WIRE.W_4_SHIFT) - wire(p, WIRE.W_4);
1324
+
1325
+ ap.index_is_monotonically_increasing = ap.index_delta * (ap.index_delta - Fr.wrap(1)); // deg 2
1326
+
1327
+ ap.adjacent_values_match_if_adjacent_indices_match = (ap.index_delta * MINUS_ONE + ONE) * ap.record_delta; // deg 2
1328
+
1329
+ evals[15] =
1330
+ ap.adjacent_values_match_if_adjacent_indices_match *
1331
+ (wire(p, WIRE.Q_L) * wire(p, WIRE.Q_R)) *
1332
+ (wire(p, WIRE.Q_MEMORY) * domainSep); // deg 5
1333
+ evals[16] = ap.index_is_monotonically_increasing * (wire(p, WIRE.Q_L) * wire(p, WIRE.Q_R)) * (wire(p, WIRE.Q_MEMORY) * domainSep); // deg 5
1334
+
1335
+ ap.ROM_consistency_check_identity = ap.memory_record_check * (wire(p, WIRE.Q_L) * wire(p, WIRE.Q_R)); // deg 3 or 7
1336
+
1337
+ /**
1338
+ * Contributions 15,16,17
1339
+ * RAM Consistency Check
1340
+ *
1341
+ * The 'access' type of the record is extracted with the expression `w_4 - ap.partial_record_check`
1342
+ * (i.e. for an honest Prover `w1 * eta + w2 * eta^2 + w3 * eta^3 - w4 = access`.
1343
+ * This is validated by requiring `access` to be boolean
1344
+ *
1345
+ * For two adjacent entries in the sorted list if _both_
1346
+ * A) index values match
1347
+ * B) adjacent access value is 0 (i.e. next gate is a READ)
1348
+ * then
1349
+ * C) both values must match.
1350
+ * The gate boolean check is
1351
+ * (A && B) => C === !(A && B) || C === !A || !B || C
1352
+ *
1353
+ * N.B. it is the responsibility of the circuit writer to ensure that every RAM cell is initialized
1354
+ * with a WRITE operation.
1355
+ */
1356
+ Fr access_type = (wire(p, WIRE.W_4) - ap.partial_record_check); // will be 0 or 1 for honest Prover; deg 1 or 4
1357
+ ap.access_check = access_type * (access_type - Fr.wrap(1)); // check value is 0 or 1; deg 2 or 8
1358
+
1359
+ // reverse order we could re-use `ap.partial_record_check` 1 - ((w3' * eta + w2') * eta + w1') * eta
1360
+ // deg 1 or 4
1361
+ ap.next_gate_access_type = wire(p, WIRE.W_O_SHIFT) * eta_three;
1362
+ ap.next_gate_access_type = ap.next_gate_access_type + (wire(p, WIRE.W_R_SHIFT) * eta_two);
1363
+ ap.next_gate_access_type = ap.next_gate_access_type + (wire(p, WIRE.W_L_SHIFT) * rp.eta);
1364
+ ap.next_gate_access_type = wire(p, WIRE.W_4_SHIFT) - ap.next_gate_access_type;
1365
+
1366
+ Fr value_delta = wire(p, WIRE.W_O_SHIFT) - wire(p, WIRE.W_O);
1367
+ ap.adjacent_values_match_if_adjacent_indices_match_and_next_access_is_a_read_operation =
1368
+ (ap.index_delta * MINUS_ONE + ONE) *
1369
+ value_delta *
1370
+ (ap.next_gate_access_type * MINUS_ONE + ONE); // deg 3 or 6
1371
+
1372
+ // We can't apply the RAM consistency check identity on the final entry in the sorted list (the wires in the
1373
+ // next gate would make the identity fail). We need to validate that its 'access type' bool is correct. Can't
1374
+ // do with an arithmetic gate because of the `eta` factors. We need to check that the *next* gate's access
1375
+ // type is correct, to cover this edge case
1376
+ // deg 2 or 4
1377
+ ap.next_gate_access_type_is_boolean = ap.next_gate_access_type * ap.next_gate_access_type - ap.next_gate_access_type;
1378
+
1379
+ // Putting it all together...
1380
+ evals[17] =
1381
+ ap.adjacent_values_match_if_adjacent_indices_match_and_next_access_is_a_read_operation *
1382
+ (wire(p, WIRE.Q_O)) *
1383
+ (wire(p, WIRE.Q_MEMORY) * domainSep); // deg 5 or 8
1384
+ evals[18] = ap.index_is_monotonically_increasing * (wire(p, WIRE.Q_O)) * (wire(p, WIRE.Q_MEMORY) * domainSep); // deg 4
1385
+ evals[19] = ap.next_gate_access_type_is_boolean * (wire(p, WIRE.Q_O)) * (wire(p, WIRE.Q_MEMORY) * domainSep); // deg 4 or 6
1386
+
1387
+ ap.RAM_consistency_check_identity = ap.access_check * (wire(p, WIRE.Q_O)); // deg 3 or 9
1388
+
1389
+ /**
1390
+ * RAM Timestamp Consistency Check
1391
+ *
1392
+ * | w1 | w2 | w3 | w4 |
1393
+ * | index | timestamp | timestamp_check | -- |
1394
+ *
1395
+ * Let delta_index = index_{i + 1} - index_{i}
1396
+ *
1397
+ * Iff delta_index == 0, timestamp_check = timestamp_{i + 1} - timestamp_i
1398
+ * Else timestamp_check = 0
1399
+ */
1400
+ ap.timestamp_delta = wire(p, WIRE.W_R_SHIFT) - wire(p, WIRE.W_R);
1401
+ ap.RAM_timestamp_check_identity = (ap.index_delta * MINUS_ONE + ONE) * ap.timestamp_delta - wire(p, WIRE.W_O); // deg 3
1402
+
1403
+ /**
1404
+ * Complete Contribution 12
1405
+ * The complete RAM/ROM memory identity
1406
+ * Partial degree:
1407
+ */
1408
+ ap.memory_identity = ap.ROM_consistency_check_identity; // deg 3 or 6
1409
+ ap.memory_identity = ap.memory_identity + ap.RAM_timestamp_check_identity * (wire(p, WIRE.Q_4) * wire(p, WIRE.Q_L)); // deg 4
1410
+ ap.memory_identity = ap.memory_identity + ap.memory_record_check * (wire(p, WIRE.Q_M) * wire(p, WIRE.Q_L)); // deg 3 or 6
1411
+ ap.memory_identity = ap.memory_identity + ap.RAM_consistency_check_identity; // deg 3 or 9
1412
+
1413
+ // (deg 3 or 9) + (deg 4) + (deg 3)
1414
+ ap.memory_identity = ap.memory_identity * (wire(p, WIRE.Q_MEMORY) * domainSep); // deg 4 or 10
1415
+ evals[14] = ap.memory_identity;
1416
+ }
1417
+
1418
+ function accumulateNnfRelation(Fr[NUMBER_OF_ENTITIES] memory p, Fr[NUMBER_OF_SUBRELATIONS] memory evals, Fr domainSep) internal pure {
1419
+ NnfParams memory ap;
1420
+
1421
+ /**
1422
+ * Contribution 12
1423
+ * Non native field arithmetic gate 2
1424
+ * deg 4
1425
+ *
1426
+ * _ _
1427
+ * / _ _ _ 14 \
1428
+ * q_2 . q_4 | (w_1 . w_2) + (w_1 . w_2) + (w_1 . w_4 + w_2 . w_3 - w_3) . 2 - w_3 - w_4 |
1429
+ * \_ _/
1430
+ *
1431
+ *
1432
+ */
1433
+ ap.limb_subproduct = wire(p, WIRE.W_L) * wire(p, WIRE.W_R_SHIFT) + wire(p, WIRE.W_L_SHIFT) * wire(p, WIRE.W_R);
1434
+ ap.non_native_field_gate_2 = (wire(p, WIRE.W_L) * wire(p, WIRE.W_4) + wire(p, WIRE.W_R) * wire(p, WIRE.W_O) - wire(p, WIRE.W_O_SHIFT));
1435
+ ap.non_native_field_gate_2 = ap.non_native_field_gate_2 * LIMB_SIZE;
1436
+ ap.non_native_field_gate_2 = ap.non_native_field_gate_2 - wire(p, WIRE.W_4_SHIFT);
1437
+ ap.non_native_field_gate_2 = ap.non_native_field_gate_2 + ap.limb_subproduct;
1438
+ ap.non_native_field_gate_2 = ap.non_native_field_gate_2 * wire(p, WIRE.Q_4);
1439
+
1440
+ ap.limb_subproduct = ap.limb_subproduct * LIMB_SIZE;
1441
+ ap.limb_subproduct = ap.limb_subproduct + (wire(p, WIRE.W_L_SHIFT) * wire(p, WIRE.W_R_SHIFT));
1442
+ ap.non_native_field_gate_1 = ap.limb_subproduct;
1443
+ ap.non_native_field_gate_1 = ap.non_native_field_gate_1 - (wire(p, WIRE.W_O) + wire(p, WIRE.W_4));
1444
+ ap.non_native_field_gate_1 = ap.non_native_field_gate_1 * wire(p, WIRE.Q_O);
1445
+
1446
+ ap.non_native_field_gate_3 = ap.limb_subproduct;
1447
+ ap.non_native_field_gate_3 = ap.non_native_field_gate_3 + wire(p, WIRE.W_4);
1448
+ ap.non_native_field_gate_3 = ap.non_native_field_gate_3 - (wire(p, WIRE.W_O_SHIFT) + wire(p, WIRE.W_4_SHIFT));
1449
+ ap.non_native_field_gate_3 = ap.non_native_field_gate_3 * wire(p, WIRE.Q_M);
1450
+
1451
+ Fr non_native_field_identity = ap.non_native_field_gate_1 + ap.non_native_field_gate_2 + ap.non_native_field_gate_3;
1452
+ non_native_field_identity = non_native_field_identity * wire(p, WIRE.Q_R);
1453
+
1454
+ // ((((w2' * 2^14 + w1') * 2^14 + w3) * 2^14 + w2) * 2^14 + w1 - w4) * qm
1455
+ // deg 2
1456
+ ap.limb_accumulator_1 = wire(p, WIRE.W_R_SHIFT) * SUBLIMB_SHIFT;
1457
+ ap.limb_accumulator_1 = ap.limb_accumulator_1 + wire(p, WIRE.W_L_SHIFT);
1458
+ ap.limb_accumulator_1 = ap.limb_accumulator_1 * SUBLIMB_SHIFT;
1459
+ ap.limb_accumulator_1 = ap.limb_accumulator_1 + wire(p, WIRE.W_O);
1460
+ ap.limb_accumulator_1 = ap.limb_accumulator_1 * SUBLIMB_SHIFT;
1461
+ ap.limb_accumulator_1 = ap.limb_accumulator_1 + wire(p, WIRE.W_R);
1462
+ ap.limb_accumulator_1 = ap.limb_accumulator_1 * SUBLIMB_SHIFT;
1463
+ ap.limb_accumulator_1 = ap.limb_accumulator_1 + wire(p, WIRE.W_L);
1464
+ ap.limb_accumulator_1 = ap.limb_accumulator_1 - wire(p, WIRE.W_4);
1465
+ ap.limb_accumulator_1 = ap.limb_accumulator_1 * wire(p, WIRE.Q_4);
1466
+
1467
+ // ((((w3' * 2^14 + w2') * 2^14 + w1') * 2^14 + w4) * 2^14 + w3 - w4') * qm
1468
+ // deg 2
1469
+ ap.limb_accumulator_2 = wire(p, WIRE.W_O_SHIFT) * SUBLIMB_SHIFT;
1470
+ ap.limb_accumulator_2 = ap.limb_accumulator_2 + wire(p, WIRE.W_R_SHIFT);
1471
+ ap.limb_accumulator_2 = ap.limb_accumulator_2 * SUBLIMB_SHIFT;
1472
+ ap.limb_accumulator_2 = ap.limb_accumulator_2 + wire(p, WIRE.W_L_SHIFT);
1473
+ ap.limb_accumulator_2 = ap.limb_accumulator_2 * SUBLIMB_SHIFT;
1474
+ ap.limb_accumulator_2 = ap.limb_accumulator_2 + wire(p, WIRE.W_4);
1475
+ ap.limb_accumulator_2 = ap.limb_accumulator_2 * SUBLIMB_SHIFT;
1476
+ ap.limb_accumulator_2 = ap.limb_accumulator_2 + wire(p, WIRE.W_O);
1477
+ ap.limb_accumulator_2 = ap.limb_accumulator_2 - wire(p, WIRE.W_4_SHIFT);
1478
+ ap.limb_accumulator_2 = ap.limb_accumulator_2 * wire(p, WIRE.Q_M);
1479
+
1480
+ Fr limb_accumulator_identity = ap.limb_accumulator_1 + ap.limb_accumulator_2;
1481
+ limb_accumulator_identity = limb_accumulator_identity * wire(p, WIRE.Q_O); // deg 3
1482
+
1483
+ ap.nnf_identity = non_native_field_identity + limb_accumulator_identity;
1484
+ ap.nnf_identity = ap.nnf_identity * (wire(p, WIRE.Q_NNF) * domainSep);
1485
+ evals[20] = ap.nnf_identity;
1486
+ }
1487
+
1488
+ function accumulatePoseidonExternalRelation(
1489
+ Fr[NUMBER_OF_ENTITIES] memory p,
1490
+ Fr[NUMBER_OF_SUBRELATIONS] memory evals,
1491
+ Fr domainSep
1492
+ ) internal pure {
1493
+ PoseidonExternalParams memory ep;
1494
+
1495
+ ep.s1 = wire(p, WIRE.W_L) + wire(p, WIRE.Q_L);
1496
+ ep.s2 = wire(p, WIRE.W_R) + wire(p, WIRE.Q_R);
1497
+ ep.s3 = wire(p, WIRE.W_O) + wire(p, WIRE.Q_O);
1498
+ ep.s4 = wire(p, WIRE.W_4) + wire(p, WIRE.Q_4);
1499
+
1500
+ ep.u1 = ep.s1 * ep.s1 * ep.s1 * ep.s1 * ep.s1;
1501
+ ep.u2 = ep.s2 * ep.s2 * ep.s2 * ep.s2 * ep.s2;
1502
+ ep.u3 = ep.s3 * ep.s3 * ep.s3 * ep.s3 * ep.s3;
1503
+ ep.u4 = ep.s4 * ep.s4 * ep.s4 * ep.s4 * ep.s4;
1504
+ // matrix mul v = M_E * u with 14 additions
1505
+ ep.t0 = ep.u1 + ep.u2; // u_1 + u_2
1506
+ ep.t1 = ep.u3 + ep.u4; // u_3 + u_4
1507
+ ep.t2 = ep.u2 + ep.u2 + ep.t1; // 2u_2
1508
+ // ep.t2 += ep.t1; // 2u_2 + u_3 + u_4
1509
+ ep.t3 = ep.u4 + ep.u4 + ep.t0; // 2u_4
1510
+ // ep.t3 += ep.t0; // u_1 + u_2 + 2u_4
1511
+ ep.v4 = ep.t1 + ep.t1;
1512
+ ep.v4 = ep.v4 + ep.v4 + ep.t3;
1513
+ // ep.v4 += ep.t3; // u_1 + u_2 + 4u_3 + 6u_4
1514
+ ep.v2 = ep.t0 + ep.t0;
1515
+ ep.v2 = ep.v2 + ep.v2 + ep.t2;
1516
+ // ep.v2 += ep.t2; // 4u_1 + 6u_2 + u_3 + u_4
1517
+ ep.v1 = ep.t3 + ep.v2; // 5u_1 + 7u_2 + u_3 + 3u_4
1518
+ ep.v3 = ep.t2 + ep.v4; // u_1 + 3u_2 + 5u_3 + 7u_4
1519
+
1520
+ ep.q_pos_by_scaling = wire(p, WIRE.Q_POSEIDON2_EXTERNAL) * domainSep;
1521
+ evals[21] = evals[21] + ep.q_pos_by_scaling * (ep.v1 - wire(p, WIRE.W_L_SHIFT));
1522
+
1523
+ evals[22] = evals[22] + ep.q_pos_by_scaling * (ep.v2 - wire(p, WIRE.W_R_SHIFT));
1524
+
1525
+ evals[23] = evals[23] + ep.q_pos_by_scaling * (ep.v3 - wire(p, WIRE.W_O_SHIFT));
1526
+
1527
+ evals[24] = evals[24] + ep.q_pos_by_scaling * (ep.v4 - wire(p, WIRE.W_4_SHIFT));
1528
+ }
1529
+
1530
+ function accumulatePoseidonInternalRelation(
1531
+ Fr[NUMBER_OF_ENTITIES] memory p,
1532
+ Fr[NUMBER_OF_SUBRELATIONS] memory evals,
1533
+ Fr domainSep
1534
+ ) internal pure {
1535
+ PoseidonInternalParams memory ip;
1536
+
1537
+ Fr[4] memory INTERNAL_MATRIX_DIAGONAL = [
1538
+ FrLib.from(0x10dc6e9c006ea38b04b1e03b4bd9490c0d03f98929ca1d7fb56821fd19d3b6e7),
1539
+ FrLib.from(0x0c28145b6a44df3e0149b3d0a30b3bb599df9756d4dd9b84a86b38cfb45a740b),
1540
+ FrLib.from(0x00544b8338791518b2c7645a50392798b21f75bb60e3596170067d00141cac15),
1541
+ FrLib.from(0x222c01175718386f2e2e82eb122789e352e105a3b8fa852613bc534433ee428b)
1542
+ ];
1543
+
1544
+ // add round constants
1545
+ ip.s1 = wire(p, WIRE.W_L) + wire(p, WIRE.Q_L);
1546
+
1547
+ // apply s-box round
1548
+ ip.u1 = ip.s1 * ip.s1 * ip.s1 * ip.s1 * ip.s1;
1549
+ ip.u2 = wire(p, WIRE.W_R);
1550
+ ip.u3 = wire(p, WIRE.W_O);
1551
+ ip.u4 = wire(p, WIRE.W_4);
1552
+
1553
+ // matrix mul with v = M_I * u 4 muls and 7 additions
1554
+ ip.u_sum = ip.u1 + ip.u2 + ip.u3 + ip.u4;
1555
+
1556
+ ip.q_pos_by_scaling = wire(p, WIRE.Q_POSEIDON2_INTERNAL) * domainSep;
1557
+
1558
+ ip.v1 = ip.u1 * INTERNAL_MATRIX_DIAGONAL[0] + ip.u_sum;
1559
+ evals[25] = evals[25] + ip.q_pos_by_scaling * (ip.v1 - wire(p, WIRE.W_L_SHIFT));
1560
+
1561
+ ip.v2 = ip.u2 * INTERNAL_MATRIX_DIAGONAL[1] + ip.u_sum;
1562
+ evals[26] = evals[26] + ip.q_pos_by_scaling * (ip.v2 - wire(p, WIRE.W_R_SHIFT));
1563
+
1564
+ ip.v3 = ip.u3 * INTERNAL_MATRIX_DIAGONAL[2] + ip.u_sum;
1565
+ evals[27] = evals[27] + ip.q_pos_by_scaling * (ip.v3 - wire(p, WIRE.W_O_SHIFT));
1566
+
1567
+ ip.v4 = ip.u4 * INTERNAL_MATRIX_DIAGONAL[3] + ip.u_sum;
1568
+ evals[28] = evals[28] + ip.q_pos_by_scaling * (ip.v4 - wire(p, WIRE.W_4_SHIFT));
1569
+ }
1570
+
1571
+ // Batch subrelation evaluations using precomputed powers of alpha
1572
+ // First subrelation is implicitly scaled by 1, subsequent ones use powers from the subrelationChallenges array
1573
+ function scaleAndBatchSubrelations(
1574
+ Fr[NUMBER_OF_SUBRELATIONS] memory evaluations,
1575
+ Fr[NUMBER_OF_ALPHAS] memory subrelationChallenges
1576
+ ) internal pure returns (Fr accumulator) {
1577
+ accumulator = evaluations[0];
1578
+
1579
+ for (uint256 i = 1; i < NUMBER_OF_SUBRELATIONS; ++i) {
1580
+ accumulator = accumulator + evaluations[i] * subrelationChallenges[i - 1];
1581
+ }
1582
+ }
1583
+ }
1584
+
1585
+ library CommitmentSchemeLib {
1586
+ using FrLib for Fr;
1587
+
1588
+ // Avoid stack too deep
1589
+ struct ShpleminiIntermediates {
1590
+ Fr unshiftedScalar;
1591
+ Fr shiftedScalar;
1592
+ Fr unshiftedScalarNeg;
1593
+ Fr shiftedScalarNeg;
1594
+ // Scalar to be multiplied by [1]₁
1595
+ Fr constantTermAccumulator;
1596
+ // Accumulator for powers of rho
1597
+ Fr batchingChallenge;
1598
+ // Linear combination of multilinear (sumcheck) evaluations and powers of rho
1599
+ Fr batchedEvaluation;
1600
+ Fr[NUM_SMALL_IPA_OPENING_CLAIMS] denominators;
1601
+ Fr[NUM_SMALL_IPA_OPENING_CLAIMS] batchingScalars;
1602
+ // 1/(z - r^{2^i}) for i = 0, ..., logSize, dynamically updated
1603
+ Fr posInvertedDenominator;
1604
+ // 1/(z + r^{2^i}) for i = 0, ..., logSize, dynamically updated
1605
+ Fr negInvertedDenominator;
1606
+ // ν^{2i} * 1/(z - r^{2^i})
1607
+ Fr scalingFactorPos;
1608
+ // ν^{2i+1} * 1/(z + r^{2^i})
1609
+ Fr scalingFactorNeg;
1610
+ // Fold_i(r^{2^i}) reconstructed by Verifier
1611
+ Fr[] foldPosEvaluations;
1612
+ }
1613
+
1614
+ // Compute the evaluations Aₗ(r^{2ˡ}) for l = 0, ..., m-1
1615
+ function computeFoldPosEvaluations(
1616
+ Fr[CONST_PROOF_SIZE_LOG_N] memory sumcheckUChallenges,
1617
+ Fr batchedEvalAccumulator,
1618
+ Fr[CONST_PROOF_SIZE_LOG_N] memory geminiEvaluations,
1619
+ Fr[] memory geminiEvalChallengePowers,
1620
+ uint256 logSize
1621
+ ) internal view returns (Fr[] memory) {
1622
+ Fr[] memory foldPosEvaluations = new Fr[](logSize);
1623
+ for (uint256 i = logSize; i > 0; --i) {
1624
+ Fr challengePower = geminiEvalChallengePowers[i - 1];
1625
+ Fr u = sumcheckUChallenges[i - 1];
1626
+
1627
+ Fr batchedEvalRoundAcc = ((challengePower * batchedEvalAccumulator * Fr.wrap(2)) -
1628
+ geminiEvaluations[i - 1] *
1629
+ (challengePower * (ONE - u) - u));
1630
+ // Divide by the denominator
1631
+ batchedEvalRoundAcc = batchedEvalRoundAcc * (challengePower * (ONE - u) + u).invert();
1632
+
1633
+ batchedEvalAccumulator = batchedEvalRoundAcc;
1634
+ foldPosEvaluations[i - 1] = batchedEvalRoundAcc;
1635
+ }
1636
+ return foldPosEvaluations;
1637
+ }
1638
+
1639
+ function computeSquares(Fr r, uint256 logN) internal pure returns (Fr[] memory) {
1640
+ Fr[] memory squares = new Fr[](logN);
1641
+ squares[0] = r;
1642
+ for (uint256 i = 1; i < logN; ++i) {
1643
+ squares[i] = squares[i - 1].sqr();
1644
+ }
1645
+ return squares;
1646
+ }
1647
+ }
1648
+
1649
+ uint256 constant Q = 21888242871839275222246405745257275088696311157297823662689037894645226208583; // EC group order. F_q
1650
+
1651
+ // Fr utility
1652
+
1653
+ function bytesToFr(bytes calldata proofSection) pure returns (Fr scalar) {
1654
+ scalar = FrLib.fromBytes32(bytes32(proofSection));
1655
+ }
1656
+
1657
+ // EC Point utilities
1658
+ function bytesToG1Point(bytes calldata proofSection) pure returns (Honk.G1Point memory point) {
1659
+ uint256 x = uint256(bytes32(proofSection[0x00:0x20]));
1660
+ uint256 y = uint256(bytes32(proofSection[0x20:0x40]));
1661
+ require(x < Q && y < Q, Errors.ValueGeGroupOrder());
1662
+
1663
+ // (0,0) is the canonical EIP-196 encoding of the identity. It is accepted here
1664
+ // because polynomial commitments to identically-zero polynomials (e.g. unused
1665
+ // selector or table polys) are legitimately the identity. On-curve validation
1666
+ // (y² = x³ + 3) is handled by the ecAdd/ecMul precompiles per EIP-196.
1667
+ point = Honk.G1Point({ x: x, y: y });
1668
+ }
1669
+
1670
+ function negateInplace(Honk.G1Point memory point) pure returns (Honk.G1Point memory) {
1671
+ // When y == 0 (order-2 point), negation is the same point. Q - 0 = Q which is >= Q.
1672
+ if (point.y != 0) {
1673
+ point.y = Q - point.y;
1674
+ }
1675
+ return point;
1676
+ }
1677
+
1678
+ /**
1679
+ * Convert the pairing points to G1 points.
1680
+ *
1681
+ * The pairing points are serialised as an array of 2 limbs representing two points
1682
+ * (P0 and P1, used for lhs and rhs of pairing operation).
1683
+ *
1684
+ * There are 2 limbs (lo, hi) for each coordinate, so 4 limbs per point, 8 total.
1685
+ * Layout: [P0.x_lo, P0.x_hi, P0.y_lo, P0.y_hi, P1.x_lo, P1.x_hi, P1.y_lo, P1.y_hi]
1686
+ *
1687
+ * @param pairingPoints The pairing points to convert.
1688
+ * @return lhs P0 point
1689
+ * @return rhs P1 point
1690
+ */
1691
+ function convertPairingPointsToG1(
1692
+ Fr[PAIRING_POINTS_SIZE] memory pairingPoints
1693
+ ) pure returns (Honk.G1Point memory lhs, Honk.G1Point memory rhs) {
1694
+ // P0 (lhs): x = lo | (hi << 136)
1695
+ uint256 lhsX = Fr.unwrap(pairingPoints[0]);
1696
+ lhsX |= Fr.unwrap(pairingPoints[1]) << 136;
1697
+
1698
+ uint256 lhsY = Fr.unwrap(pairingPoints[2]);
1699
+ lhsY |= Fr.unwrap(pairingPoints[3]) << 136;
1700
+
1701
+ // P1 (rhs): x = lo | (hi << 136)
1702
+ uint256 rhsX = Fr.unwrap(pairingPoints[4]);
1703
+ rhsX |= Fr.unwrap(pairingPoints[5]) << 136;
1704
+
1705
+ uint256 rhsY = Fr.unwrap(pairingPoints[6]);
1706
+ rhsY |= Fr.unwrap(pairingPoints[7]) << 136;
1707
+
1708
+ // Reconstructed coordinates must be < Q to prevent malleability.
1709
+ // Without this, two different limb encodings could map to the same curve point
1710
+ // (via mulmod reduction in on-curve checks) but produce different transcript hashes.
1711
+ require(lhsX < Q && lhsY < Q && rhsX < Q && rhsY < Q, Errors.ValueGeGroupOrder());
1712
+
1713
+ lhs.x = lhsX;
1714
+ lhs.y = lhsY;
1715
+ rhs.x = rhsX;
1716
+ rhs.y = rhsY;
1717
+ }
1718
+
1719
+ /**
1720
+ * Hash the pairing inputs from the present verification context with those extracted from the public inputs.
1721
+ *
1722
+ * @param proofPairingPoints Pairing points from the proof - (public inputs).
1723
+ * @param accLhs Accumulator point for the left side - result of shplemini.
1724
+ * @param accRhs Accumulator point for the right side - result of shplemini.
1725
+ * @return recursionSeparator The recursion separator - generated from hashing the above.
1726
+ */
1727
+ function generateRecursionSeparator(
1728
+ Fr[PAIRING_POINTS_SIZE] memory proofPairingPoints,
1729
+ Honk.G1Point memory accLhs,
1730
+ Honk.G1Point memory accRhs
1731
+ ) pure returns (Fr recursionSeparator) {
1732
+ // hash the proof aggregated X
1733
+ // hash the proof aggregated Y
1734
+ // hash the accum X
1735
+ // hash the accum Y
1736
+
1737
+ (Honk.G1Point memory proofLhs, Honk.G1Point memory proofRhs) = convertPairingPointsToG1(proofPairingPoints);
1738
+
1739
+ uint256[8] memory recursionSeparatorElements;
1740
+
1741
+ // Proof points
1742
+ recursionSeparatorElements[0] = proofLhs.x;
1743
+ recursionSeparatorElements[1] = proofLhs.y;
1744
+ recursionSeparatorElements[2] = proofRhs.x;
1745
+ recursionSeparatorElements[3] = proofRhs.y;
1746
+
1747
+ // Accumulator points
1748
+ recursionSeparatorElements[4] = accLhs.x;
1749
+ recursionSeparatorElements[5] = accLhs.y;
1750
+ recursionSeparatorElements[6] = accRhs.x;
1751
+ recursionSeparatorElements[7] = accRhs.y;
1752
+
1753
+ recursionSeparator = FrLib.from(uint256(keccak256(abi.encodePacked(recursionSeparatorElements))) % P);
1754
+ }
1755
+
1756
+ /**
1757
+ * G1 Mul with Separator
1758
+ * Using the ecAdd and ecMul precompiles
1759
+ *
1760
+ * @param basePoint The point to multiply.
1761
+ * @param other The other point to add.
1762
+ * @param recursionSeperator The separator to use for the multiplication.
1763
+ * @return `(recursionSeperator * basePoint) + other`.
1764
+ */
1765
+ function mulWithSeperator(
1766
+ Honk.G1Point memory basePoint,
1767
+ Honk.G1Point memory other,
1768
+ Fr recursionSeperator
1769
+ ) view returns (Honk.G1Point memory) {
1770
+ Honk.G1Point memory result;
1771
+
1772
+ result = ecMul(recursionSeperator, basePoint);
1773
+ result = ecAdd(result, other);
1774
+
1775
+ return result;
1776
+ }
1777
+
1778
+ /**
1779
+ * G1 Mul
1780
+ * Takes a Fr value and a G1 point and uses the ecMul precompile to return the result.
1781
+ *
1782
+ * @param value The value to multiply the point by.
1783
+ * @param point The point to multiply.
1784
+ * @return result The result of the multiplication.
1785
+ */
1786
+ function ecMul(Fr value, Honk.G1Point memory point) view returns (Honk.G1Point memory) {
1787
+ Honk.G1Point memory result;
1788
+
1789
+ assembly {
1790
+ let free := mload(0x40)
1791
+ // Write the point into memory (two 32 byte words)
1792
+ // Memory layout:
1793
+ // Address | value
1794
+ // free | point.x
1795
+ // free + 0x20| point.y
1796
+ mstore(free, mload(point))
1797
+ mstore(add(free, 0x20), mload(add(point, 0x20)))
1798
+ // Write the scalar into memory (one 32 byte word)
1799
+ // Memory layout:
1800
+ // Address | value
1801
+ // free + 0x40| value
1802
+ mstore(add(free, 0x40), value)
1803
+
1804
+ // Call the ecMul precompile, it takes in the following
1805
+ // [point.x, point.y, scalar], and returns the result back into the free memory location.
1806
+ let success := staticcall(gas(), 0x07, free, 0x60, free, 0x40)
1807
+ if iszero(success) {
1808
+ revert(0, 0)
1809
+ }
1810
+ // Copy the result of the multiplication back into the result memory location.
1811
+ // Memory layout:
1812
+ // Address | value
1813
+ // result | result.x
1814
+ // result + 0x20| result.y
1815
+ mstore(result, mload(free))
1816
+ mstore(add(result, 0x20), mload(add(free, 0x20)))
1817
+
1818
+ mstore(0x40, add(free, 0x60))
1819
+ }
1820
+
1821
+ return result;
1822
+ }
1823
+
1824
+ /**
1825
+ * G1 Add
1826
+ * Takes two G1 points and uses the ecAdd precompile to return the result.
1827
+ *
1828
+ * @param lhs The left hand side of the addition.
1829
+ * @param rhs The right hand side of the addition.
1830
+ * @return result The result of the addition.
1831
+ */
1832
+ function ecAdd(Honk.G1Point memory lhs, Honk.G1Point memory rhs) view returns (Honk.G1Point memory) {
1833
+ Honk.G1Point memory result;
1834
+
1835
+ assembly {
1836
+ let free := mload(0x40)
1837
+ // Write lhs into memory (two 32 byte words)
1838
+ // Memory layout:
1839
+ // Address | value
1840
+ // free | lhs.x
1841
+ // free + 0x20| lhs.y
1842
+ mstore(free, mload(lhs))
1843
+ mstore(add(free, 0x20), mload(add(lhs, 0x20)))
1844
+
1845
+ // Write rhs into memory (two 32 byte words)
1846
+ // Memory layout:
1847
+ // Address | value
1848
+ // free + 0x40| rhs.x
1849
+ // free + 0x60| rhs.y
1850
+ mstore(add(free, 0x40), mload(rhs))
1851
+ mstore(add(free, 0x60), mload(add(rhs, 0x20)))
1852
+
1853
+ // Call the ecAdd precompile, it takes in the following
1854
+ // [lhs.x, lhs.y, rhs.x, rhs.y], and returns their addition back into the free memory location.
1855
+ let success := staticcall(gas(), 0x06, free, 0x80, free, 0x40)
1856
+ if iszero(success) {
1857
+ revert(0, 0)
1858
+ }
1859
+
1860
+ // Copy the result of the addition back into the result memory location.
1861
+ // Memory layout:
1862
+ // Address | value
1863
+ // result | result.x
1864
+ // result + 0x20| result.y
1865
+ mstore(result, mload(free))
1866
+ mstore(add(result, 0x20), mload(add(free, 0x20)))
1867
+
1868
+ mstore(0x40, add(free, 0x80))
1869
+ }
1870
+
1871
+ return result;
1872
+ }
1873
+
1874
+ function rejectPointAtInfinity(Honk.G1Point memory point) pure {
1875
+ require((point.x | point.y) != 0, Errors.PointAtInfinity());
1876
+ }
1877
+
1878
+ /**
1879
+ * Check if pairing point limbs are all zero (default/infinity).
1880
+ * Default pairing points indicate no recursive verification occurred.
1881
+ */
1882
+ function arePairingPointsDefault(Fr[PAIRING_POINTS_SIZE] memory pairingPoints) pure returns (bool) {
1883
+ uint256 acc = 0;
1884
+ for (uint256 i = 0; i < PAIRING_POINTS_SIZE; i++) {
1885
+ acc |= Fr.unwrap(pairingPoints[i]);
1886
+ }
1887
+ return acc == 0;
1888
+ }
1889
+
1890
+ function pairing(Honk.G1Point memory rhs, Honk.G1Point memory lhs) view returns (bool decodedResult) {
1891
+ bytes memory input = abi.encodePacked(
1892
+ rhs.x,
1893
+ rhs.y,
1894
+ // Fixed G2 point
1895
+ uint256(0x198e9393920d483a7260bfb731fb5d25f1aa493335a9e71297e485b7aef312c2),
1896
+ uint256(0x1800deef121f1e76426a00665e5c4479674322d4f75edadd46debd5cd992f6ed),
1897
+ uint256(0x090689d0585ff075ec9e99ad690c3395bc4b313370b38ef355acdadcd122975b),
1898
+ uint256(0x12c85ea5db8c6deb4aab71808dcb408fe3d1e7690c43d37b4ce6cc0166fa7daa),
1899
+ lhs.x,
1900
+ lhs.y,
1901
+ // G2 point from VK
1902
+ uint256(0x260e01b251f6f1c7e7ff4e580791dee8ea51d87a358e038b4efe30fac09383c1),
1903
+ uint256(0x0118c4d5b837bcc2bc89b5b398b5974e9f5944073b32078b7e231fec938883b0),
1904
+ uint256(0x04fc6369f7110fe3d25156c1bb9a72859cf2a04641f99ba4ee413c80da6a5fe4),
1905
+ uint256(0x22febda3c0c0632a56475b4214e5615e11e6dd3f96e6cea2854a87d4dacc5e55)
1906
+ );
1907
+
1908
+ (bool success, bytes memory result) = address(0x08).staticcall(input);
1909
+ decodedResult = success && abi.decode(result, (bool));
1910
+ }
1911
+
1912
+ abstract contract BaseZKHonkVerifier is IVerifier {
1913
+ using FrLib for Fr;
1914
+
1915
+ struct PairingInputs {
1916
+ Honk.G1Point P_0;
1917
+ Honk.G1Point P_1;
1918
+ }
1919
+
1920
+ struct SmallSubgroupIpaIntermediates {
1921
+ Fr[SUBGROUP_SIZE] challengePolyLagrange;
1922
+ Fr challengePolyEval;
1923
+ Fr lagrangeFirst;
1924
+ Fr lagrangeLast;
1925
+ Fr rootPower;
1926
+ Fr[SUBGROUP_SIZE] denominators; // this has to disappear
1927
+ Fr diff;
1928
+ }
1929
+
1930
+ // Constants for proof length calculation (matching UltraKeccakZKFlavor)
1931
+ uint256 internal constant NUM_WITNESS_ENTITIES = 8 + NUM_MASKING_POLYNOMIALS;
1932
+ uint256 internal constant NUM_ELEMENTS_COMM = 2; // uint256 elements for curve points
1933
+ uint256 internal constant NUM_ELEMENTS_FR = 1; // uint256 elements for field elements
1934
+ uint256 internal constant NUM_LIBRA_EVALUATIONS = 4; // libra evaluations
1935
+
1936
+ uint256 internal constant LIBRA_COMMITMENTS = 3;
1937
+ uint256 internal constant LIBRA_EVALUATIONS = 4;
1938
+ uint256 internal constant LIBRA_UNIVARIATES_LENGTH = 9;
1939
+
1940
+ uint256 internal constant SHIFTED_COMMITMENTS_START = 30;
1941
+ uint256 internal constant PERMUTATION_ARGUMENT_VALUE_SEPARATOR = 1 << 28;
1942
+
1943
+ uint256 internal immutable $N;
1944
+ uint256 internal immutable $LOG_N;
1945
+ uint256 internal immutable $VK_HASH;
1946
+ uint256 internal immutable $NUM_PUBLIC_INPUTS;
1947
+ uint256 internal immutable $MSMSize;
1948
+
1949
+ constructor(uint256 _N, uint256 _logN, uint256 _vkHash, uint256 _numPublicInputs) {
1950
+ $N = _N;
1951
+ $LOG_N = _logN;
1952
+ $VK_HASH = _vkHash;
1953
+ $NUM_PUBLIC_INPUTS = _numPublicInputs;
1954
+ $MSMSize = NUMBER_UNSHIFTED_ZK + _logN + LIBRA_COMMITMENTS + 2;
1955
+ }
1956
+
1957
+ function validateVerificationKey(Honk.VerificationKey memory vk) internal view {
1958
+ require($N == vk.circuitSize, Errors.VerificationKeyConfigurationMismatch());
1959
+ require($LOG_N == vk.logCircuitSize, Errors.VerificationKeyConfigurationMismatch());
1960
+ require($NUM_PUBLIC_INPUTS == vk.publicInputsSize, Errors.VerificationKeyConfigurationMismatch());
1961
+ }
1962
+
1963
+ function verify(bytes calldata proof, bytes32[] calldata publicInputs) public view override returns (bool verified) {
1964
+ // Calculate expected proof size based on $LOG_N
1965
+ uint256 expectedProofSize = calculateProofSize($LOG_N);
1966
+
1967
+ // Check the received proof is the expected size where each field element is 32 bytes
1968
+ require(proof.length == expectedProofSize, Errors.ProofLengthWrongWithLogN($LOG_N, proof.length, expectedProofSize));
1969
+
1970
+ Honk.VerificationKey memory vk = loadVerificationKey();
1971
+ Honk.ZKProof memory p = ZKTranscriptLib.loadProof(proof, $LOG_N);
1972
+
1973
+ require(publicInputs.length == vk.publicInputsSize - PAIRING_POINTS_SIZE, Errors.PublicInputsLengthWrong());
1974
+
1975
+ // Generate the fiat shamir challenges for the whole protocol
1976
+ ZKTranscript memory t = ZKTranscriptLib.generateTranscript(p, publicInputs, $VK_HASH, $NUM_PUBLIC_INPUTS, $LOG_N);
1977
+
1978
+ // Derive public input delta
1979
+ t.relationParameters.publicInputsDelta = computePublicInputDelta(
1980
+ publicInputs,
1981
+ p.pairingPointObject,
1982
+ t.relationParameters.beta,
1983
+ t.relationParameters.gamma,
1984
+ 5 // pubInputsOffset = NUM_DISABLED_ROWS_IN_SUMCHECK + NUM_ZERO_ROWS = 4 + 1
1985
+ );
1986
+
1987
+ // Sumcheck
1988
+ require(verifySumcheck(p, t), Errors.SumcheckFailed());
1989
+ require(verifyShplemini(p, vk, t), Errors.ShpleminiFailed());
1990
+
1991
+ verified = true;
1992
+ }
1993
+
1994
+ function computePublicInputDelta(
1995
+ bytes32[] memory publicInputs,
1996
+ Fr[PAIRING_POINTS_SIZE] memory pairingPointObject,
1997
+ Fr beta,
1998
+ Fr gamma,
1999
+ uint256 offset
2000
+ ) internal view returns (Fr publicInputDelta) {
2001
+ Fr numerator = Fr.wrap(1);
2002
+ Fr denominator = Fr.wrap(1);
2003
+
2004
+ Fr numeratorAcc = gamma + (beta * FrLib.from(PERMUTATION_ARGUMENT_VALUE_SEPARATOR + offset));
2005
+ Fr denominatorAcc = gamma - (beta * FrLib.from(offset + 1));
2006
+
2007
+ {
2008
+ for (uint256 i = 0; i < $NUM_PUBLIC_INPUTS - PAIRING_POINTS_SIZE; i++) {
2009
+ Fr pubInput = FrLib.fromBytes32(publicInputs[i]);
2010
+
2011
+ numerator = numerator * (numeratorAcc + pubInput);
2012
+ denominator = denominator * (denominatorAcc + pubInput);
2013
+
2014
+ numeratorAcc = numeratorAcc + beta;
2015
+ denominatorAcc = denominatorAcc - beta;
2016
+ }
2017
+
2018
+ for (uint256 i = 0; i < PAIRING_POINTS_SIZE; i++) {
2019
+ Fr pubInput = pairingPointObject[i];
2020
+
2021
+ numerator = numerator * (numeratorAcc + pubInput);
2022
+ denominator = denominator * (denominatorAcc + pubInput);
2023
+
2024
+ numeratorAcc = numeratorAcc + beta;
2025
+ denominatorAcc = denominatorAcc - beta;
2026
+ }
2027
+ }
2028
+
2029
+ // Fr delta = numerator / denominator; // TOOO: batch invert later?
2030
+ publicInputDelta = FrLib.div(numerator, denominator);
2031
+ }
2032
+
2033
+ function verifySumcheck(Honk.ZKProof memory proof, ZKTranscript memory tp) internal view returns (bool verified) {
2034
+ Fr roundTargetSum = tp.libraChallenge * proof.libraSum; // default 0
2035
+ Fr powPartialEvaluation = Fr.wrap(1);
2036
+
2037
+ // We perform sumcheck reductions over log n rounds ( the multivariate degree )
2038
+ for (uint256 round; round < $LOG_N; ++round) {
2039
+ Fr[ZK_BATCHED_RELATION_PARTIAL_LENGTH] memory roundUnivariate = proof.sumcheckUnivariates[round];
2040
+ Fr totalSum = roundUnivariate[0] + roundUnivariate[1];
2041
+ require(totalSum == roundTargetSum, Errors.SumcheckFailed());
2042
+
2043
+ Fr roundChallenge = tp.sumCheckUChallenges[round];
2044
+
2045
+ // Update the round target for the next rounf
2046
+ roundTargetSum = computeNextTargetSum(roundUnivariate, roundChallenge);
2047
+ powPartialEvaluation = powPartialEvaluation * (Fr.wrap(1) + roundChallenge * (tp.gateChallenges[round] - Fr.wrap(1)));
2048
+ }
2049
+
2050
+ // Last round
2051
+ // For ZK flavors: sumcheckEvaluations has 42 elements
2052
+ // Index 0 is gemini_masking_poly, indices 1-41 are the regular entities used in relations
2053
+ Fr[NUMBER_OF_ENTITIES] memory relationsEvaluations;
2054
+ for (uint256 i = 0; i < NUMBER_OF_ENTITIES; i++) {
2055
+ relationsEvaluations[i] = proof.sumcheckEvaluations[i + NUM_MASKING_POLYNOMIALS]; // Skip gemini_masking_poly at index 0
2056
+ }
2057
+ Fr grandHonkRelationSum = RelationsLib.accumulateRelationEvaluations(
2058
+ relationsEvaluations,
2059
+ tp.relationParameters,
2060
+ tp.alphas,
2061
+ powPartialEvaluation
2062
+ );
2063
+
2064
+ // Row-disabling polynomial: 1 - ∏_{i≥2}(1 - u_i)
2065
+ Fr evaluation = Fr.wrap(1);
2066
+ for (uint256 i = 2; i < $LOG_N; i++) {
2067
+ evaluation = evaluation * (Fr.wrap(1) - tp.sumCheckUChallenges[i]);
2068
+ }
2069
+
2070
+ grandHonkRelationSum = grandHonkRelationSum * (Fr.wrap(1) - evaluation) + proof.libraEvaluation * tp.libraChallenge;
2071
+ verified = (grandHonkRelationSum == roundTargetSum);
2072
+ }
2073
+
2074
+ // Return the new target sum for the next sumcheck round
2075
+ function computeNextTargetSum(
2076
+ Fr[ZK_BATCHED_RELATION_PARTIAL_LENGTH] memory roundUnivariates,
2077
+ Fr roundChallenge
2078
+ ) internal view returns (Fr targetSum) {
2079
+ Fr[ZK_BATCHED_RELATION_PARTIAL_LENGTH] memory BARYCENTRIC_LAGRANGE_DENOMINATORS = [
2080
+ Fr.wrap(0x0000000000000000000000000000000000000000000000000000000000009d80),
2081
+ Fr.wrap(0x30644e72e131a029b85045b68181585d2833e84879b9709143e1f593efffec51),
2082
+ Fr.wrap(0x00000000000000000000000000000000000000000000000000000000000005a0),
2083
+ Fr.wrap(0x30644e72e131a029b85045b68181585d2833e84879b9709143e1f593effffd31),
2084
+ Fr.wrap(0x0000000000000000000000000000000000000000000000000000000000000240),
2085
+ Fr.wrap(0x30644e72e131a029b85045b68181585d2833e84879b9709143e1f593effffd31),
2086
+ Fr.wrap(0x00000000000000000000000000000000000000000000000000000000000005a0),
2087
+ Fr.wrap(0x30644e72e131a029b85045b68181585d2833e84879b9709143e1f593efffec51),
2088
+ Fr.wrap(0x0000000000000000000000000000000000000000000000000000000000009d80)
2089
+ ];
2090
+
2091
+ // To compute the next target sum, we evaluate the given univariate at a point u (challenge).
2092
+
2093
+ // Performing Barycentric evaluations
2094
+ // Compute B(x)
2095
+ Fr numeratorValue = Fr.wrap(1);
2096
+ for (uint256 i = 0; i < ZK_BATCHED_RELATION_PARTIAL_LENGTH; ++i) {
2097
+ numeratorValue = numeratorValue * (roundChallenge - Fr.wrap(i));
2098
+ }
2099
+
2100
+ Fr[ZK_BATCHED_RELATION_PARTIAL_LENGTH] memory denominatorInverses;
2101
+ for (uint256 i = 0; i < ZK_BATCHED_RELATION_PARTIAL_LENGTH; ++i) {
2102
+ denominatorInverses[i] = FrLib.invert(BARYCENTRIC_LAGRANGE_DENOMINATORS[i] * (roundChallenge - Fr.wrap(i)));
2103
+ }
2104
+
2105
+ for (uint256 i = 0; i < ZK_BATCHED_RELATION_PARTIAL_LENGTH; ++i) {
2106
+ targetSum = targetSum + roundUnivariates[i] * denominatorInverses[i];
2107
+ }
2108
+
2109
+ // Scale the sum by the value of B(x)
2110
+ targetSum = targetSum * numeratorValue;
2111
+ }
2112
+
2113
+ function verifyShplemini(
2114
+ Honk.ZKProof memory proof,
2115
+ Honk.VerificationKey memory vk,
2116
+ ZKTranscript memory tp
2117
+ ) internal view returns (bool verified) {
2118
+ CommitmentSchemeLib.ShpleminiIntermediates memory mem; // stack
2119
+
2120
+ // - Compute vector (r, r², ... , r²⁽ⁿ⁻¹⁾), where n = log_circuit_size
2121
+ Fr[] memory powers_of_evaluation_challenge = CommitmentSchemeLib.computeSquares(tp.geminiR, $LOG_N);
2122
+ // Arrays hold values that will be linearly combined for the gemini and shplonk batch openings
2123
+ Fr[] memory scalars = new Fr[]($MSMSize);
2124
+ Honk.G1Point[] memory commitments = new Honk.G1Point[]($MSMSize);
2125
+
2126
+ mem.posInvertedDenominator = (tp.shplonkZ - powers_of_evaluation_challenge[0]).invert();
2127
+ mem.negInvertedDenominator = (tp.shplonkZ + powers_of_evaluation_challenge[0]).invert();
2128
+
2129
+ mem.unshiftedScalar = mem.posInvertedDenominator + (tp.shplonkNu * mem.negInvertedDenominator);
2130
+ mem.shiftedScalar = tp.geminiR.invert() * (mem.posInvertedDenominator - (tp.shplonkNu * mem.negInvertedDenominator));
2131
+
2132
+ scalars[0] = Fr.wrap(1);
2133
+ commitments[0] = proof.shplonkQ;
2134
+
2135
+ /* Batch multivariate opening claims, shifted and unshifted
2136
+ * The vector of scalars is populated as follows:
2137
+ * \f[
2138
+ * \left(
2139
+ * - \left(\frac{1}{z-r} + \nu \times \frac{1}{z+r}\right),
2140
+ * \ldots,
2141
+ * - \rho^{i+k-1} \times \left(\frac{1}{z-r} + \nu \times \frac{1}{z+r}\right),
2142
+ * - \rho^{i+k} \times \frac{1}{r} \times \left(\frac{1}{z-r} - \nu \times \frac{1}{z+r}\right),
2143
+ * \ldots,
2144
+ * - \rho^{k+m-1} \times \frac{1}{r} \times \left(\frac{1}{z-r} - \nu \times \frac{1}{z+r}\right)
2145
+ * \right)
2146
+ * \f]
2147
+ *
2148
+ * The following vector is concatenated to the vector of commitments:
2149
+ * \f[
2150
+ * f_0, \ldots, f_{m-1}, f_{\text{shift}, 0}, \ldots, f_{\text{shift}, k-1}
2151
+ * \f]
2152
+ *
2153
+ * Simultaneously, the evaluation of the multilinear polynomial
2154
+ * \f[
2155
+ * \sum \rho^i \cdot f_i + \sum \rho^{i+k} \cdot f_{\text{shift}, i}
2156
+ * \f]
2157
+ * at the challenge point \f$ (u_0,\ldots, u_{n-1}) \f$ is computed.
2158
+ *
2159
+ * This approach minimizes the number of iterations over the commitments to multilinear polynomials
2160
+ * and eliminates the need to store the powers of \f$ \rho \f$.
2161
+ */
2162
+ // For ZK flavors: evaluations array is [gemini_masking_poly, qm, qc, ql, qr, ...]
2163
+ // Start batching challenge at 1, not rho, to match non-ZK pattern
2164
+ mem.batchingChallenge = Fr.wrap(1);
2165
+ mem.batchedEvaluation = Fr.wrap(0);
2166
+
2167
+ mem.unshiftedScalarNeg = mem.unshiftedScalar.neg();
2168
+ mem.shiftedScalarNeg = mem.shiftedScalar.neg();
2169
+
2170
+ // Process all NUMBER_UNSHIFTED_ZK evaluations (includes gemini_masking_poly at index 0)
2171
+ for (uint256 i = 1; i <= NUMBER_UNSHIFTED_ZK; ++i) {
2172
+ scalars[i] = mem.unshiftedScalarNeg * mem.batchingChallenge;
2173
+ mem.batchedEvaluation = mem.batchedEvaluation + (proof.sumcheckEvaluations[i - NUM_MASKING_POLYNOMIALS] * mem.batchingChallenge);
2174
+ mem.batchingChallenge = mem.batchingChallenge * tp.rho;
2175
+ }
2176
+ // g commitments are accumulated at r
2177
+ // For each of the to be shifted commitments perform the shift in place by
2178
+ // adding to the unshifted value.
2179
+ // We do so, as the values are to be used in batchMul later, and as
2180
+ // `a * c + b * c = (a + b) * c` this will allow us to reduce memory and compute.
2181
+ // Applied to w1, w2, w3, w4 and zPerm
2182
+ for (uint256 i = 0; i < NUMBER_TO_BE_SHIFTED; ++i) {
2183
+ uint256 scalarOff = i + SHIFTED_COMMITMENTS_START;
2184
+ uint256 evaluationOff = i + NUMBER_UNSHIFTED_ZK;
2185
+
2186
+ scalars[scalarOff] = scalars[scalarOff] + (mem.shiftedScalarNeg * mem.batchingChallenge);
2187
+ mem.batchedEvaluation = mem.batchedEvaluation + (proof.sumcheckEvaluations[evaluationOff] * mem.batchingChallenge);
2188
+ mem.batchingChallenge = mem.batchingChallenge * tp.rho;
2189
+ }
2190
+
2191
+ commitments[1] = proof.geminiMaskingPoly;
2192
+
2193
+ commitments[2] = vk.s1;
2194
+ commitments[3] = vk.s2;
2195
+ commitments[4] = vk.s3;
2196
+ commitments[5] = vk.s4;
2197
+ commitments[6] = vk.id1;
2198
+ commitments[7] = vk.id2;
2199
+ commitments[8] = vk.id3;
2200
+ commitments[9] = vk.id4;
2201
+ commitments[10] = vk.lagrangeFirst;
2202
+ commitments[11] = vk.lagrangeLast;
2203
+ commitments[12] = vk.qLookup;
2204
+ commitments[13] = vk.t1;
2205
+ commitments[14] = vk.t2;
2206
+ commitments[15] = vk.t3;
2207
+ commitments[16] = vk.t4;
2208
+ commitments[17] = vk.qm;
2209
+ commitments[18] = vk.qr;
2210
+ commitments[19] = vk.qo;
2211
+ commitments[20] = vk.qc;
2212
+ commitments[21] = vk.ql;
2213
+ commitments[22] = vk.q4;
2214
+ commitments[23] = vk.qArith;
2215
+ commitments[24] = vk.qDeltaRange;
2216
+ commitments[25] = vk.qElliptic;
2217
+ commitments[26] = vk.qMemory;
2218
+ commitments[27] = vk.qNnf;
2219
+ commitments[28] = vk.qPoseidon2External;
2220
+ commitments[29] = vk.qPoseidon2Internal;
2221
+
2222
+ // Accumulate proof points
2223
+ commitments[30] = proof.w1;
2224
+ commitments[31] = proof.w2;
2225
+ commitments[32] = proof.w3;
2226
+ commitments[33] = proof.w4;
2227
+ commitments[34] = proof.zPerm;
2228
+ commitments[35] = proof.lookupInverses;
2229
+ commitments[36] = proof.lookupReadCounts;
2230
+ commitments[37] = proof.lookupReadTags;
2231
+
2232
+ /* Batch gemini claims from the prover
2233
+ * place the commitments to gemini aᵢ to the vector of commitments, compute the contributions from
2234
+ * aᵢ(−r²ⁱ) for i=1, … , n−1 to the constant term accumulator, add corresponding scalars
2235
+ *
2236
+ * 1. Moves the vector
2237
+ * \f[
2238
+ * \left( \text{com}(A_1), \text{com}(A_2), \ldots, \text{com}(A_{n-1}) \right)
2239
+ * \f]
2240
+ * to the 'commitments' vector.
2241
+ *
2242
+ * 2. Computes the scalars:
2243
+ * \f[
2244
+ * \frac{\nu^{2}}{z + r^2}, \frac{\nu^3}{z + r^4}, \ldots, \frac{\nu^{n-1}}{z + r^{2^{n-1}}}
2245
+ * \f]
2246
+ * and places them into the 'scalars' vector.
2247
+ *
2248
+ * 3. Accumulates the summands of the constant term:
2249
+ * \f[
2250
+ * \sum_{i=2}^{n-1} \frac{\nu^{i} \cdot A_i(-r^{2^i})}{z + r^{2^i}}
2251
+ * \f]
2252
+ * and adds them to the 'constant_term_accumulator'.
2253
+ */
2254
+
2255
+ // Add contributions from A₀(r) and A₀(-r) to constant_term_accumulator:
2256
+ // Compute the evaluations Aₗ(r^{2ˡ}) for l = 0, ..., $LOG_N - 1
2257
+ Fr[] memory foldPosEvaluations = CommitmentSchemeLib.computeFoldPosEvaluations(
2258
+ tp.sumCheckUChallenges,
2259
+ mem.batchedEvaluation,
2260
+ proof.geminiAEvaluations,
2261
+ powers_of_evaluation_challenge,
2262
+ $LOG_N
2263
+ );
2264
+
2265
+ mem.constantTermAccumulator = foldPosEvaluations[0] * mem.posInvertedDenominator;
2266
+ mem.constantTermAccumulator = mem.constantTermAccumulator + (proof.geminiAEvaluations[0] * tp.shplonkNu * mem.negInvertedDenominator);
2267
+
2268
+ mem.batchingChallenge = tp.shplonkNu.sqr();
2269
+ uint256 boundary = NUMBER_UNSHIFTED_ZK + 1;
2270
+
2271
+ // Compute Shplonk constant term contributions from Aₗ(± r^{2ˡ}) for l = 1, ..., m-1;
2272
+ // Compute scalar multipliers for each fold commitment
2273
+ for (uint256 i = 0; i < $LOG_N - 1; ++i) {
2274
+ bool dummy_round = i >= ($LOG_N - 1);
2275
+
2276
+ if (!dummy_round) {
2277
+ // Update inverted denominators
2278
+ mem.posInvertedDenominator = (tp.shplonkZ - powers_of_evaluation_challenge[i + 1]).invert();
2279
+ mem.negInvertedDenominator = (tp.shplonkZ + powers_of_evaluation_challenge[i + 1]).invert();
2280
+
2281
+ // Compute the scalar multipliers for Aₗ(± r^{2ˡ}) and [Aₗ]
2282
+ mem.scalingFactorPos = mem.batchingChallenge * mem.posInvertedDenominator;
2283
+ mem.scalingFactorNeg = mem.batchingChallenge * tp.shplonkNu * mem.negInvertedDenominator;
2284
+ scalars[boundary + i] = mem.scalingFactorNeg.neg() + mem.scalingFactorPos.neg();
2285
+
2286
+ // Accumulate the const term contribution given by
2287
+ // v^{2l} * Aₗ(r^{2ˡ}) /(z-r^{2^l}) + v^{2l+1} * Aₗ(-r^{2ˡ}) /(z+ r^{2^l})
2288
+ Fr accumContribution = mem.scalingFactorNeg * proof.geminiAEvaluations[i + 1];
2289
+ accumContribution = accumContribution + mem.scalingFactorPos * foldPosEvaluations[i + 1];
2290
+ mem.constantTermAccumulator = mem.constantTermAccumulator + accumContribution;
2291
+ }
2292
+ // Update the running power of v
2293
+ mem.batchingChallenge = mem.batchingChallenge * tp.shplonkNu * tp.shplonkNu;
2294
+
2295
+ commitments[boundary + i] = proof.geminiFoldComms[i];
2296
+ }
2297
+
2298
+ boundary += $LOG_N - 1;
2299
+
2300
+ // Denominators 1/(z - point_i) for the five opening points {r, g*r, r, 1, r}.
2301
+ mem.denominators[0] = ONE.div(tp.shplonkZ - tp.geminiR);
2302
+ mem.denominators[1] = ONE.div(tp.shplonkZ - SUBGROUP_GENERATOR * tp.geminiR);
2303
+ mem.denominators[2] = mem.denominators[0];
2304
+ mem.denominators[SMALL_IPA_BOUNDARY_OPENING_IDX] = ONE.div(tp.shplonkZ - ONE);
2305
+ mem.denominators[NUM_SMALL_IPA_OPENING_CLAIMS - 1] = mem.denominators[0];
2306
+
2307
+ // Iterate the opening claims in three segments — the inner loops can't be merged without an extra induction
2308
+ // variable, which pushes us into stack-too-deep.
2309
+ for (uint256 i = 0; i < SMALL_IPA_BOUNDARY_OPENING_IDX; i++) {
2310
+ Fr scalingFactor = mem.denominators[i] * mem.batchingChallenge;
2311
+ mem.batchingScalars[i] = scalingFactor.neg();
2312
+ mem.batchingChallenge = mem.batchingChallenge * tp.shplonkNu;
2313
+ mem.constantTermAccumulator = mem.constantTermAccumulator + scalingFactor * proof.libraPolyEvals[i];
2314
+ }
2315
+
2316
+ // Boundary slot: claimed value is hardcoded 0, so no constantTermAccumulator contribution.
2317
+ {
2318
+ Fr scalingFactor = mem.denominators[SMALL_IPA_BOUNDARY_OPENING_IDX] * mem.batchingChallenge;
2319
+ mem.batchingScalars[SMALL_IPA_BOUNDARY_OPENING_IDX] = scalingFactor.neg();
2320
+ mem.batchingChallenge = mem.batchingChallenge * tp.shplonkNu;
2321
+ }
2322
+
2323
+ for (uint256 i = SMALL_IPA_BOUNDARY_OPENING_IDX + 1; i < NUM_SMALL_IPA_OPENING_CLAIMS; i++) {
2324
+ Fr scalingFactor = mem.denominators[i] * mem.batchingChallenge;
2325
+ mem.batchingScalars[i] = scalingFactor.neg();
2326
+ mem.batchingChallenge = mem.batchingChallenge * tp.shplonkNu;
2327
+ mem.constantTermAccumulator = mem.constantTermAccumulator + scalingFactor * proof.libraPolyEvals[i - 1];
2328
+ }
2329
+
2330
+ // Group per-claim batching scalars by commitment: [G], [A] (three openings), [Q].
2331
+ scalars[boundary] = mem.batchingScalars[0];
2332
+ scalars[boundary + 1] = mem.batchingScalars[1] + mem.batchingScalars[2] + mem.batchingScalars[SMALL_IPA_BOUNDARY_OPENING_IDX];
2333
+ scalars[boundary + 2] = mem.batchingScalars[NUM_SMALL_IPA_OPENING_CLAIMS - 1];
2334
+
2335
+ for (uint256 i = 0; i < LIBRA_COMMITMENTS; i++) {
2336
+ commitments[boundary++] = proof.libraCommitments[i];
2337
+ }
2338
+
2339
+ commitments[boundary] = Honk.G1Point({ x: 1, y: 2 });
2340
+ scalars[boundary++] = mem.constantTermAccumulator;
2341
+
2342
+ require(
2343
+ checkEvalsConsistency(proof.libraPolyEvals, tp.geminiR, tp.sumCheckUChallenges, proof.libraEvaluation),
2344
+ Errors.ConsistencyCheckFailed()
2345
+ );
2346
+
2347
+ Honk.G1Point memory quotient_commitment = proof.kzgQuotient;
2348
+
2349
+ commitments[boundary] = quotient_commitment;
2350
+ scalars[boundary] = tp.shplonkZ; // evaluation challenge
2351
+
2352
+ PairingInputs memory pair;
2353
+ pair.P_0 = batchMul(commitments, scalars);
2354
+ pair.P_1 = negateInplace(quotient_commitment);
2355
+
2356
+ // Aggregate pairing points (skip if default/infinity — no recursive verification occurred)
2357
+ if (!arePairingPointsDefault(proof.pairingPointObject)) {
2358
+ Fr recursionSeparator = generateRecursionSeparator(proof.pairingPointObject, pair.P_0, pair.P_1);
2359
+ (Honk.G1Point memory P_0_other, Honk.G1Point memory P_1_other) = convertPairingPointsToG1(proof.pairingPointObject);
2360
+
2361
+ // Validate the points from the proof are on the curve
2362
+ rejectPointAtInfinity(P_0_other);
2363
+ rejectPointAtInfinity(P_1_other);
2364
+
2365
+ // accumulate with aggregate points in proof
2366
+ pair.P_0 = mulWithSeperator(pair.P_0, P_0_other, recursionSeparator);
2367
+ pair.P_1 = mulWithSeperator(pair.P_1, P_1_other, recursionSeparator);
2368
+ }
2369
+
2370
+ return pairing(pair.P_0, pair.P_1);
2371
+ }
2372
+
2373
+ function checkEvalsConsistency(
2374
+ Fr[LIBRA_EVALUATIONS] memory libraPolyEvals,
2375
+ Fr geminiR,
2376
+ Fr[CONST_PROOF_SIZE_LOG_N] memory uChallenges,
2377
+ Fr libraEval
2378
+ ) internal view returns (bool check) {
2379
+ Fr one = Fr.wrap(1);
2380
+ Fr vanishingPolyEval = geminiR.pow(SUBGROUP_SIZE) - one;
2381
+ require(vanishingPolyEval != Fr.wrap(0), Errors.GeminiChallengeInSubgroup());
2382
+
2383
+ SmallSubgroupIpaIntermediates memory mem;
2384
+ mem.challengePolyLagrange[0] = one;
2385
+ for (uint256 round = 0; round < $LOG_N; round++) {
2386
+ uint256 currIdx = 1 + LIBRA_UNIVARIATES_LENGTH * round;
2387
+ mem.challengePolyLagrange[currIdx] = one;
2388
+ for (uint256 idx = currIdx + 1; idx < currIdx + LIBRA_UNIVARIATES_LENGTH; idx++) {
2389
+ mem.challengePolyLagrange[idx] = mem.challengePolyLagrange[idx - 1] * uChallenges[round];
2390
+ }
2391
+ }
2392
+
2393
+ mem.rootPower = one;
2394
+ mem.challengePolyEval = Fr.wrap(0);
2395
+ for (uint256 idx = 0; idx < SUBGROUP_SIZE; idx++) {
2396
+ mem.denominators[idx] = mem.rootPower * geminiR - one;
2397
+ mem.denominators[idx] = mem.denominators[idx].invert();
2398
+ mem.challengePolyEval = mem.challengePolyEval + mem.challengePolyLagrange[idx] * mem.denominators[idx];
2399
+ mem.rootPower = mem.rootPower * SUBGROUP_GENERATOR_INVERSE;
2400
+ }
2401
+
2402
+ Fr numerator = vanishingPolyEval * Fr.wrap(SUBGROUP_SIZE).invert();
2403
+ mem.challengePolyEval = mem.challengePolyEval * numerator;
2404
+ mem.lagrangeFirst = mem.denominators[0] * numerator;
2405
+ mem.lagrangeLast = mem.denominators[SUBGROUP_SIZE - 1] * numerator;
2406
+
2407
+ mem.diff = mem.lagrangeFirst * libraPolyEvals[2];
2408
+
2409
+ mem.diff =
2410
+ mem.diff +
2411
+ (geminiR - SUBGROUP_GENERATOR_INVERSE) *
2412
+ (libraPolyEvals[1] - libraPolyEvals[2] - libraPolyEvals[0] * mem.challengePolyEval);
2413
+ mem.diff = mem.diff + mem.lagrangeLast * (libraPolyEvals[2] - libraEval) - vanishingPolyEval * libraPolyEvals[3];
2414
+
2415
+ check = mem.diff == Fr.wrap(0);
2416
+ }
2417
+
2418
+ // This implementation is the same as above with different constants
2419
+ function batchMul(Honk.G1Point[] memory base, Fr[] memory scalars) internal view returns (Honk.G1Point memory result) {
2420
+ uint256 limit = $MSMSize;
2421
+
2422
+ // Identity bases are accepted: VK selector/table polys may be identically zero,
2423
+ // and the ecAdd/ecMul precompiles treat (0,0) as the additive identity per EIP-196.
2424
+ // Soundness against an attacker substituting (0,0) for a non-zero commitment is
2425
+ // upheld by sumcheck/Shplemini, which would fail on inconsistent evaluations.
2426
+
2427
+ bool success = true;
2428
+ assembly {
2429
+ let free := mload(0x40)
2430
+
2431
+ let count := 0x01
2432
+ for {} lt(count, add(limit, 1)) {
2433
+ count := add(count, 1)
2434
+ } {
2435
+ // Get loop offsets
2436
+ let base_base := add(base, mul(count, 0x20))
2437
+ let scalar_base := add(scalars, mul(count, 0x20))
2438
+
2439
+ mstore(add(free, 0x40), mload(mload(base_base)))
2440
+ mstore(add(free, 0x60), mload(add(0x20, mload(base_base))))
2441
+ // Add scalar
2442
+ mstore(add(free, 0x80), mload(scalar_base))
2443
+
2444
+ success := and(success, staticcall(gas(), 7, add(free, 0x40), 0x60, add(free, 0x40), 0x40))
2445
+ // accumulator = accumulator + accumulator_2
2446
+ success := and(success, staticcall(gas(), 6, free, 0x80, free, 0x40))
2447
+ }
2448
+
2449
+ // Return the result
2450
+ mstore(result, mload(free))
2451
+ mstore(add(result, 0x20), mload(add(free, 0x20)))
2452
+ }
2453
+
2454
+ require(success, Errors.ShpleminiFailed());
2455
+ }
2456
+
2457
+ // Calculate proof size based on log_n (matching UltraKeccakZKFlavor formula)
2458
+ function calculateProofSize(uint256 logN) internal pure returns (uint256) {
2459
+ // Witness and Libra commitments
2460
+ uint256 proofLength = NUM_WITNESS_ENTITIES * NUM_ELEMENTS_COMM; // witness commitments
2461
+ proofLength += NUM_ELEMENTS_COMM * 3; // Libra concat, grand sum, quotient comms
2462
+
2463
+ // Sumcheck
2464
+ proofLength += logN * ZK_BATCHED_RELATION_PARTIAL_LENGTH * NUM_ELEMENTS_FR; // sumcheck univariates
2465
+ proofLength += NUMBER_OF_ENTITIES_ZK * NUM_ELEMENTS_FR; // sumcheck evaluations
2466
+
2467
+ // Libra and Gemini
2468
+ proofLength += NUM_ELEMENTS_FR * 2; // Libra sum, claimed eval
2469
+ proofLength += logN * NUM_ELEMENTS_FR; // Gemini a evaluations
2470
+ proofLength += NUM_LIBRA_EVALUATIONS * NUM_ELEMENTS_FR; // libra evaluations
2471
+
2472
+ // PCS commitments
2473
+ proofLength += (logN - 1) * NUM_ELEMENTS_COMM; // Gemini Fold commitments
2474
+ proofLength += NUM_ELEMENTS_COMM * 2; // Shplonk Q and KZG W commitments
2475
+
2476
+ // Pairing points
2477
+ proofLength += PAIRING_POINTS_SIZE; // pairing inputs carried on public inputs
2478
+
2479
+ return proofLength * 32;
2480
+ }
2481
+
2482
+ function loadVerificationKey() internal pure virtual returns (Honk.VerificationKey memory);
2483
+ }
2484
+
2485
+ contract HonkVerifier is BaseZKHonkVerifier(N, LOG_N, VK_HASH, NUMBER_OF_PUBLIC_INPUTS) {
2486
+ constructor() {
2487
+ validateVerificationKey(HonkVerificationKey.loadVerificationKey());
2488
+ }
2489
+
2490
+ function loadVerificationKey() internal pure override returns (Honk.VerificationKey memory) {
2491
+ return HonkVerificationKey.loadVerificationKey();
2492
+ }
2493
+ }