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