14static const char HONK_ZK_CONTRACT_SOURCE[] = R
"(
15pragma solidity ^0.8.27;
18 function verify(bytes calldata _proof, bytes32[] calldata _publicInputs) external view returns (bool);
23using {add as +} for Fr global;
24using {sub as -} for Fr global;
25using {mul as *} for Fr global;
27using {exp as ^} for Fr global;
28using {notEqual as !=} for Fr global;
29using {equal as ==} for Fr global;
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);
42 function from(uint256 value) internal pure returns (Fr) {
44 return Fr.wrap(value % MODULUS);
48 function fromBytes32(bytes32 value) internal pure returns (Fr) {
50 return Fr.wrap(uint256(value) % MODULUS);
54 function toBytes32(Fr value) internal pure returns (bytes32) {
56 return bytes32(Fr.unwrap(value));
60 function invert(Fr value) internal view returns (Fr) {
61 uint256 v = Fr.unwrap(value);
64 // Call the modexp precompile to invert in the field
66 let free := mload(0x40)
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)
78 mstore(0x40, add(free, 0x80))
81 return Fr.wrap(result);
84 function pow(Fr base, uint256 v) internal view returns (Fr) {
85 uint256 b = Fr.unwrap(base);
88 // Call the modexp precompile to invert in the field
90 let free := mload(0x40)
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)
101 result := mload(0x00)
102 mstore(0x40, add(free, 0x80))
105 return Fr.wrap(result);
108 function div(Fr numerator, Fr denominator) internal view returns (Fr) {
110 return numerator * invert(denominator);
114 function sqr(Fr value) internal pure returns (Fr) {
116 return value * value;
120 function unwrap(Fr value) internal pure returns (uint256) {
122 return Fr.unwrap(value);
126 function neg(Fr value) internal pure returns (Fr) {
128 return Fr.wrap(MODULUS - Fr.unwrap(value));
134function add(Fr a, Fr b) pure returns (Fr) {
136 return Fr.wrap(addmod(Fr.unwrap(a), Fr.unwrap(b), MODULUS));
140function mul(Fr a, Fr b) pure returns (Fr) {
142 return Fr.wrap(mulmod(Fr.unwrap(a), Fr.unwrap(b), MODULUS));
146function sub(Fr a, Fr b) pure returns (Fr) {
148 return Fr.wrap(addmod(Fr.unwrap(a), MODULUS - Fr.unwrap(b), MODULUS));
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) {
161function notEqual(Fr a, Fr b) pure returns (bool) {
163 return Fr.unwrap(a) != Fr.unwrap(b);
167function equal(Fr a, Fr b) pure returns (bool) {
169 return Fr.unwrap(a) == Fr.unwrap(b);
173uint256 constant CONST_PROOF_SIZE_LOG_N = 28;
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;
187uint256 constant FIELD_ELEMENT_SIZE = 0x20;
188uint256 constant GROUP_ELEMENT_SIZE = 0x40;
190// Powers of alpha used to batch subrelations (alpha, alpha^2, ..., alpha^(NUM_SUBRELATIONS-1))
191uint256 constant NUMBER_OF_ALPHAS = NUMBER_OF_SUBRELATIONS - 1;
207 Q_POSEIDON2_EXTERNAL,
208 Q_POSEIDON2_INTERNAL,
244 struct VerificationKey {
247 uint256 logCircuitSize;
248 uint256 publicInputsSize;
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;
274 // Precomputed lookup table
279 // Fixed first and last
280 G1Point lagrangeFirst;
281 G1Point lagrangeLast;
284 struct RelationParameters {
290 Fr publicInputsDelta;
294 // Pairing point object
295 Fr[PAIRING_POINTS_SIZE] pairingPointObject;
301 // Lookup helpers - Permutations
303 // Lookup helpers - logup
304 G1Point lookupReadCounts;
305 G1Point lookupReadTags;
306 G1Point lookupInverses;
308 Fr[BATCHED_RELATION_PARTIAL_LENGTH][CONST_PROOF_SIZE_LOG_N] sumcheckUnivariates;
309 Fr[NUMBER_OF_ENTITIES] sumcheckEvaluations;
311 G1Point[CONST_PROOF_SIZE_LOG_N - 1] geminiFoldComms;
312 Fr[CONST_PROOF_SIZE_LOG_N] geminiAEvaluations;
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
328 // Commitments to logup witness polynomials
329 G1Point lookupReadCounts;
330 G1Point lookupReadTags;
331 G1Point lookupInverses;
332 // Commitment to grand permutation polynomial
334 G1Point[3] libraCommitments;
337 Fr[ZK_BATCHED_RELATION_PARTIAL_LENGTH][CONST_PROOF_SIZE_LOG_N] sumcheckUnivariates;
339 Fr[NUMBER_OF_ENTITIES_ZK] sumcheckEvaluations; // Includes gemini_masking_poly eval at index 0 (first position)
341 G1Point[CONST_PROOF_SIZE_LOG_N - 1] geminiFoldComms;
342 Fr[CONST_PROOF_SIZE_LOG_N] geminiAEvaluations;
343 Fr[4] libraPolyEvals;
349// ZKTranscript library to generate fiat shamir challenges, the ZK transcript only differest
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;
358 Fr[CONST_PROOF_SIZE_LOG_N] sumCheckUChallenges;
365 Fr publicInputsDelta;
368library ZKTranscriptLib {
369 function generateTranscript(
370 Honk.ZKProof memory proof,
371 bytes32[] calldata publicInputs,
373 uint256 publicInputsSize,
375 ) external pure returns (ZKTranscript memory t) {
376 Fr previousChallenge;
377 (t.relationParameters, previousChallenge) =
378 generateRelationParametersChallenges(proof, publicInputs, vkHash, publicInputsSize, previousChallenge);
380 (t.alphas, previousChallenge) = generateAlphaChallenges(previousChallenge, proof);
382 (t.gateChallenges, previousChallenge) = generateGateChallenges(previousChallenge, logN);
383 (t.libraChallenge, previousChallenge) = generateLibraChallenge(previousChallenge, proof);
384 (t.sumCheckUChallenges, previousChallenge) = generateSumcheckChallenges(proof, previousChallenge, logN);
386 (t.rho, previousChallenge) = generateRhoChallenge(proof, previousChallenge);
388 (t.geminiR, previousChallenge) = generateGeminiRChallenge(proof, previousChallenge, logN);
390 (t.shplonkNu, previousChallenge) = generateShplonkNuChallenge(proof, previousChallenge, logN);
392 (t.shplonkZ, previousChallenge) = generateShplonkZChallenge(proof, previousChallenge);
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));
405 function generateRelationParametersChallenges(
406 Honk.ZKProof memory proof,
407 bytes32[] calldata publicInputs,
409 uint256 publicInputsSize,
411 ) internal pure returns (Honk.RelationParameters memory rp, Fr nextPreviousChallenge) {
412 (rp.eta, previousChallenge) = generateEtaChallenge(proof, publicInputs, vkHash, publicInputsSize);
414 (rp.beta, rp.gamma, nextPreviousChallenge) = generateBetaGammaChallenges(previousChallenge, proof);
417 function generateEtaChallenge(
418 Honk.ZKProof memory proof,
419 bytes32[] calldata publicInputs,
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);
427 for (uint256 i = 0; i < publicInputsSize - PAIRING_POINTS_SIZE; i++) {
428 round0[1 + i] = bytes32(publicInputs[i]);
430 for (uint256 i = 0; i < PAIRING_POINTS_SIZE; i++) {
431 round0[1 + publicInputsSize - PAIRING_POINTS_SIZE + i] = FrLib.toBytes32(proof.pairingPointObject[i]);
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);
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);
447 previousChallenge = FrLib.fromBytes32(keccak256(abi.encodePacked(round0)));
448 (eta,) = splitChallenge(previousChallenge);
451 function generateBetaGammaChallenges(Fr previousChallenge, Honk.ZKProof memory proof)
454 returns (Fr beta, Fr gamma, Fr nextPreviousChallenge)
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);
465 nextPreviousChallenge = FrLib.fromBytes32(keccak256(abi.encodePacked(round1)));
466 (beta, gamma) = splitChallenge(nextPreviousChallenge);
469 // Alpha challenges non-linearise the gate contributions
470 function generateAlphaChallenges(Fr previousChallenge, Honk.ZKProof memory proof)
473 returns (Fr[NUMBER_OF_ALPHAS] memory alphas, Fr nextPreviousChallenge)
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;
483 nextPreviousChallenge = FrLib.fromBytes32(keccak256(abi.encodePacked(alpha0)));
485 (alpha,) = splitChallenge(nextPreviousChallenge);
487 // Compute powers of alpha for batching subrelations
489 for (uint256 i = 1; i < NUMBER_OF_ALPHAS; i++) {
490 alphas[i] = alphas[i - 1] * alpha;
494 function generateGateChallenges(Fr previousChallenge, uint256 logN)
497 returns (Fr[CONST_PROOF_SIZE_LOG_N] memory gateChallenges, Fr nextPreviousChallenge)
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];
504 nextPreviousChallenge = previousChallenge;
507 function generateLibraChallenge(Fr previousChallenge, Honk.ZKProof memory proof)
510 returns (Fr libraChallenge, Fr nextPreviousChallenge)
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);
522 function generateSumcheckChallenges(Honk.ZKProof memory proof, Fr prevChallenge, uint256 logN)
525 returns (Fr[CONST_PROOF_SIZE_LOG_N] memory sumcheckChallenges, Fr nextPreviousChallenge)
527 for (uint256 i = 0; i < logN; i++) {
528 Fr[ZK_BATCHED_RELATION_PARTIAL_LENGTH + 1] memory univariateChal;
529 univariateChal[0] = prevChallenge;
531 for (uint256 j = 0; j < ZK_BATCHED_RELATION_PARTIAL_LENGTH; j++) {
532 univariateChal[j + 1] = proof.sumcheckUnivariates[i][j];
534 prevChallenge = FrLib.fromBytes32(keccak256(abi.encodePacked(univariateChal)));
536 (sumcheckChallenges[i],) = splitChallenge(prevChallenge);
538 nextPreviousChallenge = prevChallenge;
541 // We add Libra claimed eval + 2 libra commitments (grand_sum, quotient)
542 function generateRhoChallenge(Honk.ZKProof memory proof, Fr prevChallenge)
545 returns (Fr rho, Fr nextPreviousChallenge)
547 uint256[NUMBER_OF_ENTITIES_ZK + 6] memory rhoChallengeElements;
548 rhoChallengeElements[0] = Fr.unwrap(prevChallenge);
550 for (i = 1; i <= NUMBER_OF_ENTITIES_ZK; i++) {
551 rhoChallengeElements[i] = Fr.unwrap(proof.sumcheckEvaluations[i - 1]);
553 rhoChallengeElements[i] = Fr.unwrap(proof.libraEvaluation);
555 rhoChallengeElements[i] = proof.libraCommitments[1].x;
556 rhoChallengeElements[i + 1] = proof.libraCommitments[1].y;
558 rhoChallengeElements[i] = proof.libraCommitments[2].x;
559 rhoChallengeElements[i + 1] = proof.libraCommitments[2].y;
561 nextPreviousChallenge = FrLib.fromBytes32(keccak256(abi.encodePacked(rhoChallengeElements)));
562 (rho,) = splitChallenge(nextPreviousChallenge);
565 function generateGeminiRChallenge(Honk.ZKProof memory proof, Fr prevChallenge, uint256 logN)
568 returns (Fr geminiR, Fr nextPreviousChallenge)
570 uint256[] memory gR = new uint256[]((logN - 1) * 2 + 1);
571 gR[0] = Fr.unwrap(prevChallenge);
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;
578 nextPreviousChallenge = FrLib.fromBytes32(keccak256(abi.encodePacked(gR)));
580 (geminiR,) = splitChallenge(nextPreviousChallenge);
583 function generateShplonkNuChallenge(Honk.ZKProof memory proof, Fr prevChallenge, uint256 logN)
586 returns (Fr shplonkNu, Fr nextPreviousChallenge)
588 uint256[] memory shplonkNuChallengeElements = new uint256[](logN + 1 + 4);
589 shplonkNuChallengeElements[0] = Fr.unwrap(prevChallenge);
591 for (uint256 i = 1; i <= logN; i++) {
592 shplonkNuChallengeElements[i] = Fr.unwrap(proof.geminiAEvaluations[i - 1]);
595 uint256 libraIdx = 0;
596 for (uint256 i = logN + 1; i <= logN + 4; i++) {
597 shplonkNuChallengeElements[i] = Fr.unwrap(proof.libraPolyEvals[libraIdx]);
601 nextPreviousChallenge = FrLib.fromBytes32(keccak256(abi.encodePacked(shplonkNuChallengeElements)));
602 (shplonkNu,) = splitChallenge(nextPreviousChallenge);
605 function generateShplonkZChallenge(Honk.ZKProof memory proof, Fr prevChallenge)
608 returns (Fr shplonkZ, Fr nextPreviousChallenge)
610 uint256[3] memory shplonkZChallengeElements;
611 shplonkZChallengeElements[0] = Fr.unwrap(prevChallenge);
613 shplonkZChallengeElements[1] = proof.shplonkQ.x;
614 shplonkZChallengeElements[2] = proof.shplonkQ.y;
616 nextPreviousChallenge = FrLib.fromBytes32(keccak256(abi.encodePacked(shplonkZChallengeElements)));
617 (shplonkZ,) = splitChallenge(nextPreviousChallenge);
620 function loadProof(bytes calldata proof, uint256 logN) internal pure returns (Honk.ZKProof memory p) {
621 uint256 boundary = 0x0;
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;
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;
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;
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;
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;
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;
671 p.libraEvaluation = bytesToFr(proof[boundary:boundary + FIELD_ELEMENT_SIZE]);
672 boundary += FIELD_ELEMENT_SIZE;
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;
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;
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;
692 for (uint256 i = 0; i < 4; i++) {
693 p.libraPolyEvals[i] = bytesToFr(proof[boundary:boundary + FIELD_ELEMENT_SIZE]);
694 boundary += FIELD_ELEMENT_SIZE;
698 p.shplonkQ = bytesToG1Point(proof[boundary:boundary + GROUP_ELEMENT_SIZE]);
699 boundary += GROUP_ELEMENT_SIZE;
701 p.kzgQuotient = bytesToG1Point(proof[boundary:boundary + GROUP_ELEMENT_SIZE]);
705// Field arithmetic libraries
707library RelationsLib {
708 Fr internal constant GRUMPKIN_CURVE_B_PARAMETER_NEGATED = Fr.wrap(17); // -(-17)
710 function accumulateRelationEvaluations(
711 Fr[NUMBER_OF_ENTITIES] memory purportedEvaluations,
712 Honk.RelationParameters memory rp,
713 Fr[NUMBER_OF_ALPHAS] memory subrelationChallenges,
715 ) internal pure returns (Fr accumulator) {
716 Fr[NUMBER_OF_SUBRELATIONS] memory evaluations;
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);
729 // batch the subrelations with the precomputed alpha powers to obtain the full honk relation
730 accumulator = scaleAndBatchSubrelations(evaluations, subrelationChallenges);
738 function wire(Fr[NUMBER_OF_ENTITIES] memory p, WIRE _wire) internal pure returns (Fr) {
739 return p[uint256(_wire)];
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,
754 Fr q_arith = wire(p, WIRE.Q_ARITH);
756 Fr neg_half = Fr.wrap(NEG_HALF_MODULO_P);
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;
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;
778 function accumulatePermutationRelation(
779 Fr[NUMBER_OF_ENTITIES] memory p,
780 Honk.RelationParameters memory rp,
781 Fr[NUMBER_OF_SUBRELATIONS] memory evals,
784 Fr grand_product_numerator;
785 Fr grand_product_denominator;
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);
793 grand_product_numerator = num;
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);
801 grand_product_denominator = den;
806 Fr acc = (wire(p, WIRE.Z_PERM) + wire(p, WIRE.LAGRANGE_FIRST)) * grand_product_numerator;
809 - ((wire(p, WIRE.Z_PERM_SHIFT) + (wire(p, WIRE.LAGRANGE_LAST) * rp.publicInputsDelta))
810 * grand_product_denominator);
811 acc = acc * domainSep;
817 Fr acc = (wire(p, WIRE.LAGRANGE_LAST) * wire(p, WIRE.Z_PERM_SHIFT)) * domainSep;
822 function accumulateLogDerivativeLookupRelation(
823 Fr[NUMBER_OF_ENTITIES] memory p,
824 Honk.RelationParameters memory rp,
825 Fr[NUMBER_OF_SUBRELATIONS] memory evals,
831 // Calculate the write term (the table accumulation)
832 // table_term = table_1 + γ + table_2 * β + table_3 * β² + table_4 * β³
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);
839 // Calculate the read term
840 // lookup_term = derived_entry_1 + γ + derived_entry_2 * β + derived_entry_3 * β² + q_index * β³
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);
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);
851 Fr lookup_inverse = wire(p, WIRE.LOOKUP_INVERSES) * table_term;
852 Fr table_inverse = wire(p, WIRE.LOOKUP_INVERSES) * lookup_term;
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));
858 // Inverse calculated correctly relation
859 Fr accumulatorNone = lookup_term * table_term * wire(p, WIRE.LOOKUP_INVERSES) - inverse_exists_xor;
860 accumulatorNone = accumulatorNone * domainSep;
863 Fr accumulatorOne = wire(p, WIRE.Q_LOOKUP) * lookup_inverse - wire(p, WIRE.LOOKUP_READ_COUNTS) * table_inverse;
865 Fr read_tag = wire(p, WIRE.LOOKUP_READ_TAGS);
867 Fr read_tag_boolean_relation = read_tag * read_tag - read_tag;
869 evals[4] = accumulatorNone;
870 evals[5] = accumulatorOne;
871 evals[6] = read_tag_boolean_relation * domainSep;
874 function accumulateDeltaRangeRelation(
875 Fr[NUMBER_OF_ENTITIES] memory p,
876 Fr[NUMBER_OF_SUBRELATIONS] memory evals,
879 Fr minus_one = ZERO - ONE;
880 Fr minus_two = ZERO - Fr.wrap(2);
881 Fr minus_three = ZERO - Fr.wrap(3);
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);
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;
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;
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;
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;
934 struct EllipticParams {
942 // push accumulators into memory
943 Fr x_double_identity;
946 function accumulateEllipticRelation(
947 Fr[NUMBER_OF_ENTITIES] memory p,
948 Fr[NUMBER_OF_SUBRELATIONS] memory evals,
951 EllipticParams memory ep;
952 ep.x_1 = wire(p, WIRE.W_R);
953 ep.y_1 = wire(p, WIRE.W_O);
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);
960 Fr q_sign = wire(p, WIRE.Q_L);
961 Fr q_is_double = wire(p, WIRE.Q_M);
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);
969 Fr partialEval = domainSep;
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;
977 evals[11] = x_add_identity * partialEval * wire(p, WIRE.Q_ELLIPTIC) * (ONE - q_is_double);
980 // Contribution 11 point addition, x-coordinate check
981 // q_elliptic * (q_sign * y1 + y3)(x2 - x1) + (x3 - x1)(y2 - q_sign * y1) = 0
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);
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
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);
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;
1001 Fr acc = ep.x_double_identity * domainSep * wire(p, WIRE.Q_ELLIPTIC) * q_is_double;
1002 evals[11] = evals[11] + acc;
1005 // Contribution 11 point doubling, y-coordinate check
1006 // (y1 + y1) (2y1) - (3 * x1 * x1)(x1 - x3) = 0
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;
1014 // Parameters used within the Memory Relation
1015 // A struct is used to work around stack too deep. This relation has alot of variables
1017 Fr memory_record_check;
1018 Fr partial_record_check;
1019 Fr next_gate_access_type;
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;
1025 Fr next_gate_access_type_is_boolean;
1026 Fr ROM_consistency_check_identity;
1027 Fr RAM_consistency_check_identity;
1029 Fr RAM_timestamp_check_identity;
1031 Fr index_is_monotonically_increasing;
1034 function accumulateMemoryRelation(
1035 Fr[NUMBER_OF_ENTITIES] memory p,
1036 Honk.RelationParameters memory rp,
1037 Fr[NUMBER_OF_SUBRELATIONS] memory evals,
1040 MemParams memory ap;
1042 // Compute eta powers locally
1043 Fr eta_two = rp.eta * rp.eta;
1044 Fr eta_three = eta_two * rp.eta;
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);
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);
1113 ap.index_is_monotonically_increasing = ap.index_delta * (ap.index_delta - Fr.wrap(1)); // deg 2
1115 ap.adjacent_values_match_if_adjacent_indices_match = (ap.index_delta * MINUS_ONE + ONE) * ap.record_delta; // deg 2
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
1122 ap.ROM_consistency_check_identity = ap.memory_record_check * (wire(p, WIRE.Q_L) * wire(p, WIRE.Q_R)); // deg 3 or 7
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
1146 // reverse order we could re-use `ap.partial_record_check` 1 - ((w3' * eta + w2') * eta + w1') * eta
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;
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
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
1162 ap.next_gate_access_type_is_boolean =
1163 ap.next_gate_access_type * ap.next_gate_access_type - ap.next_gate_access_type;
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
1171 ap.RAM_consistency_check_identity = ap.access_check * (wire(p, WIRE.Q_O)); // deg 3 or 9
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
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
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;
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);
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
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;
1219 function accumulateNnfRelation(
1220 Fr[NUMBER_OF_ENTITIES] memory p,
1221 Fr[NUMBER_OF_SUBRELATIONS] memory evals,
1224 NnfParams memory ap;
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);
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);
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);
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);
1261 // ((((w2' * 2^14 + w1') * 2^14 + w3) * 2^14 + w2) * 2^14 + w1 - w4) * qm
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);
1274 // ((((w3' * 2^14 + w2') * 2^14 + w1') * 2^14 + w4) * 2^14 + w3 - w4') * qm
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);
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
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;
1295 struct PoseidonExternalParams {
1312 Fr q_pos_by_scaling;
1315 function accumulatePoseidonExternalRelation(
1316 Fr[NUMBER_OF_ENTITIES] memory p,
1317 Fr[NUMBER_OF_SUBRELATIONS] memory evals,
1320 PoseidonExternalParams memory ep;
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);
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
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));
1350 evals[21] = evals[21] + ep.q_pos_by_scaling * (ep.v2 - wire(p, WIRE.W_R_SHIFT));
1352 evals[22] = evals[22] + ep.q_pos_by_scaling * (ep.v3 - wire(p, WIRE.W_O_SHIFT));
1354 evals[23] = evals[23] + ep.q_pos_by_scaling * (ep.v4 - wire(p, WIRE.W_4_SHIFT));
1357 struct PoseidonInternalParams {
1368 Fr q_pos_by_scaling;
1371 function accumulatePoseidonInternalRelation(
1372 Fr[NUMBER_OF_ENTITIES] memory p,
1373 Fr[NUMBER_OF_SUBRELATIONS] memory evals,
1376 PoseidonInternalParams memory ip;
1378 Fr[4] memory INTERNAL_MATRIX_DIAGONAL = [
1379 FrLib.from(0x10dc6e9c006ea38b04b1e03b4bd9490c0d03f98929ca1d7fb56821fd19d3b6e7),
1380 FrLib.from(0x0c28145b6a44df3e0149b3d0a30b3bb599df9756d4dd9b84a86b38cfb45a740b),
1381 FrLib.from(0x00544b8338791518b2c7645a50392798b21f75bb60e3596170067d00141cac15),
1382 FrLib.from(0x222c01175718386f2e2e82eb122789e352e105a3b8fa852613bc534433ee428b)
1385 // add round constants
1386 ip.s1 = wire(p, WIRE.W_L) + wire(p, WIRE.Q_L);
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);
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;
1397 ip.q_pos_by_scaling = wire(p, WIRE.Q_POSEIDON2_INTERNAL) * domainSep;
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));
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));
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));
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));
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];
1420 for (uint256 i = 1; i < NUMBER_OF_SUBRELATIONS; ++i) {
1421 accumulator = accumulator + evaluations[i] * subrelationChallenges[i - 1];
1426// Field arithmetic libraries - prevent littering the code with modmul / addmul
1428library CommitmentSchemeLib {
1431 // Avoid stack too deep
1432 struct ShpleminiIntermediates {
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;
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;
1457 function computeSquares(Fr r, uint256 logN) internal pure returns (Fr[] memory) {
1458 Fr[] memory squares = new Fr[](logN);
1460 for (uint256 i = 1; i < logN; ++i) {
1461 squares[i] = squares[i - 1].sqr();
1465 // Compute the evaluations Aₗ(r^{2ˡ}) for l = 0, ..., m-1
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,
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];
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();
1484 batchedEvalAccumulator = batchedEvalRoundAcc;
1485 foldPosEvaluations[i - 1] = batchedEvalRoundAcc;
1487 return foldPosEvaluations;
1491uint256 constant Q = 21888242871839275222246405745257275088696311157297823662689037894645226208583; // EC group order. F_q
1493function bytes32ToString(bytes32 value) pure returns (string memory result) {
1494 bytes memory alphabet = "0123456789abcdef";
1496 bytes memory str = new bytes(66);
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)];
1503 result = string(str);
1508function bytesToFr(bytes calldata proofSection) pure returns (Fr scalar) {
1509 scalar = FrLib.fromBytes32(bytes32(proofSection));
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
1519function negateInplace(Honk.G1Point memory point) pure returns (Honk.G1Point memory) {
1520 point.y = (Q - point.y) % Q;
1537function convertPairingPointsToG1(Fr[PAIRING_POINTS_SIZE] memory pairingPoints)
1539 returns (Honk.G1Point memory lhs, Honk.G1Point memory rhs)
1541 // P0 (lhs): x = lo + hi << 136
1542 uint256 lhsX = Fr.unwrap(pairingPoints[0]);
1543 lhsX |= Fr.unwrap(pairingPoints[1]) << 136;
1546 uint256 lhsY = Fr.unwrap(pairingPoints[2]);
1547 lhsY |= Fr.unwrap(pairingPoints[3]) << 136;
1550 // P1 (rhs): x = lo + hi << 136
1551 uint256 rhsX = Fr.unwrap(pairingPoints[4]);
1552 rhsX |= Fr.unwrap(pairingPoints[5]) << 136;
1555 uint256 rhsY = Fr.unwrap(pairingPoints[6]);
1556 rhsY |= Fr.unwrap(pairingPoints[7]) << 136;
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
1578 (Honk.G1Point memory proofLhs, Honk.G1Point memory proofRhs) = convertPairingPointsToG1(proofPairingPoints);
1580 uint256[8] memory recursionSeparatorElements;
1583 recursionSeparatorElements[0] = proofLhs.x;
1584 recursionSeparatorElements[1] = proofLhs.y;
1585 recursionSeparatorElements[2] = proofRhs.x;
1586 recursionSeparatorElements[3] = proofRhs.y;
1588 // Accumulator points
1589 recursionSeparatorElements[4] = accLhs.x;
1590 recursionSeparatorElements[5] = accLhs.y;
1591 recursionSeparatorElements[6] = accRhs.x;
1592 recursionSeparatorElements[7] = accRhs.y;
1594 recursionSeparator = FrLib.fromBytes32(keccak256(abi.encodePacked(recursionSeparatorElements)));
1606function mulWithSeperator(Honk.G1Point memory basePoint, Honk.G1Point memory other, Fr recursionSeperator)
1608 returns (Honk.G1Point memory)
1610 Honk.G1Point memory result;
1612 result = ecMul(recursionSeperator, basePoint);
1613 result = ecAdd(result, other);
1626function ecMul(Fr value, Honk.G1Point memory point) view returns (Honk.G1Point memory) {
1627 Honk.G1Point memory result;
1630 let free := mload(0x40)
1631 // Write the point into memory (two 32 byte words)
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)
1641 // free + 0x40| value
1642 mstore(add(free, 0x40), value)
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) {
1650 // Copy the result of the multiplication back into the result memory location.
1653 // result | result.x
1654 // result + 0x20| result.y
1655 mstore(result, mload(free))
1656 mstore(add(result, 0x20), mload(add(free, 0x20)))
1658 mstore(0x40, add(free, 0x60))
1672function ecAdd(Honk.G1Point memory lhs, Honk.G1Point memory rhs) view returns (Honk.G1Point memory) {
1673 Honk.G1Point memory result;
1676 let free := mload(0x40)
1677 // Write lhs into memory (two 32 byte words)
1681 // free + 0x20| lhs.y
1682 mstore(free, mload(lhs))
1683 mstore(add(free, 0x20), mload(add(lhs, 0x20)))
1685 // Write rhs into memory (two 32 byte words)
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)))
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) }
1698 // Copy the result of the addition back into the result memory location.
1701 // result | result.x
1702 // result + 0x20| result.y
1703 mstore(result, mload(free))
1704 mstore(add(result, 0x20), mload(add(free, 0x20)))
1706 mstore(0x40, add(free, 0x80))
1712function validateOnCurve(Honk.G1Point memory point) pure {
1713 uint256 x = point.x;
1714 uint256 y = point.y;
1716 bool success = false;
1718 let xx := mulmod(x, x, Q)
1719 success := eq(mulmod(y, y, Q), addmod(mulmod(x, xx, Q), 3, Q))
1722 require(success, "point is not on the curve");
1725function pairing(Honk.G1Point memory rhs, Honk.G1Point memory lhs) view returns (bool decodedResult) {
1726 bytes memory input = abi.encodePacked(
1730 uint256(0x198e9393920d483a7260bfb731fb5d25f1aa493335a9e71297e485b7aef312c2),
1731 uint256(0x1800deef121f1e76426a00665e5c4479674322d4f75edadd46debd5cd992f6ed),
1732 uint256(0x090689d0585ff075ec9e99ad690c3395bc4b313370b38ef355acdadcd122975b),
1733 uint256(0x12c85ea5db8c6deb4aab71808dcb408fe3d1e7690c43d37b4ce6cc0166fa7daa),
1737 uint256(0x260e01b251f6f1c7e7ff4e580791dee8ea51d87a358e038b4efe30fac09383c1),
1738 uint256(0x0118c4d5b837bcc2bc89b5b398b5974e9f5944073b32078b7e231fec938883b0),
1739 uint256(0x04fc6369f7110fe3d25156c1bb9a72859cf2a04641f99ba4ee413c80da6a5fe4),
1740 uint256(0x22febda3c0c0632a56475b4214e5615e11e6dd3f96e6cea2854a87d4dacc5e55)
1743 (bool success, bytes memory result) = address(0x08).staticcall(input);
1744 decodedResult = success && abi.decode(result, (bool));
1747// Field arithmetic libraries - prevent littering the code with modmul / addmul
1752abstract contract BaseZKHonkVerifier is IVerifier {
1755 uint256 immutable $N;
1756 uint256 immutable $LOG_N;
1757 uint256 immutable $VK_HASH;
1758 uint256 immutable $NUM_PUBLIC_INPUTS;
1759 uint256 immutable $MSMSize;
1761 constructor(uint256 _N, uint256 _logN, uint256 _vkHash, uint256 _numPublicInputs) {
1765 $NUM_PUBLIC_INPUTS = _numPublicInputs;
1766 $MSMSize = NUMBER_UNSHIFTED_ZK + _logN + LIBRA_COMMITMENTS + 2;
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();
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
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
1791 proofLength += logN * ZK_BATCHED_RELATION_PARTIAL_LENGTH * NUM_ELEMENTS_FR; // sumcheck univariates
1792 proofLength += NUMBER_OF_ENTITIES_ZK * NUM_ELEMENTS_FR; // sumcheck evaluations
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
1800 proofLength += (logN - 1) * NUM_ELEMENTS_COMM; // Gemini Fold commitments
1801 proofLength += NUM_ELEMENTS_COMM * 2; // Shplonk Q and KZG W commitments
1804 proofLength += PAIRING_POINTS_SIZE; // pairing inputs carried on public inputs
1809 uint256 constant SHIFTED_COMMITMENTS_START = 30;
1811 function loadVerificationKey() internal pure virtual returns (Honk.VerificationKey memory);
1813 function verify(bytes calldata proof, bytes32[] calldata publicInputs)
1817 returns (bool verified)
1819 // Calculate expected proof size based on $LOG_N
1820 uint256 expectedProofSize = calculateProofSize($LOG_N);
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);
1827 Honk.VerificationKey memory vk = loadVerificationKey();
1828 Honk.ZKProof memory p = ZKTranscriptLib.loadProof(proof, $LOG_N);
1830 if (publicInputs.length != vk.publicInputsSize - PAIRING_POINTS_SIZE) {
1831 revert PublicInputsLengthWrong();
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);
1838 // Derive public input delta
1839 t.relationParameters.publicInputsDelta = computePublicInputDelta(
1841 p.pairingPointObject,
1842 t.relationParameters.beta,
1843 t.relationParameters.gamma, /*pubInputsOffset=*/
1848 if (!verifySumcheck(p, t)) revert SumcheckFailed();
1850 if (!verifyShplemini(p, vk, t)) revert ShpleminiFailed();
1855 uint256 constant PERMUTATION_ARGUMENT_VALUE_SEPARATOR = 1 << 28;
1857 function computePublicInputDelta(
1858 bytes32[] memory publicInputs,
1859 Fr[PAIRING_POINTS_SIZE] memory pairingPointObject,
1863 ) internal view returns (Fr publicInputDelta) {
1864 Fr numerator = Fr.wrap(1);
1865 Fr denominator = Fr.wrap(1);
1867 Fr numeratorAcc = gamma + (beta * FrLib.from(PERMUTATION_ARGUMENT_VALUE_SEPARATOR + offset));
1868 Fr denominatorAcc = gamma - (beta * FrLib.from(offset + 1));
1871 for (uint256 i = 0; i < $NUM_PUBLIC_INPUTS - PAIRING_POINTS_SIZE; i++) {
1872 Fr pubInput = FrLib.fromBytes32(publicInputs[i]);
1874 numerator = numerator * (numeratorAcc + pubInput);
1875 denominator = denominator * (denominatorAcc + pubInput);
1877 numeratorAcc = numeratorAcc + beta;
1878 denominatorAcc = denominatorAcc - beta;
1881 for (uint256 i = 0; i < PAIRING_POINTS_SIZE; i++) {
1882 Fr pubInput = pairingPointObject[i];
1884 numerator = numerator * (numeratorAcc + pubInput);
1885 denominator = denominator * (denominatorAcc + pubInput);
1887 numeratorAcc = numeratorAcc + beta;
1888 denominatorAcc = denominatorAcc - beta;
1892 // Fr delta = numerator / denominator; // TOOO: batch invert later?
1893 publicInputDelta = FrLib.div(numerator, denominator);
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);
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();
1906 Fr roundChallenge = tp.sumCheckUChallenges[round];
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)));
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
1921 Fr grandHonkRelationSum = RelationsLib.accumulateRelationEvaluations(
1922 relationsEvaluations, tp.relationParameters, tp.alphas, powPartialEvaluation
1925 Fr evaluation = Fr.wrap(1);
1926 for (uint256 i = 2; i < $LOG_N; i++) {
1927 evaluation = evaluation * tp.sumCheckUChallenges[i];
1930 grandHonkRelationSum =
1931 grandHonkRelationSum * (Fr.wrap(1) - evaluation) + proof.libraEvaluation * tp.libraChallenge;
1932 verified = (grandHonkRelationSum == roundTargetSum);
1935 // Return the new target sum for the next sumcheck round
1936 function computeNextTargetSum(Fr[ZK_BATCHED_RELATION_PARTIAL_LENGTH] memory roundUnivariates, Fr roundChallenge)
1939 returns (Fr targetSum)
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)
1953 // To compute the next target sum, we evaluate the given univariate at a point u (challenge).
1955 // Performing Barycentric evaluations
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));
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)));
1967 for (uint256 i = 0; i < ZK_BATCHED_RELATION_PARTIAL_LENGTH; ++i) {
1968 targetSum = targetSum + roundUnivariates[i] * denominatorInverses[i];
1971 // Scale the sum by the value of B(x)
1972 targetSum = targetSum * numeratorValue;
1975 uint256 constant LIBRA_COMMITMENTS = 3;
1976 uint256 constant LIBRA_EVALUATIONS = 4;
1977 uint256 constant LIBRA_UNIVARIATES_LENGTH = 9;
1979 struct PairingInputs {
1984 function verifyShplemini(Honk.ZKProof memory proof, Honk.VerificationKey memory vk, ZKTranscript memory tp)
1987 returns (bool verified)
1989 CommitmentSchemeLib.ShpleminiIntermediates memory mem; // stack
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);
1997 mem.posInvertedDenominator = (tp.shplonkZ - powers_of_evaluation_challenge[0]).invert();
1998 mem.negInvertedDenominator = (tp.shplonkZ + powers_of_evaluation_challenge[0]).invert();
2000 mem.unshiftedScalar = mem.posInvertedDenominator + (tp.shplonkNu * mem.negInvertedDenominator);
2002 tp.geminiR.invert() * (mem.posInvertedDenominator - (tp.shplonkNu * mem.negInvertedDenominator));
2004 scalars[0] = Fr.wrap(1);
2005 commitments[0] = proof.shplonkQ;
2007 /* Batch multivariate opening claims, shifted and unshifted
2008 * The vector of scalars is populated as follows:
2011 * - \left(\frac{1}{z-r} + \nu \times \frac{1}{z+r}\right),
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),
2016 * - \rho^{k+m-1} \times \frac{1}{r} \times \left(\frac{1}{z-r} - \nu \times \frac{1}{z+r}\right)
2020 * The following vector is concatenated to the vector of commitments:
2022 * f_0, \ldots, f_{m-1}, f_{\text{shift}, 0}, \ldots, f_{\text{shift}, k-1}
2025 * Simultaneously, the evaluation of the multilinear polynomial
2027 * \sum \rho^i \cdot f_i + \sum \rho^{i+k} \cdot f_{\text{shift}, i}
2029 * at the challenge point \f$ (u_0,\ldots, u_{n-1}) \f$ is computed.
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$.
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);
2039 mem.unshiftedScalarNeg = mem.unshiftedScalar.neg();
2040 mem.shiftedScalarNeg = mem.shiftedScalar.neg();
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;
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;
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;
2065 commitments[1] = proof.geminiMaskingPoly;
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;
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;
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
2110 * 1. Moves the vector
2112 * \left( \text{com}(A_1), \text{com}(A_2), \ldots, \text{com}(A_{n-1}) \right)
2114 * to the 'commitments' vector.
2116 * 2. Computes the scalars:
2118 * \frac{\nu^{2}}{z + r^2}, \frac{\nu^3}{z + r^4}, \ldots, \frac{\nu^{n-1}}{z + r^{2^{n-1}}}
2120 * and places them into the 'scalars' vector.
2122 * 3. Accumulates the summands of the constant term:
2124 * \sum_{i=2}^{n-1} \frac{\nu^{i} \cdot A_i(-r^{2^i})}{z + r^{2^i}}
2126 * and adds them to the 'constant_term_accumulator'.
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,
2139 mem.constantTermAccumulator = foldPosEvaluations[0] * mem.posInvertedDenominator;
2140 mem.constantTermAccumulator =
2141 mem.constantTermAccumulator + (proof.geminiAEvaluations[0] * tp.shplonkNu * mem.negInvertedDenominator);
2143 mem.batchingChallenge = tp.shplonkNu.sqr();
2144 uint256 boundary = NUMBER_UNSHIFTED_ZK + 1;
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);
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();
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();
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;
2167 // Update the running power of v
2168 mem.batchingChallenge = mem.batchingChallenge * tp.shplonkNu * tp.shplonkNu;
2170 commitments[boundary + i] = proof.geminiFoldComms[i];
2173 boundary += $LOG_N - 1;
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];
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];
2188 scalars[boundary] = mem.batchingScalars[0];
2189 scalars[boundary + 1] = mem.batchingScalars[1] + mem.batchingScalars[2];
2190 scalars[boundary + 2] = mem.batchingScalars[3];
2192 for (uint256 i = 0; i < LIBRA_COMMITMENTS; i++) {
2193 commitments[boundary++] = proof.libraCommitments[i];
2196 commitments[boundary] = Honk.G1Point({x: 1, y: 2});
2197 scalars[boundary++] = mem.constantTermAccumulator;
2199 if (!checkEvalsConsistency(proof.libraPolyEvals, tp.geminiR, tp.sumCheckUChallenges, proof.libraEvaluation)) {
2200 revert ConsistencyCheckFailed();
2203 Honk.G1Point memory quotient_commitment = proof.kzgQuotient;
2205 commitments[boundary] = quotient_commitment;
2206 scalars[boundary] = tp.shplonkZ; // evaluation challenge
2208 PairingInputs memory pair;
2209 pair.P_0 = batchMul(commitments, scalars);
2210 pair.P_1 = negateInplace(quotient_commitment);
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);
2217 // Validate the points from the proof are on the curve
2218 validateOnCurve(P_0_other);
2219 validateOnCurve(P_1_other);
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);
2225 return pairing(pair.P_0, pair.P_1);
2228 struct SmallSubgroupIpaIntermediates {
2229 Fr[SUBGROUP_SIZE] challengePolyLagrange;
2230 Fr challengePolyEval;
2234 Fr[SUBGROUP_SIZE] denominators; // this has to disappear
2238 function checkEvalsConsistency(
2239 Fr[LIBRA_EVALUATIONS] memory libraPolyEvals,
2241 Fr[CONST_PROOF_SIZE_LOG_N] memory uChallenges,
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();
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];
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;
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;
2274 mem.diff = mem.lagrangeFirst * libraPolyEvals[2];
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];
2280 check = mem.diff == Fr.wrap(0);
2283 // This implementation is the same as above with different constants
2284 function batchMul(Honk.G1Point[] memory base, Fr[] memory scalars)
2287 returns (Honk.G1Point memory result)
2289 uint256 limit = $MSMSize;
2291 // Validate all points are on the curve
2292 for (uint256 i = 0; i < limit; ++i) {
2293 validateOnCurve(base[i]);
2296 bool success = true;
2298 let free := mload(0x40)
2301 for {} lt(count, add(limit, 1)) { count := add(count, 1) } {
2303 let base_base := add(base, mul(count, 0x20))
2304 let scalar_base := add(scalars, mul(count, 0x20))
2306 mstore(add(free, 0x40), mload(mload(base_base)))
2307 mstore(add(free, 0x60), mload(add(0x20, mload(base_base))))
2309 mstore(add(free, 0x80), mload(scalar_base))
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))
2316 // Return the result
2317 mstore(result, mload(free))
2318 mstore(add(result, 0x20), mload(add(free, 0x20)))
2321 require(success, ShpleminiFailed());
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();
2334 std::ostringstream stream;
2336 return stream.str() + HONK_ZK_CONTRACT_SOURCE;
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)