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