diff --git a/Cargo.lock b/Cargo.lock index 3c30010..d3f2233 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3071,6 +3071,20 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "ziren-groth16-export" +version = "0.1.0" +dependencies = [ + "anyhow", + "bincode", + "serde_json", + "zkm-core-executor", + "zkm-core-machine", + "zkm-pcs", + "zkm-primitives", + "zkm-prover", +] + [[package]] name = "ziren-shrink-export" version = "0.1.0" @@ -3124,7 +3138,7 @@ dependencies = [ [[package]] name = "zkm-core-executor" version = "2.0.0" -source = "git+https://github.com/ProjectZKM/Ziren.git?branch=feat%2Fkeccak-terminal-evm#0116b8620e1b1354e3260d6bf01e6d715f60b911" +source = "git+https://github.com/ProjectZKM/Ziren.git?branch=feat%2Fkeccak-terminal-evm#d1932fd9a7efd5c17d7cfae1b3e98ab63cfbd835" dependencies = [ "anyhow", "bincode", @@ -3163,7 +3177,7 @@ dependencies = [ [[package]] name = "zkm-core-jit" version = "2.0.0" -source = "git+https://github.com/ProjectZKM/Ziren.git?branch=feat%2Fkeccak-terminal-evm#0116b8620e1b1354e3260d6bf01e6d715f60b911" +source = "git+https://github.com/ProjectZKM/Ziren.git?branch=feat%2Fkeccak-terminal-evm#d1932fd9a7efd5c17d7cfae1b3e98ab63cfbd835" dependencies = [ "dynasmrt", "libc", @@ -3176,7 +3190,7 @@ dependencies = [ [[package]] name = "zkm-core-machine" version = "2.0.0" -source = "git+https://github.com/ProjectZKM/Ziren.git?branch=feat%2Fkeccak-terminal-evm#0116b8620e1b1354e3260d6bf01e6d715f60b911" +source = "git+https://github.com/ProjectZKM/Ziren.git?branch=feat%2Fkeccak-terminal-evm#d1932fd9a7efd5c17d7cfae1b3e98ab63cfbd835" dependencies = [ "bincode", "cfg-if", @@ -3226,7 +3240,7 @@ dependencies = [ [[package]] name = "zkm-curves" version = "2.0.0" -source = "git+https://github.com/ProjectZKM/Ziren.git?branch=feat%2Fkeccak-terminal-evm#0116b8620e1b1354e3260d6bf01e6d715f60b911" +source = "git+https://github.com/ProjectZKM/Ziren.git?branch=feat%2Fkeccak-terminal-evm#d1932fd9a7efd5c17d7cfae1b3e98ab63cfbd835" dependencies = [ "cfg-if", "curve25519-dalek", @@ -3250,7 +3264,7 @@ dependencies = [ [[package]] name = "zkm-derive" version = "2.0.0" -source = "git+https://github.com/ProjectZKM/Ziren.git?branch=feat%2Fkeccak-terminal-evm#0116b8620e1b1354e3260d6bf01e6d715f60b911" +source = "git+https://github.com/ProjectZKM/Ziren.git?branch=feat%2Fkeccak-terminal-evm#d1932fd9a7efd5c17d7cfae1b3e98ab63cfbd835" dependencies = [ "proc-macro2", "quote", @@ -3260,7 +3274,7 @@ dependencies = [ [[package]] name = "zkm-pcs" version = "2.0.0" -source = "git+https://github.com/ProjectZKM/Ziren.git?branch=feat%2Fkeccak-terminal-evm#0116b8620e1b1354e3260d6bf01e6d715f60b911" +source = "git+https://github.com/ProjectZKM/Ziren.git?branch=feat%2Fkeccak-terminal-evm#d1932fd9a7efd5c17d7cfae1b3e98ab63cfbd835" dependencies = [ "arrayref", "bincode", @@ -3302,7 +3316,7 @@ dependencies = [ [[package]] name = "zkm-poly" version = "2.0.0" -source = "git+https://github.com/ProjectZKM/Ziren.git?branch=feat%2Fkeccak-terminal-evm#0116b8620e1b1354e3260d6bf01e6d715f60b911" +source = "git+https://github.com/ProjectZKM/Ziren.git?branch=feat%2Fkeccak-terminal-evm#d1932fd9a7efd5c17d7cfae1b3e98ab63cfbd835" dependencies = [ "itertools 0.13.0", "p3-field", @@ -3311,7 +3325,7 @@ dependencies = [ [[package]] name = "zkm-primitives" version = "2.0.0" -source = "git+https://github.com/ProjectZKM/Ziren.git?branch=feat%2Fkeccak-terminal-evm#0116b8620e1b1354e3260d6bf01e6d715f60b911" +source = "git+https://github.com/ProjectZKM/Ziren.git?branch=feat%2Fkeccak-terminal-evm#d1932fd9a7efd5c17d7cfae1b3e98ab63cfbd835" dependencies = [ "bincode", "blake3", @@ -3331,7 +3345,7 @@ dependencies = [ [[package]] name = "zkm-prover" version = "2.0.0" -source = "git+https://github.com/ProjectZKM/Ziren.git?branch=feat%2Fkeccak-terminal-evm#0116b8620e1b1354e3260d6bf01e6d715f60b911" +source = "git+https://github.com/ProjectZKM/Ziren.git?branch=feat%2Fkeccak-terminal-evm#d1932fd9a7efd5c17d7cfae1b3e98ab63cfbd835" dependencies = [ "anyhow", "bincode", @@ -3370,7 +3384,7 @@ dependencies = [ [[package]] name = "zkm-recursion-circuit" version = "2.0.0" -source = "git+https://github.com/ProjectZKM/Ziren.git?branch=feat%2Fkeccak-terminal-evm#0116b8620e1b1354e3260d6bf01e6d715f60b911" +source = "git+https://github.com/ProjectZKM/Ziren.git?branch=feat%2Fkeccak-terminal-evm#d1932fd9a7efd5c17d7cfae1b3e98ab63cfbd835" dependencies = [ "hashbrown 0.14.5", "itertools 0.13.0", @@ -3400,7 +3414,7 @@ dependencies = [ [[package]] name = "zkm-recursion-compiler" version = "2.0.0" -source = "git+https://github.com/ProjectZKM/Ziren.git?branch=feat%2Fkeccak-terminal-evm#0116b8620e1b1354e3260d6bf01e6d715f60b911" +source = "git+https://github.com/ProjectZKM/Ziren.git?branch=feat%2Fkeccak-terminal-evm#d1932fd9a7efd5c17d7cfae1b3e98ab63cfbd835" dependencies = [ "backtrace", "itertools 0.13.0", @@ -3421,7 +3435,7 @@ dependencies = [ [[package]] name = "zkm-recursion-core" version = "2.0.0" -source = "git+https://github.com/ProjectZKM/Ziren.git?branch=feat%2Fkeccak-terminal-evm#0116b8620e1b1354e3260d6bf01e6d715f60b911" +source = "git+https://github.com/ProjectZKM/Ziren.git?branch=feat%2Fkeccak-terminal-evm#d1932fd9a7efd5c17d7cfae1b3e98ab63cfbd835" dependencies = [ "backtrace", "bincode", @@ -3460,7 +3474,7 @@ dependencies = [ [[package]] name = "zkm-recursion-derive" version = "2.0.0" -source = "git+https://github.com/ProjectZKM/Ziren.git?branch=feat%2Fkeccak-terminal-evm#0116b8620e1b1354e3260d6bf01e6d715f60b911" +source = "git+https://github.com/ProjectZKM/Ziren.git?branch=feat%2Fkeccak-terminal-evm#d1932fd9a7efd5c17d7cfae1b3e98ab63cfbd835" dependencies = [ "quote", "syn 1.0.109", @@ -3469,7 +3483,7 @@ dependencies = [ [[package]] name = "zkm-recursion-gnark-ffi" version = "2.0.0" -source = "git+https://github.com/ProjectZKM/Ziren.git?branch=feat%2Fkeccak-terminal-evm#0116b8620e1b1354e3260d6bf01e6d715f60b911" +source = "git+https://github.com/ProjectZKM/Ziren.git?branch=feat%2Fkeccak-terminal-evm#d1932fd9a7efd5c17d7cfae1b3e98ab63cfbd835" dependencies = [ "anyhow", "bincode", diff --git a/Cargo.toml b/Cargo.toml index b448fb5..d7aa006 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,5 +1,5 @@ [workspace] -members = ["crates/ziren-shrink-export"] +members = ["crates/ziren-shrink-export", "crates/ziren-groth16-export"] resolver = "2" [workspace.package] diff --git a/contracts/metis-output-oracle/foundry.toml b/contracts/metis-output-oracle/foundry.toml index fbc1712..880e7e5 100644 --- a/contracts/metis-output-oracle/foundry.toml +++ b/contracts/metis-output-oracle/foundry.toml @@ -6,6 +6,8 @@ optimizer = true optimizer_runs = 200 evm_version = "prague" fs_permissions = [] +remappings = ["@ziren-shared/=../shared/"] +allow_paths = ["../shared"] [fmt] ignore = ["test/metis/Lib_MerkleTree.sol"] diff --git a/contracts/metis-output-oracle/src/MetisOPSuccinctL2OutputOracle.sol b/contracts/metis-output-oracle/src/MetisOPSuccinctL2OutputOracle.sol index 1847948..9b0cd8f 100644 --- a/contracts/metis-output-oracle/src/MetisOPSuccinctL2OutputOracle.sol +++ b/contracts/metis-output-oracle/src/MetisOPSuccinctL2OutputOracle.sol @@ -1,7 +1,7 @@ // SPDX-License-Identifier: MIT pragma solidity ^0.8.30; -import {IZirenShrinkVerifier} from "./interfaces/IZirenShrinkVerifier.sol"; +import {IZirenProofVerifier} from "@ziren-shared/IZirenProofVerifier.sol"; import {MetisAggregationOutputs} from "./lib/Types.sol"; import {IChainStorageContainer, IMVMStateCommitmentChain} from "./metis/IMVMStateCommitmentChain.sol"; import {Lib_OVMCodec} from "./metis/Lib_OVMCodec.sol"; @@ -169,7 +169,7 @@ contract MetisOPSuccinctL2OutputOracle { rangeVkeyCommitment: config.rangeVkeyCommitment, proverAddress: _proverAddress }); - if (!IZirenShrinkVerifier(config.verifier).verify(_proof, sha256(abi.encode(publicValues)))) { + if (!IZirenProofVerifier(config.verifier).verify(_proof, sha256(abi.encode(publicValues)))) { revert InvalidProof(); } diff --git a/contracts/metis-output-oracle/src/interfaces/IZirenShrinkVerifier.sol b/contracts/metis-output-oracle/src/interfaces/IZirenShrinkVerifier.sol deleted file mode 100644 index b5febd8..0000000 --- a/contracts/metis-output-oracle/src/interfaces/IZirenShrinkVerifier.sol +++ /dev/null @@ -1,9 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity ^0.8.30; - -/// @notice Generated entry of contracts/ziren-shrink-verifier. The guest's -/// application key, exit code and recursion root are compiled into -/// the entry, so one deployment serves one approved guest. -interface IZirenShrinkVerifier { - function verify(bytes calldata proofPacket, bytes32 expectedOutputDigest) external view returns (bool); -} diff --git a/contracts/shared/IZirenProofVerifier.sol b/contracts/shared/IZirenProofVerifier.sol new file mode 100644 index 0000000..445184f --- /dev/null +++ b/contracts/shared/IZirenProofVerifier.sol @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.30; + +/// @notice Verifies a proof packet against the output digest the caller expects. +/// The packet layout and how the digest is bound to the proof are defined +/// by the implementing contract. +interface IZirenProofVerifier { + function verify(bytes calldata proofPacket, bytes32 expectedOutputDigest) external view returns (bool); +} diff --git a/contracts/ziren-groth16-verifier/foundry.toml b/contracts/ziren-groth16-verifier/foundry.toml new file mode 100644 index 0000000..880e7e5 --- /dev/null +++ b/contracts/ziren-groth16-verifier/foundry.toml @@ -0,0 +1,13 @@ +[profile.default] +src = "src" +test = "test" +solc_version = "0.8.30" +optimizer = true +optimizer_runs = 200 +evm_version = "prague" +fs_permissions = [] +remappings = ["@ziren-shared/=../shared/"] +allow_paths = ["../shared"] + +[fmt] +ignore = ["test/metis/Lib_MerkleTree.sol"] diff --git a/contracts/ziren-groth16-verifier/src/Groth16Verifier.sol b/contracts/ziren-groth16-verifier/src/Groth16Verifier.sol new file mode 100644 index 0000000..d4e5c8f --- /dev/null +++ b/contracts/ziren-groth16-verifier/src/Groth16Verifier.sol @@ -0,0 +1,549 @@ + +// SPDX-License-Identifier: MIT + +pragma solidity 0.8.30; + +/// @title Groth16 verifier template. +/// @author Remco Bloemen +/// @notice Supports verifying Groth16 proofs. Proofs can be in uncompressed +/// (256 bytes) and compressed (128 bytes) format. A view function is provided +/// to compress proofs. +/// @notice See for further explanation. +contract Groth16Verifier { + + /// Some of the provided public input values are larger than the field modulus. + /// @dev Public input elements are not automatically reduced, as this is can be + /// a dangerous source of bugs. + error PublicInputNotInField(); + + /// The proof is invalid. + /// @dev This can mean that provided Groth16 proof points are not on their + /// curves, that pairing equation fails, or that the proof is not for the + /// provided public input. + error ProofInvalid(); + + // Addresses of precompiles + uint256 constant PRECOMPILE_MODEXP = 0x05; + uint256 constant PRECOMPILE_ADD = 0x06; + uint256 constant PRECOMPILE_MUL = 0x07; + uint256 constant PRECOMPILE_VERIFY = 0x08; + + // Base field Fp order P and scalar field Fr order R. + // For BN254 these are computed as follows: + // t = 4965661367192848881 + // P = 36⋅t⁴ + 36⋅t³ + 24⋅t² + 6⋅t + 1 + // R = 36⋅t⁴ + 36⋅t³ + 18⋅t² + 6⋅t + 1 + uint256 constant P = 0x30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47; + uint256 constant R = 0x30644e72e131a029b85045b68181585d2833e84879b9709143e1f593f0000001; + + // Extension field Fp2 = Fp[i] / (i² + 1) + // Note: This is the complex extension field of Fp with i² = -1. + // Values in Fp2 are represented as a pair of Fp elements (a₀, a₁) as a₀ + a₁⋅i. + // Note: The order of Fp2 elements is *opposite* that of the pairing contract, which + // expects Fp2 elements in order (a₁, a₀). This is also the order in which + // Fp2 elements are encoded in the public interface as this became convention. + + // Constants in Fp + uint256 constant FRACTION_1_2_FP = 0x183227397098d014dc2822db40c0ac2ecbc0b548b438e5469e10460b6c3e7ea4; + uint256 constant FRACTION_27_82_FP = 0x2b149d40ceb8aaae81be18991be06ac3b5b4c5e559dbefa33267e6dc24a138e5; + uint256 constant FRACTION_3_82_FP = 0x2fcd3ac2a640a154eb23960892a85a68f031ca0c8344b23a577dcf1052b9e775; + + // Exponents for inversions and square roots mod P + uint256 constant EXP_INVERSE_FP = 0x30644E72E131A029B85045B68181585D97816A916871CA8D3C208C16D87CFD45; // P - 2 + uint256 constant EXP_SQRT_FP = 0xC19139CB84C680A6E14116DA060561765E05AA45A1C72A34F082305B61F3F52; // (P + 1) / 4; + + // Groth16 alpha point in G1 + uint256 constant ALPHA_X = 20491192805390485299153009773594534940189261866228447918068658471970481763042; + uint256 constant ALPHA_Y = 9383485363053290200918347156157836566562967994039712273449902621266178545958; + + // Groth16 beta point in G2 in powers of i + uint256 constant BETA_NEG_X_0 = 6375614351688725206403948262868962793625744043794305715222011528459656738731; + uint256 constant BETA_NEG_X_1 = 4252822878758300859123897981450591353533073413197771768651442665752259397132; + uint256 constant BETA_NEG_Y_0 = 11383000245469012944693504663162918391286475477077232690815866754273895001727; + uint256 constant BETA_NEG_Y_1 = 41207766310529818958173054109690360505148424997958324311878202295167071904; + + // Groth16 gamma point in G2 in powers of i + uint256 constant GAMMA_NEG_X_0 = 10857046999023057135944570762232829481370756359578518086990519993285655852781; + uint256 constant GAMMA_NEG_X_1 = 11559732032986387107991004021392285783925812861821192530917403151452391805634; + uint256 constant GAMMA_NEG_Y_0 = 13392588948715843804641432497768002650278120570034223513918757245338268106653; + uint256 constant GAMMA_NEG_Y_1 = 17805874995975841540914202342111839520379459829704422454583296818431106115052; + + // Groth16 delta point in G2 in powers of i + uint256 constant DELTA_NEG_X_0 = 11261132216207933765499043549930468317581291754549215555806596536771307869577; + uint256 constant DELTA_NEG_X_1 = 3540462836163114745590798649291612458171584020313305829916122638074038111111; + uint256 constant DELTA_NEG_Y_0 = 12476903909224593844467797379642704505323962419312106061781725027382372396345; + uint256 constant DELTA_NEG_Y_1 = 2229397275628518650110795104909494807331663084618134898818407085962563675538; + + // Constant and public input points + uint256 constant CONSTANT_X = 12067734068385735269710298397816518245765677917578548171423105513834897559050; + uint256 constant CONSTANT_Y = 14116208884206165407695652154080469503316842666011098313092845730626814214139; + uint256 constant PUB_0_X = 18807224464197555970107164686622067170904116077092869998918504702950096959852; + uint256 constant PUB_0_Y = 15992700861332858983179608543360606303300522738696003900378856099458844890665; + uint256 constant PUB_1_X = 743278247134288418539605715841236819761368684662933707997593136463977712794; + uint256 constant PUB_1_Y = 19051244801569834478610626322442233545253273967782903119051284036116982832063; + uint256 constant PUB_2_X = 16228025367567075671354166425508438011647361586247589038592330064997124203122; + uint256 constant PUB_2_Y = 17710554997205290957163818566131535524859911220968411176944839611720872537272; + + /// Negation in Fp. + /// @notice Returns a number x such that a + x = 0 in Fp. + /// @notice The input does not need to be reduced. + /// @param a the base + /// @return x the result + function negate(uint256 a) internal pure returns (uint256 x) { + unchecked { + x = (P - (a % P)) % P; // Modulo is cheaper than branching + } + } + + /// Exponentiation in Fp. + /// @notice Returns a number x such that a ^ e = x in Fp. + /// @notice The input does not need to be reduced. + /// @param a the base + /// @param e the exponent + /// @return x the result + function exp(uint256 a, uint256 e) internal view returns (uint256 x) { + bool success; + assembly ("memory-safe") { + let f := mload(0x40) + mstore(f, 0x20) + mstore(add(f, 0x20), 0x20) + mstore(add(f, 0x40), 0x20) + mstore(add(f, 0x60), a) + mstore(add(f, 0x80), e) + mstore(add(f, 0xa0), P) + success := staticcall(gas(), PRECOMPILE_MODEXP, f, 0xc0, f, 0x20) + x := mload(f) + } + if (!success) { + // Exponentiation failed. + // Should not happen. + revert ProofInvalid(); + } + } + + /// Invertsion in Fp. + /// @notice Returns a number x such that a * x = 1 in Fp. + /// @notice The input does not need to be reduced. + /// @notice Reverts with ProofInvalid() if the inverse does not exist + /// @param a the input + /// @return x the solution + function invert_Fp(uint256 a) internal view returns (uint256 x) { + x = exp(a, EXP_INVERSE_FP); + if (mulmod(a, x, P) != 1) { + // Inverse does not exist. + // Can only happen during G2 point decompression. + revert ProofInvalid(); + } + } + + /// Square root in Fp. + /// @notice Returns a number x such that x * x = a in Fp. + /// @notice Will revert with InvalidProof() if the input is not a square + /// or not reduced. + /// @param a the square + /// @return x the solution + function sqrt_Fp(uint256 a) internal view returns (uint256 x) { + x = exp(a, EXP_SQRT_FP); + if (mulmod(x, x, P) != a) { + // Square root does not exist or a is not reduced. + // Happens when G1 point is not on curve. + revert ProofInvalid(); + } + } + + /// Square test in Fp. + /// @notice Returns whether a number x exists such that x * x = a in Fp. + /// @notice Will revert with InvalidProof() if the input is not a square + /// or not reduced. + /// @param a the square + /// @return x the solution + function isSquare_Fp(uint256 a) internal view returns (bool) { + uint256 x = exp(a, EXP_SQRT_FP); + return mulmod(x, x, P) == a; + } + + /// Square root in Fp2. + /// @notice Fp2 is the complex extension Fp[i]/(i^2 + 1). The input is + /// a0 + a1 ⋅ i and the result is x0 + x1 ⋅ i. + /// @notice Will revert with InvalidProof() if + /// * the input is not a square, + /// * the hint is incorrect, or + /// * the input coefficents are not reduced. + /// @param a0 The real part of the input. + /// @param a1 The imaginary part of the input. + /// @param hint A hint which of two possible signs to pick in the equation. + /// @return x0 The real part of the square root. + /// @return x1 The imaginary part of the square root. + function sqrt_Fp2(uint256 a0, uint256 a1, bool hint) internal view returns (uint256 x0, uint256 x1) { + // If this square root reverts there is no solution in Fp2. + uint256 d = sqrt_Fp(addmod(mulmod(a0, a0, P), mulmod(a1, a1, P), P)); + if (hint) { + d = negate(d); + } + // If this square root reverts there is no solution in Fp2. + x0 = sqrt_Fp(mulmod(addmod(a0, d, P), FRACTION_1_2_FP, P)); + x1 = mulmod(a1, invert_Fp(mulmod(x0, 2, P)), P); + + // Check result to make sure we found a root. + // Note: this also fails if a0 or a1 is not reduced. + if (a0 != addmod(mulmod(x0, x0, P), negate(mulmod(x1, x1, P)), P) + || a1 != mulmod(2, mulmod(x0, x1, P), P)) { + revert ProofInvalid(); + } + } + + /// Compress a G1 point. + /// @notice Reverts with InvalidProof if the coordinates are not reduced + /// or if the point is not on the curve. + /// @notice The point at infinity is encoded as (0,0) and compressed to 0. + /// @param x The X coordinate in Fp. + /// @param y The Y coordinate in Fp. + /// @return c The compresed point (x with one signal bit). + function compress_g1(uint256 x, uint256 y) internal view returns (uint256 c) { + if (x >= P || y >= P) { + // G1 point not in field. + revert ProofInvalid(); + } + if (x == 0 && y == 0) { + // Point at infinity + return 0; + } + + // Note: sqrt_Fp reverts if there is no solution, i.e. the x coordinate is invalid. + uint256 y_pos = sqrt_Fp(addmod(mulmod(mulmod(x, x, P), x, P), 3, P)); + if (y == y_pos) { + return (x << 1) | 0; + } else if (y == negate(y_pos)) { + return (x << 1) | 1; + } else { + // G1 point not on curve. + revert ProofInvalid(); + } + } + + /// Decompress a G1 point. + /// @notice Reverts with InvalidProof if the input does not represent a valid point. + /// @notice The point at infinity is encoded as (0,0) and compressed to 0. + /// @param c The compresed point (x with one signal bit). + /// @return x The X coordinate in Fp. + /// @return y The Y coordinate in Fp. + function decompress_g1(uint256 c) internal view returns (uint256 x, uint256 y) { + // Note that X = 0 is not on the curve since 0³ + 3 = 3 is not a square. + // so we can use it to represent the point at infinity. + if (c == 0) { + // Point at infinity as encoded in EIP196 and EIP197. + return (0, 0); + } + bool negate_point = c & 1 == 1; + x = c >> 1; + if (x >= P) { + // G1 x coordinate not in field. + revert ProofInvalid(); + } + + // Note: (x³ + 3) is irreducible in Fp, so it can not be zero and therefore + // y can not be zero. + // Note: sqrt_Fp reverts if there is no solution, i.e. the point is not on the curve. + y = sqrt_Fp(addmod(mulmod(mulmod(x, x, P), x, P), 3, P)); + if (negate_point) { + y = negate(y); + } + } + + /// Compress a G2 point. + /// @notice Reverts with InvalidProof if the coefficients are not reduced + /// or if the point is not on the curve. + /// @notice The G2 curve is defined over the complex extension Fp[i]/(i^2 + 1) + /// with coordinates (x0 + x1 ⋅ i, y0 + y1 ⋅ i). + /// @notice The point at infinity is encoded as (0,0,0,0) and compressed to (0,0). + /// @param x0 The real part of the X coordinate. + /// @param x1 The imaginary poart of the X coordinate. + /// @param y0 The real part of the Y coordinate. + /// @param y1 The imaginary part of the Y coordinate. + /// @return c0 The first half of the compresed point (x0 with two signal bits). + /// @return c1 The second half of the compressed point (x1 unmodified). + function compress_g2(uint256 x0, uint256 x1, uint256 y0, uint256 y1) + internal view returns (uint256 c0, uint256 c1) { + if (x0 >= P || x1 >= P || y0 >= P || y1 >= P) { + // G2 point not in field. + revert ProofInvalid(); + } + if ((x0 | x1 | y0 | y1) == 0) { + // Point at infinity + return (0, 0); + } + + // Compute y^2 + // Note: shadowing variables and scoping to avoid stack-to-deep. + uint256 y0_pos; + uint256 y1_pos; + { + uint256 n3ab = mulmod(mulmod(x0, x1, P), P-3, P); + uint256 a_3 = mulmod(mulmod(x0, x0, P), x0, P); + uint256 b_3 = mulmod(mulmod(x1, x1, P), x1, P); + y0_pos = addmod(FRACTION_27_82_FP, addmod(a_3, mulmod(n3ab, x1, P), P), P); + y1_pos = negate(addmod(FRACTION_3_82_FP, addmod(b_3, mulmod(n3ab, x0, P), P), P)); + } + + // Determine hint bit + // If this sqrt fails the x coordinate is not on the curve. + bool hint; + { + uint256 d = sqrt_Fp(addmod(mulmod(y0_pos, y0_pos, P), mulmod(y1_pos, y1_pos, P), P)); + hint = !isSquare_Fp(mulmod(addmod(y0_pos, d, P), FRACTION_1_2_FP, P)); + } + + // Recover y + (y0_pos, y1_pos) = sqrt_Fp2(y0_pos, y1_pos, hint); + if (y0 == y0_pos && y1 == y1_pos) { + c0 = (x0 << 2) | (hint ? 2 : 0) | 0; + c1 = x1; + } else if (y0 == negate(y0_pos) && y1 == negate(y1_pos)) { + c0 = (x0 << 2) | (hint ? 2 : 0) | 1; + c1 = x1; + } else { + // G1 point not on curve. + revert ProofInvalid(); + } + } + + /// Decompress a G2 point. + /// @notice Reverts with InvalidProof if the input does not represent a valid point. + /// @notice The G2 curve is defined over the complex extension Fp[i]/(i^2 + 1) + /// with coordinates (x0 + x1 ⋅ i, y0 + y1 ⋅ i). + /// @notice The point at infinity is encoded as (0,0,0,0) and compressed to (0,0). + /// @param c0 The first half of the compresed point (x0 with two signal bits). + /// @param c1 The second half of the compressed point (x1 unmodified). + /// @return x0 The real part of the X coordinate. + /// @return x1 The imaginary poart of the X coordinate. + /// @return y0 The real part of the Y coordinate. + /// @return y1 The imaginary part of the Y coordinate. + function decompress_g2(uint256 c0, uint256 c1) + internal view returns (uint256 x0, uint256 x1, uint256 y0, uint256 y1) { + // Note that X = (0, 0) is not on the curve since 0³ + 3/(9 + i) is not a square. + // so we can use it to represent the point at infinity. + if (c0 == 0 && c1 == 0) { + // Point at infinity as encoded in EIP197. + return (0, 0, 0, 0); + } + bool negate_point = c0 & 1 == 1; + bool hint = c0 & 2 == 2; + x0 = c0 >> 2; + x1 = c1; + if (x0 >= P || x1 >= P) { + // G2 x0 or x1 coefficient not in field. + revert ProofInvalid(); + } + + uint256 n3ab = mulmod(mulmod(x0, x1, P), P-3, P); + uint256 a_3 = mulmod(mulmod(x0, x0, P), x0, P); + uint256 b_3 = mulmod(mulmod(x1, x1, P), x1, P); + + y0 = addmod(FRACTION_27_82_FP, addmod(a_3, mulmod(n3ab, x1, P), P), P); + y1 = negate(addmod(FRACTION_3_82_FP, addmod(b_3, mulmod(n3ab, x0, P), P), P)); + + // Note: sqrt_Fp2 reverts if there is no solution, i.e. the point is not on the curve. + // Note: (X³ + 3/(9 + i)) is irreducible in Fp2, so y can not be zero. + // But y0 or y1 may still independently be zero. + (y0, y1) = sqrt_Fp2(y0, y1, hint); + if (negate_point) { + y0 = negate(y0); + y1 = negate(y1); + } + } + + /// Compute the public input linear combination. + /// @notice Reverts with PublicInputNotInField if the input is not in the field. + /// @notice Computes the multi-scalar-multiplication of the public input + /// elements and the verification key including the constant term. + /// @param input The public inputs. These are elements of the scalar field Fr. + /// @return x The X coordinate of the resulting G1 point. + /// @return y The Y coordinate of the resulting G1 point. + function publicInputMSM(uint256[3] calldata input) + internal view returns (uint256 x, uint256 y) { + // Note: The ECMUL precompile does not reject unreduced values, so we check this. + // Note: Unrolling this loop does not cost much extra in code-size, the bulk of the + // code-size is in the PUB_ constants. + // ECMUL has input (x, y, scalar) and output (x', y'). + // ECADD has input (x1, y1, x2, y2) and output (x', y'). + // We reduce commitments(if any) with constants as the first point argument to ECADD. + // We call them such that ecmul output is already in the second point + // argument to ECADD so we can have a tight loop. + bool success = true; + assembly ("memory-safe") { + let f := mload(0x40) + let g := add(f, 0x40) + let s + mstore(f, CONSTANT_X) + mstore(add(f, 0x20), CONSTANT_Y) + mstore(g, PUB_0_X) + mstore(add(g, 0x20), PUB_0_Y) + s := calldataload(input) + mstore(add(g, 0x40), s) + success := and(success, lt(s, R)) + success := and(success, staticcall(gas(), PRECOMPILE_MUL, g, 0x60, g, 0x40)) + success := and(success, staticcall(gas(), PRECOMPILE_ADD, f, 0x80, f, 0x40)) + mstore(g, PUB_1_X) + mstore(add(g, 0x20), PUB_1_Y) + s := calldataload(add(input, 32)) + mstore(add(g, 0x40), s) + success := and(success, lt(s, R)) + success := and(success, staticcall(gas(), PRECOMPILE_MUL, g, 0x60, g, 0x40)) + success := and(success, staticcall(gas(), PRECOMPILE_ADD, f, 0x80, f, 0x40)) + mstore(g, PUB_2_X) + mstore(add(g, 0x20), PUB_2_Y) + s := calldataload(add(input, 64)) + mstore(add(g, 0x40), s) + success := and(success, lt(s, R)) + success := and(success, staticcall(gas(), PRECOMPILE_MUL, g, 0x60, g, 0x40)) + success := and(success, staticcall(gas(), PRECOMPILE_ADD, f, 0x80, f, 0x40)) + + x := mload(f) + y := mload(add(f, 0x20)) + } + if (!success) { + // Either Public input not in field, or verification key invalid. + // We assume the contract is correctly generated, so the verification key is valid. + revert PublicInputNotInField(); + } + } + + /// Compress a proof. + /// @notice Will revert with InvalidProof if the curve points are invalid, + /// but does not verify the proof itself. + /// @param proof The uncompressed Groth16 proof. Elements are in the same order as for + /// verifyProof. I.e. Groth16 points (A, B, C) encoded as in EIP-197. + /// @return compressed The compressed proof. Elements are in the same order as for + /// verifyCompressedProof. I.e. points (A, B, C) in compressed format. + function compressProof(uint256[8] calldata proof) + public view returns (uint256[4] memory compressed) { + compressed[0] = compress_g1(proof[0], proof[1]); + (compressed[2], compressed[1]) = compress_g2(proof[3], proof[2], proof[5], proof[4]); + compressed[3] = compress_g1(proof[6], proof[7]); + } + + /// Verify a Groth16 proof with compressed points. + /// @notice Reverts with InvalidProof if the proof is invalid or + /// with PublicInputNotInField the public input is not reduced. + /// @notice There is no return value. If the function does not revert, the + /// proof was successfully verified. + /// @param compressedProof the points (A, B, C) in compressed format + /// matching the output of compressProof. + /// @param input the public input field elements in the scalar field Fr. + /// Elements must be reduced. + function verifyCompressedProof( + uint256[4] calldata compressedProof, + uint256[3] calldata input + ) public view { + uint256[24] memory pairings; + + { + (uint256 Ax, uint256 Ay) = decompress_g1(compressedProof[0]); + (uint256 Bx0, uint256 Bx1, uint256 By0, uint256 By1) = decompress_g2(compressedProof[2], compressedProof[1]); + (uint256 Cx, uint256 Cy) = decompress_g1(compressedProof[3]); + (uint256 Lx, uint256 Ly) = publicInputMSM(input); + + // Verify the pairing + // Note: The precompile expects the F2 coefficients in big-endian order. + // Note: The pairing precompile rejects unreduced values, so we won't check that here. + // e(A, B) + pairings[ 0] = Ax; + pairings[ 1] = Ay; + pairings[ 2] = Bx1; + pairings[ 3] = Bx0; + pairings[ 4] = By1; + pairings[ 5] = By0; + // e(C, -δ) + pairings[ 6] = Cx; + pairings[ 7] = Cy; + pairings[ 8] = DELTA_NEG_X_1; + pairings[ 9] = DELTA_NEG_X_0; + pairings[10] = DELTA_NEG_Y_1; + pairings[11] = DELTA_NEG_Y_0; + // e(α, -β) + pairings[12] = ALPHA_X; + pairings[13] = ALPHA_Y; + pairings[14] = BETA_NEG_X_1; + pairings[15] = BETA_NEG_X_0; + pairings[16] = BETA_NEG_Y_1; + pairings[17] = BETA_NEG_Y_0; + // e(L_pub, -γ) + pairings[18] = Lx; + pairings[19] = Ly; + pairings[20] = GAMMA_NEG_X_1; + pairings[21] = GAMMA_NEG_X_0; + pairings[22] = GAMMA_NEG_Y_1; + pairings[23] = GAMMA_NEG_Y_0; + + // Check pairing equation. + bool success; + uint256[1] memory output; + assembly ("memory-safe") { + success := staticcall(gas(), PRECOMPILE_VERIFY, pairings, 0x300, output, 0x20) + } + if (!success || output[0] != 1) { + // Either proof or verification key invalid. + // We assume the contract is correctly generated, so the verification key is valid. + revert ProofInvalid(); + } + } + } + + /// Verify an uncompressed Groth16 proof. + /// @notice Reverts with InvalidProof if the proof is invalid or + /// with PublicInputNotInField the public input is not reduced. + /// @notice There is no return value. If the function does not revert, the + /// proof was successfully verified. + /// @param proof the points (A, B, C) in EIP-197 format matching the output + /// of compressProof. + /// @param input the public input field elements in the scalar field Fr. + /// Elements must be reduced. + function Verify( + uint256[8] calldata proof, + uint256[3] calldata input + ) public view { + (uint256 x, uint256 y) = publicInputMSM(input); + + // Note: The precompile expects the F2 coefficients in big-endian order. + // Note: The pairing precompile rejects unreduced values, so we won't check that here. + bool success; + assembly ("memory-safe") { + let f := mload(0x40) // Free memory pointer. + + // Copy points (A, B, C) to memory. They are already in correct encoding. + // This is pairing e(A, B) and G1 of e(C, -δ). + calldatacopy(f, proof, 0x100) + + // Complete e(C, -δ) and write e(α, -β), e(L_pub, -γ) to memory. + // OPT: This could be better done using a single codecopy, but + // Solidity (unlike standalone Yul) doesn't provide a way to + // to do this. + mstore(add(f, 0x100), DELTA_NEG_X_1) + mstore(add(f, 0x120), DELTA_NEG_X_0) + mstore(add(f, 0x140), DELTA_NEG_Y_1) + mstore(add(f, 0x160), DELTA_NEG_Y_0) + mstore(add(f, 0x180), ALPHA_X) + mstore(add(f, 0x1a0), ALPHA_Y) + mstore(add(f, 0x1c0), BETA_NEG_X_1) + mstore(add(f, 0x1e0), BETA_NEG_X_0) + mstore(add(f, 0x200), BETA_NEG_Y_1) + mstore(add(f, 0x220), BETA_NEG_Y_0) + mstore(add(f, 0x240), x) + mstore(add(f, 0x260), y) + mstore(add(f, 0x280), GAMMA_NEG_X_1) + mstore(add(f, 0x2a0), GAMMA_NEG_X_0) + mstore(add(f, 0x2c0), GAMMA_NEG_Y_1) + mstore(add(f, 0x2e0), GAMMA_NEG_Y_0) + + // Check pairing equation. + success := staticcall(gas(), PRECOMPILE_VERIFY, f, 0x300, f, 0x20) + // Also check returned value (both are either 1 or 0). + success := and(success, mload(f)) + } + if (!success) { + // Either proof or verification key invalid. + // We assume the contract is correctly generated, so the verification key is valid. + revert ProofInvalid(); + } + } +} diff --git a/contracts/ziren-groth16-verifier/src/ZirenGroth16ProofVerifier.sol b/contracts/ziren-groth16-verifier/src/ZirenGroth16ProofVerifier.sol new file mode 100644 index 0000000..6d2b2fc --- /dev/null +++ b/contracts/ziren-groth16-verifier/src/ZirenGroth16ProofVerifier.sol @@ -0,0 +1,57 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.30; + +import {IZirenProofVerifier} from "@ziren-shared/IZirenProofVerifier.sol"; + +interface IZirenGroth16Verifier { + function Verify(uint256[8] calldata proof, uint256[3] calldata input) external view; +} + +/// Serves the Ziren Groth16 terminal behind the IZirenProofVerifier interface. +/// +/// The packet is the 4-byte verifier selector followed by the 256-byte gnark +/// proof encoding (eight big-endian words). The Groth16 public inputs are +/// `[application key, committed-value digest, recursion root]`, where the +/// committed-value digest is the output digest with its top three bits cleared. +/// The recursion root is the prover's `recursion_vk_root` for the Ziren revision +/// pinned by this repository, as committed by the shrink. Exit code zero is +/// enforced inside the recursion core circuit rather than by a public input, so +/// this adapter does not bind it separately. +contract ZirenGroth16ProofVerifier is IZirenProofVerifier { + uint256 internal constant DIGEST_MASK = (1 << 253) - 1; + uint256 internal constant PACKET_LENGTH = 4 + 32 * 8; + + IZirenGroth16Verifier public immutable groth16Verifier; + bytes4 public immutable verifierSelector; + bytes32 public immutable applicationKey; + uint256 public immutable recursionRoot; + + constructor( + IZirenGroth16Verifier verifier, + bytes4 selector, + bytes32 applicationKey_, + uint256 recursionRoot_ + ) { + groth16Verifier = verifier; + verifierSelector = selector; + applicationKey = applicationKey_; + recursionRoot = recursionRoot_; + } + + function verify(bytes calldata proofPacket, bytes32 expectedOutputDigest) external view returns (bool) { + if (proofPacket.length != PACKET_LENGTH) return false; + if (bytes4(proofPacket[:4]) != verifierSelector) return false; + + uint256[8] memory proof = abi.decode(proofPacket[4:], (uint256[8])); + uint256[3] memory inputs; + inputs[0] = uint256(applicationKey); + inputs[1] = uint256(expectedOutputDigest) & DIGEST_MASK; + inputs[2] = recursionRoot; + + try groth16Verifier.Verify(proof, inputs) { + return true; + } catch { + return false; + } + } +} diff --git a/contracts/ziren-groth16-verifier/test/Groth16Verifier.t.sol b/contracts/ziren-groth16-verifier/test/Groth16Verifier.t.sol new file mode 100644 index 0000000..bf581f8 --- /dev/null +++ b/contracts/ziren-groth16-verifier/test/Groth16Verifier.t.sol @@ -0,0 +1,64 @@ +// SPDX-License-Identifier: MIT +pragma solidity 0.8.30; + +import {Groth16Verifier} from "../src/Groth16Verifier.sol"; +import {ZirenGroth16ProofVerifier, IZirenGroth16Verifier} from "../src/ZirenGroth16ProofVerifier.sol"; + +/// Runs the real Groth16Verifier on the fibonacci proof (input 10) exported by +/// scripts/groth16_verify.py's pipeline. The proof, public inputs and packet are the +/// values printed by scripts/groth16_args.py for that run. +contract Groth16VerifierTest { + bytes4 internal constant SELECTOR = 0xb3e14fe9; + bytes32 internal constant APPLICATION_KEY = 0x002c7ab66df288215fdb30b7aa52652019e409667f9f3373af22b2d395238c53; + uint256 internal constant RECURSION_ROOT = 0x007ad39482c4460fe91d19534ecc20e27d374c3e17c0fe5f44d7cf7cb0fd2349; + bytes32 internal constant OUTPUT_DIGEST = 0xd0abd303eefe48a35a09197c8840467029bde2832f61695991207d60fb6a2354; + + function fixtureProof() internal pure returns (uint256[8] memory p) { + p[0] = 0x1dd488d0ee908485258830fde6ef8e54162dddf06bf646df7dc089f227757de2; + p[1] = 0x16ccc680820d8ba2ffb36c7aa0625c345330f2ad5fb2142e42561457b7726a67; + p[2] = 0x16e07d92f9107bbda27d8cc10d9bc8a6f41d9411c42594b499fea8b56c67c16b; + p[3] = 0x2eb0b7e64fc6a6f9bba6752614116710fdae3213ddfc3a8f2902cfa6b04282a9; + p[4] = 0x0930e89b73eb2da6fc2c24b68dbed6b3bb9a5d2088b9c4b69050232d65958ce3; + p[5] = 0x1a2ff75b95fae521a3192f48baabf70e810ab0a1505b8b0d7a811fa802374ef9; + p[6] = 0x1c8f66bed48abb80a6a936dc71464784119d0a6ce4c7248fb97ea17c9680381e; + p[7] = 0x1bfd49c53b9ebbce0509560a42d571ebbbecbaedf84a6d0ed47e362575444ee6; + } + + function fixtureInputs() internal pure returns (uint256[3] memory i) { + i[0] = uint256(APPLICATION_KEY); + i[1] = 0x10abd303eefe48a35a09197c8840467029bde2832f61695991207d60fb6a2354; + i[2] = RECURSION_ROOT; + } + + function testVerifierAcceptsFixtureProof() public { + Groth16Verifier verifier = new Groth16Verifier(); + verifier.Verify(fixtureProof(), fixtureInputs()); + } + + function testVerifierRejectsTamperedProof() public { + Groth16Verifier verifier = new Groth16Verifier(); + uint256[8] memory proof = fixtureProof(); + proof[0] ^= 1; + try verifier.Verify(proof, fixtureInputs()) { + revert("tampered proof accepted"); + } catch {} + } + + function testVerifierRejectsWrongPublicInput() public { + Groth16Verifier verifier = new Groth16Verifier(); + uint256[3] memory inputs = fixtureInputs(); + inputs[2] ^= 1; + try verifier.Verify(fixtureProof(), inputs) { + revert("wrong public input accepted"); + } catch {} + } + + function testAdapterAcceptsFixturePacketWithRealVerifier() public { + Groth16Verifier verifier = new Groth16Verifier(); + ZirenGroth16ProofVerifier adapter = new ZirenGroth16ProofVerifier( + IZirenGroth16Verifier(address(verifier)), SELECTOR, APPLICATION_KEY, RECURSION_ROOT + ); + bytes memory packet = abi.encodePacked(SELECTOR, abi.encode(fixtureProof())); + require(adapter.verify(packet, OUTPUT_DIGEST), "adapter rejected fixture packet"); + } +} diff --git a/contracts/ziren-groth16-verifier/test/ZirenGroth16ProofVerifier.t.sol b/contracts/ziren-groth16-verifier/test/ZirenGroth16ProofVerifier.t.sol new file mode 100644 index 0000000..e651a70 --- /dev/null +++ b/contracts/ziren-groth16-verifier/test/ZirenGroth16ProofVerifier.t.sol @@ -0,0 +1,74 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.30; + +import {ZirenGroth16ProofVerifier, IZirenGroth16Verifier} from "../src/ZirenGroth16ProofVerifier.sol"; + +/// Accepts exactly one proof word and one public input vector, and reverts +/// otherwise, as the generated Groth16 verifier does. +contract MockGroth16Verifier is IZirenGroth16Verifier { + uint256 public immutable acceptedFirstWord; + uint256[3] public expectedInput; + + constructor(uint256 acceptedFirstWord_, uint256[3] memory expectedInput_) { + acceptedFirstWord = acceptedFirstWord_; + expectedInput = expectedInput_; + } + + function Verify(uint256[8] calldata proof, uint256[3] calldata input) external view { + if (proof[0] != acceptedFirstWord) revert("invalid proof"); + if (input[0] != expectedInput[0] || input[1] != expectedInput[1] || input[2] != expectedInput[2]) { + revert("invalid public input"); + } + } +} + +contract ZirenGroth16ProofVerifierTest { + bytes4 internal constant SELECTOR = 0xb3e14fe9; + bytes32 internal constant APPLICATION_KEY = 0x002c7ab66df288215fdb30b7aa52652019e409667f9f3373af22b2d395238c53; + uint256 internal constant RECURSION_ROOT = 0x007ad39482c4460fe91d19534ecc20e27d374c3e17c0fe5f44d7cf7cb0fd2349; + bytes32 internal constant OUTPUT_DIGEST = 0xd0abd303eefe48a35a09197c8840467029bde2832f61695991207d60fb6a2354; + uint256 internal constant MASKED_DIGEST = 0x10abd303eefe48a35a09197c8840467029bde2832f61695991207d60fb6a2354; + uint256 internal constant FIRST_WORD = 0x1dd488d0ee908485258830fde6ef8e54162dddf06bf646df7dc089f227757de2; + + MockGroth16Verifier internal mock; + ZirenGroth16ProofVerifier internal adapter; + + function setUp() public { + uint256[3] memory expected = [uint256(APPLICATION_KEY), MASKED_DIGEST, RECURSION_ROOT]; + mock = new MockGroth16Verifier(FIRST_WORD, expected); + adapter = new ZirenGroth16ProofVerifier(mock, SELECTOR, APPLICATION_KEY, RECURSION_ROOT); + } + + function packet(uint256 firstWord) internal pure returns (bytes memory out) { + out = abi.encodePacked(SELECTOR, firstWord); + for (uint256 i = 1; i < 8; ++i) { + out = abi.encodePacked(out, uint256(i)); + } + } + + function testAcceptsValidPacket() public view { + require(adapter.verify(packet(FIRST_WORD), OUTPUT_DIGEST), "valid packet rejected"); + } + + function testMasksOutputDigestTopBits() public view { + require(adapter.verify(packet(FIRST_WORD), OUTPUT_DIGEST), "digest not masked"); + require(!adapter.verify(packet(FIRST_WORD), bytes32(uint256(OUTPUT_DIGEST) ^ 1)), "wrong digest accepted"); + } + + function testRejectsInvalidProof() public view { + require(!adapter.verify(packet(FIRST_WORD + 1), OUTPUT_DIGEST), "invalid proof accepted"); + } + + function testRejectsWrongSelector() public view { + bytes memory p = packet(FIRST_WORD); + p[0] = 0x00; + require(!adapter.verify(p, OUTPUT_DIGEST), "wrong selector accepted"); + } + + function testRejectsWrongLength() public view { + bytes memory p = packet(FIRST_WORD); + bytes memory shortPacket = new bytes(p.length - 1); + for (uint256 i; i < shortPacket.length; ++i) shortPacket[i] = p[i]; + require(!adapter.verify(shortPacket, OUTPUT_DIGEST), "short packet accepted"); + } +} diff --git a/contracts/ziren-shrink-verifier/README.md b/contracts/ziren-shrink-verifier/README.md index 41fd951..b3c2d7d 100644 --- a/contracts/ziren-shrink-verifier/README.md +++ b/contracts/ziren-shrink-verifier/README.md @@ -25,14 +25,42 @@ Deployment can span transactions. Each proof verification supplies the complete packet in one transaction; partial upload or intermediate verification state is not part of this design. -Measured on 2026-10-21 for Ethereum block 26240087 (an EthProofs Ziren proof), -on a local Osaka Anvil node that enforces the 16,777,216-gas transaction cap: +Measured on 2026-11-05 for a complete shrink proof (206,726-byte raw packet) on a +local Osaka Anvil node that enforces the 16,777,216-gas transaction cap: | Cost | Gas | | --- | --- | -| Verification transaction | 13,668,039 | -| of which calldata (182 KB packet) | 2,834,640 | -| Deployment, all modules | 141,599,268 | +| Verification transaction | 13,751,027 | +| of which calldata (207 KB packet) | 3,173,300 | +| Deployment, all modules | 144,547,906 | + +The same build and proof forked from Sepolia (block 12066266, public RPC) give +identical gas figures. + +With the lossless field zero-run and full-hash dictionary transport +(`measure.py --zero-runs`, same build and proof), the packet shrinks to 182,190 +bytes and the verification transaction is cheaper; deployment is unchanged: + +| Cost | Gas | +| --- | --- | +| Verification transaction | 13,628,720 | +| of which calldata (182 KB packet) | 2,845,696 | +| Deployment, all modules | 144,547,906 | + +The Groth16 terminal is served by `ZirenGroth16ProofVerifier` +(`contracts/ziren-groth16-verifier`), which calls the Ziren Groth16 +verifier compiled with solc 0.8.30 and the optimizer enabled. Measured on +2026-11-05 for a Groth16 proof of the fibonacci guest (input 10) on a local Osaka +Anvil node (`--gas-limit 60000000`): + +| Cost | Gas | +| --- | --- | +| Verification transaction | 233,450 | +| of which calldata (388-byte `verify` call, 260-byte packet) | 5,092 | +| Deployment, Groth16Verifier | 1,135,523 | +| Deployment, ZirenGroth16ProofVerifier | 326,771 | + +The verification transaction leaves 207,358 gas for execution. For a fixed approved profile, proof geometry does not grow with the guest workload. Exact gas still depends on the build and encoded packet; the Ethereum diff --git a/crates/ziren-groth16-export/Cargo.toml b/crates/ziren-groth16-export/Cargo.toml new file mode 100644 index 0000000..83a8ee4 --- /dev/null +++ b/crates/ziren-groth16-export/Cargo.toml @@ -0,0 +1,19 @@ +[package] +name = "ziren-groth16-export" +version = { workspace = true } +edition = { workspace = true } +license = { workspace = true } +repository = { workspace = true } + +[dependencies] +anyhow = { workspace = true } +bincode = "1.3.3" +serde_json = { workspace = true } +zkm-pcs = { workspace = true } +zkm-prover = { workspace = true } +zkm-core-machine = { workspace = true } +zkm-core-executor = { workspace = true } +zkm-primitives = { workspace = true } + +[[example]] +name = "export_groth16" diff --git a/crates/ziren-groth16-export/README.md b/crates/ziren-groth16-export/README.md new file mode 100644 index 0000000..45b2919 --- /dev/null +++ b/crates/ziren-groth16-export/README.md @@ -0,0 +1,36 @@ +# Groth16 export + +Export of the Groth16 terminal: native shrink, `wrap_bn254` and +`wrap_groth16_bn254` on Ziren, writing the proof for the on-chain check. +`examples/export_groth16.rs` is the entry point. + +## Modes + +```sh +export_groth16 prove [u32 input] +export_groth16 groth16 +export_groth16 replay +``` + +- `prove` runs core proving, compression, native shrink, `wrap_bn254` and + `wrap_groth16_bn254`. It writes `compressed.bin`, `public_values.bin` and + `groth16_proof.json` to ``. `public_values.bin` is the input to + `scripts/groth16_verify.py`. +- `groth16` takes a saved compressed proof, either `compressed.bin` or an SDK + compressed proof, and runs the native shrink and both wraps without proving + the guest again. It writes the Groth16 proof to ``. +- `replay` reads `groth16_proof.json` from a `prove` output directory and checks + its layout: the encoded proof is 256 bytes, and it prints the verifier selector, + the number of public inputs and the raw proof size. It runs no proving and no wrap, + and it does not verify the proof cryptographically. + +The default input is 10. Every mode runs on the CPU. `prove` and `groth16` read the Groth16 +circuit artifacts from ``. + +`prove` and `groth16` write the proof as JSON, which `scripts/groth16_args.py` and +`scripts/groth16_verify.py` read. A successful `prove` or `groth16` run prints +`GROTH16_OK raw_proof_bytes=... out=...`; `replay` prints `REPLAY_OK ...`. + +The Solidity verifier and adapter live in +[contracts/ziren-groth16-verifier](../../contracts/ziren-groth16-verifier/). +See [groth16-verification](../../docs/groth16-verification.md) for the full steps. diff --git a/crates/ziren-groth16-export/examples/export_groth16.rs b/crates/ziren-groth16-export/examples/export_groth16.rs new file mode 100644 index 0000000..fe33750 --- /dev/null +++ b/crates/ziren-groth16-export/examples/export_groth16.rs @@ -0,0 +1,184 @@ +//! Export a Groth16 terminal proof on the CPU: native shrink, `wrap_bn254`, then +//! `wrap_groth16_bn254`. +//! +//! Usage: +//! export_groth16 prove [u32 input] +//! export_groth16 groth16 +//! export_groth16 replay +//! +//! `prove` runs core proving, compression, native shrink and both wraps. It +//! writes `compressed.bin` and `public_values.bin` (for `groth16_verify.py`) and +//! `groth16_proof.json` to ``. `groth16` takes a saved compressed proof, +//! such as `compressed.bin` or an SDK compressed proof, and runs the shrink and +//! both wraps. `replay` reads the Groth16 proof that `prove` wrote to its out +//! dir and checks its layout, without running any proving. +use std::path::Path; +use std::time::Instant; +use zkm_core_executor::ZKMContext; +use zkm_core_machine::io::ZKMStdin; +use zkm_core_machine::reduce::ZKMReduceProof; +use zkm_pcs::ZKMProverOpts; +use zkm_primitives::io::ZKMPublicValues; +use zkm_prover::{ + components::DefaultProverComponents, CompressedSC, Groth16Bn254Proof, NativeShrink, ZKMProver, +}; + +/// Hex digits in the 256-byte `encoded_proof` field of the Groth16 proof. +const ENCODED_PROOF_HEX_LEN: usize = 512; + +const USAGE: &str = "usage: + export_groth16 prove [u32 input] + export_groth16 groth16 + export_groth16 replay "; + +type Prover = ZKMProver; + +fn main() -> anyhow::Result<()> { + let args: Vec = std::env::args().skip(1).collect(); + anyhow::ensure!(args.len() >= 2, USAGE); + let started = Instant::now(); + let prover = Prover::uninitialized_with(Some(true)); + + match args[0].as_str() { + "prove" => { + anyhow::ensure!(args.len() >= 4, USAGE); + let input = args.get(4).map(|s| s.parse()).transpose()?.unwrap_or(10); + prove( + &prover, + Path::new(&args[1]), + Path::new(&args[2]), + Path::new(&args[3]), + input, + started, + )?; + } + "groth16" => { + anyhow::ensure!(args.len() >= 4, USAGE); + let compressed = read_compressed(Path::new(&args[1]))?; + groth16_from_compressed( + &prover, + compressed, + Path::new(&args[2]), + Path::new(&args[3]), + started, + )?; + } + "replay" => { + let path = Path::new(&args[1]).join("groth16_proof.json"); + let groth16: Groth16Bn254Proof = serde_json::from_slice(&std::fs::read(&path)?)?; + anyhow::ensure!( + groth16.encoded_proof.len() == ENCODED_PROOF_HEX_LEN, + "encoded_proof is {} hex digits, expected {ENCODED_PROOF_HEX_LEN}", + groth16.encoded_proof.len() + ); + println!( + "REPLAY_OK selector=0x{} public_inputs={} raw_proof_bytes={} path={}", + hex_prefix(&groth16.groth16_vkey_hash), + groth16.public_inputs.len(), + groth16.raw_proof.len(), + path.display() + ); + } + other => anyhow::bail!("unknown mode {other}\n{USAGE}"), + } + Ok(()) +} + +/// Proves the guest and compresses the core proof. +fn prove_compressed( + prover: &Prover, + elf_path: &Path, + input: u32, + started: Instant, +) -> anyhow::Result<(ZKMReduceProof, ZKMPublicValues)> { + let elf = std::fs::read(elf_path)?; + let (_, pk, program, vk) = prover.setup(&elf); + eprintln!("[export] setup {:?}", started.elapsed()); + + let mut stdin = ZKMStdin::new(); + stdin.write(&input); + let opts = ZKMProverOpts::default(); + + let core = prover.prove_core(&pk, program, &stdin, opts, ZKMContext::default())?; + eprintln!("[export] core proved {:?}", started.elapsed()); + let public_values = core.public_values.clone(); + let compressed = prover.compress(&vk, core, vec![], opts)?; + eprintln!("[export] compressed {:?}", started.elapsed()); + Ok((compressed, public_values)) +} + +/// Proves the guest end to end and writes its artifacts to `out_dir`: +/// `compressed.bin`, `public_values.bin` and `groth16_proof.json`. +fn prove( + prover: &Prover, + elf_path: &Path, + circuit_dir: &Path, + out_dir: &Path, + input: u32, + started: Instant, +) -> anyhow::Result<()> { + std::fs::create_dir_all(out_dir)?; + let (compressed, public_values) = prove_compressed(prover, elf_path, input, started)?; + std::fs::write( + out_dir.join("compressed.bin"), + bincode::serialize(&compressed)?, + )?; + std::fs::write( + out_dir.join("public_values.bin"), + bincode::serialize(&public_values)?, + )?; + groth16_from_compressed( + prover, + compressed, + circuit_dir, + &out_dir.join("groth16_proof.json"), + started, + ) +} + +/// Reads a bincode compressed proof, accepting the SDK wrapper that prefixes +/// it with a `ZKMProof` enum tag (1 = Compressed). +fn read_compressed(path: &Path) -> anyhow::Result> { + const COMPRESSED_TAG: u32 = 1; + let bytes = std::fs::read(path)?; + anyhow::ensure!( + bytes.len() >= 4, + "{} is too short to be a proof", + path.display() + ); + let tag = u32::from_le_bytes(bytes[..4].try_into()?); + Ok(match tag { + COMPRESSED_TAG => bincode::deserialize(&bytes[4..])?, + _ => bincode::deserialize(&bytes)?, + }) +} + +/// The first four bytes of the verifier hash as lowercase hex. +fn hex_prefix(hash: &[u8; 32]) -> String { + hash[..4].iter().map(|b| format!("{b:02x}")).collect() +} + +/// Runs the native shrink, `wrap_bn254` and `wrap_groth16_bn254`, and writes +/// the Groth16 proof as JSON. +fn groth16_from_compressed( + prover: &Prover, + compressed: ZKMReduceProof, + circuit_dir: &Path, + out: &Path, + started: Instant, +) -> anyhow::Result<()> { + let shrink = prover.shrink_with::(compressed, ZKMProverOpts::default())?; + eprintln!("[export] native shrink {:?}", started.elapsed()); + let wrapped = prover.wrap_bn254(shrink, ZKMProverOpts::default())?; + eprintln!("[export] wrap_bn254 {:?}", started.elapsed()); + + let groth16 = prover.wrap_groth16_bn254(wrapped, circuit_dir); + eprintln!("[export] wrap_groth16_bn254 {:?}", started.elapsed()); + std::fs::write(out, serde_json::to_vec_pretty(&groth16)?)?; + println!( + "GROTH16_OK raw_proof_bytes={} out={}", + groth16.raw_proof.len(), + out.display() + ); + Ok(()) +} diff --git a/crates/ziren-groth16-export/src/lib.rs b/crates/ziren-groth16-export/src/lib.rs new file mode 100644 index 0000000..705fc1d --- /dev/null +++ b/crates/ziren-groth16-export/src/lib.rs @@ -0,0 +1,2 @@ +//! Groth16 terminal export for the Ziren route. The export example runs native shrink, +//! `wrap_bn254` and `wrap_groth16_bn254`, and writes the Groth16 proof as JSON. diff --git a/crates/ziren-shrink-export/src/machine.rs b/crates/ziren-shrink-export/src/machine.rs index de760dd..14eaebb 100644 --- a/crates/ziren-shrink-export/src/machine.rs +++ b/crates/ziren-shrink-export/src/machine.rs @@ -212,13 +212,12 @@ pub fn export( let mut inputs = opening.main.local.clone(); inputs.extend(&opening.preprocessed.local); inputs.extend(shrink.proof.public_values.iter().copied().map(E::from)); - let expected = - zkm_pcs::shard_level::constraint_folder::eval_constraints_shard_host( - chip, - opening, - alpha, - &shrink.proof.public_values, - ); + let expected = zkm_pcs::shard_level::constraint_folder::eval_constraints_shard_host( + chip, + opening, + alpha, + &shrink.proof.public_values, + ); assert_eq!( rpn.run(&inputs, &roots, alpha), expected, @@ -246,10 +245,9 @@ pub fn export( let mut inputs = changed.main.local.clone(); inputs.extend(&changed.preprocessed.local); inputs.extend(pv.iter().copied().map(E::from)); - let expected = - zkm_pcs::shard_level::constraint_folder::eval_constraints_shard_host( - chip, &changed, alpha, &pv, - ); + let expected = zkm_pcs::shard_level::constraint_folder::eval_constraints_shard_host( + chip, &changed, alpha, &pv, + ); assert_eq!( rpn.run(&inputs, &roots, alpha), expected, diff --git a/docs/development.md b/docs/development.md index 38ea4a5..e4c5db7 100644 --- a/docs/development.md +++ b/docs/development.md @@ -141,4 +141,5 @@ WIRE_FIXTURE=$WORK/proof NATIVE_BUILD=$WORK/build \ For more differential checks against independent checkpoint vectors, run `contracts/ziren-shrink-verifier/native/run-tests.py` and drop `--skip-checkpoints`. -The bridge integration is described in [bridge.md](bridge.md). +The bridge integration is described in [bridge.md](bridge.md). The Groth16 terminal +is verified step by step in [groth16-verification.md](groth16-verification.md). diff --git a/docs/groth16-verification.md b/docs/groth16-verification.md new file mode 100644 index 0000000..ece2aa2 --- /dev/null +++ b/docs/groth16-verification.md @@ -0,0 +1,195 @@ +# Verify a Groth16 terminal proof on a local EVM + +A Ziren proof is shrunk natively, wrapped to BN254, then wrapped again as a gnark +Groth16 proof. The proof is checked by the Ziren Groth16 verifier, called through +`ZirenGroth16ProofVerifier`, which implements `IZirenProofVerifier` (`contracts/shared/`), +the interface `MetisOPSuccinctL2OutputOracle` calls. + +The shrink path is documented in [development.md](development.md). This document +covers only the Groth16 terminal. + +## What is checked + +| Check | Where | +| --- | --- | +| Ziren produces a native shrink and a Groth16 proof that verifies internally | `export_groth16` (step 1) | +| The proof verifies on chain through the Ziren verifier | `groth16_verify.py`, direct `Verify` check (step 2) | +| The adapter maps the packet and output digest to the Groth16 inputs | `groth16_verify.py`, adapter checks (step 2) | +| The adapter rejects a tampered proof, digest, selector or length | `groth16_verify.py`, negative checks (step 2) | +| The adapter's mapping logic in isolation | `forge test` in `contracts/ziren-groth16-verifier` (step 3) | + +Not checked here: an end-to-end Metis aggregation, the exit code, and the +recursion root against the release constant. See [Caveats](#caveats). + +## Prerequisites + +- The Ziren revision pinned by this repository (`Cargo.lock`). The recursion root is not read + from a file: the prover computes it from its embedded `vk_map.bin`, as the shrink exporter does, + and the Groth16 proof commits to it as `public_inputs[2]`. +- Rust toolchain, Python 3.11+, solc 0.8.30, Foundry (`anvil`, `cast`, `forge`). +- Groth16 artifacts for the pinned revision. The export example reads them from + `$CIRC`; in this document `$CIRC` is `~/.zkm/circuits/groth16/v2.0.0`. These files + are several gigabytes (`groth16_pk.bin` about 11 GB, `groth16_circuit.bin` about + 4.3 GB), so confirm the disk and memory budget first. +- A guest ELF. This document uses the fibonacci guest with input `10`. + +Run every command from the OPSuccinct root. Put outputs under `$WORK`, which must be +outside the repository. + +```sh +export WORK=/path/outside/repo/zkop-work +export CIRC=$HOME/.zkm/circuits/groth16/v2.0.0 +export ELF=/path/to/fibonacci +export CARGO_TARGET_DIR=$WORK/target +export RPC=http://127.0.0.1:18602 +mkdir -p $WORK +``` + +Start the local node in a separate terminal. Its unlocked account 0 (`0xf39F…2266`) is the +deployer that `scripts/groth16_verify.py` uses by default. It is an Anvil test key, so use it on +a local node only: + +```sh +anvil --host 127.0.0.1 --port 18602 --hardfork osaka --enable-tx-gas-limit \ + --gas-limit 60000000 --no-request-size-limit --silent +``` + +## 1. Produce the proof + +The export example runs on the CPU. `prove` runs core proving, compression, native shrink, +`wrap_bn254` and `wrap_groth16_bn254`. It writes `compressed.bin` and `public_values.bin` (step 2 +needs the latter) and `groth16_proof.json` to a directory. + +```sh +cargo build --release -p ziren-groth16-export --example export_groth16 +$WORK/target/release/examples/export_groth16 prove $ELF $CIRC $WORK/proof 10 +``` + +`replay` reads `groth16_proof.json` from that directory and checks its layout, without proving or +wrapping anything: + +```sh +$WORK/target/release/examples/export_groth16 replay $WORK/proof +``` + +`groth16` takes a saved compressed proof (`compressed.bin`, or an SDK compressed proof) and runs the +native shrink and both wraps, without proving the guest again. It overwrites `groth16_proof.json` in the same directory: + +```sh +$WORK/target/release/examples/export_groth16 groth16 $WORK/proof/compressed.bin $CIRC $WORK/proof/groth16_proof.json +``` + +The `prove` and `groth16` lines print `GROTH16_OK raw_proof_bytes=648 out=...`; `replay` prints +`REPLAY_OK selector=0x... public_inputs=3 raw_proof_bytes=648 path=...`. `wrap_groth16_bn254` +also runs gnark's own verification before returning, so a successful run is already +an internal check. + +Stage times from the first export run on the CPU with 24 threads: setup +about 0.3 s, core proving about 10 s, compression about 223 s, native shrink about 18 s, +and `wrap_bn254` plus `wrap_groth16_bn254` about 144 s, of which Groth16 proving is +about 11 s. The whole run takes about 400 s. Times vary with hardware. + +The exported JSON has these fields: + +- `public_inputs`: `[application key, committed-value digest, recursion root]`, as + decimal strings. +- `encoded_proof`: 256 bytes, eight big-endian 32-byte words (gnark `MarshalSolidity`). +- `groth16_vkey_hash`: 32 bytes. Its first four bytes are the verifier selector. + +## 2. Deploy and verify + +`scripts/groth16_verify.py` builds `contracts/ziren-groth16-verifier`, deploys +`Groth16Verifier` and `ZirenGroth16ProofVerifier`, and checks the proof: + +```sh +python3 scripts/groth16_verify.py --proof $WORK/proof/groth16_proof.json \ + --public-values $WORK/proof/public_values.bin \ + --rpc $RPC --report $WORK/groth16_report.json +``` + +The script: + +- converts the proof with `scripts/groth16_args.py` (selector, proof words, public inputs, packet); +- deploys the verifier, then the adapter with the selector, application key (`input[0]`) + and recursion root (`input[2]`) from the proof; +- calls the verifier directly and the adapter with the packet and digest, expecting `true`; +- sends the adapter's `verify` as a transaction for its gas, expecting success; +- expects `false` for a changed last proof byte, a changed digest, a replaced selector and a + truncated packet. + +It prints one line per check and the gas used, writes the same results to `--report`, and +exits non-zero if any check fails. For the fibonacci proof, the packet's selector is +`0xb3e14fe9`, which equals `VERIFIER_HASH()` in `ZKMVerifierGroth16.sol`, and the adapter's +application key is `0x002c7ab6…8c53`. + +The recursion root is the value the prover computes for the shrink (`recursion_vk_root`), +carried in the proof as `input[2]`. For the fibonacci run it is +`0x007ad39482c4460fe91d19534ecc20e27d374c3e17c0fe5f44d7cf7cb0fd2349`. + +The script computes the output digest from `--public-values`, the statement's `public_values.bin`. +The digest is SHA-256 of the committed public-value bytes: the file stores them with an 8-byte +little-endian length prefix, and the hash covers only the bytes after it. For the fibonacci +fixture this gives `0xd0abd303…2354`, the `output_digest` in its `statement.json`. Ziren computes +it as `PublicValues::hash()` (`crates/primitives/src/io.rs`), which uses SHA-256 unless the +`imm-wrap-vk` mode is set, in which case it uses BLAKE3; the script implements only SHA-256. +The adapter clears the top three bits of the digest to get the 253-bit committed value, which +must equal the proof's `input[1]`; the script exits before deploying if they differ. The +contract does not derive the digest from the proof, so the caller must supply it. In Metis the +output oracle passes `sha256(abi.encode(MetisAggregationOutputs))`. The fibonacci mapping is the +only one checked here; see [Caveats](#caveats). + +Use a transaction for +gas, not `cast estimate`: the adapter catches the verifier's revert and returns `false`, so an +estimate does not reflect a valid proof. + +The script builds with `contracts/ziren-groth16-verifier/foundry.toml` (solc 0.8.30, optimizer on). +Gas depends on the build, so the figures in section 4 are the ones from that run; use your own run's +`--report` output to compare. + +## 3. Unit tests for the adapter + +```sh +cd contracts/ziren-groth16-verifier +forge test +``` + +`ZirenGroth16ProofVerifierTest` uses a mock verifier. It checks the packet length and selector, the +digest mask, and the forwarding of the proof and the three public inputs. + +`Groth16VerifierTest` runs the real `Groth16Verifier` (`src/Groth16Verifier.sol`) on the fixture proof +in-process. It checks that the proof is accepted, that a changed proof word or public input is rejected, +and that the adapter accepts the fixture packet when it calls the real verifier. This test does not +replace section 2, which checks the deployed contracts on a node. + +## 4. Measured values + +Measured on 2026-11-05 on a local Osaka Anvil node (`--gas-limit 60000000`) on the box, with a +freshly exported Groth16 proof for the fibonacci guest (input 10). The verifier and adapter were built +by `contracts/ziren-groth16-verifier/foundry.toml` (solc 0.8.30, optimizer on), and `scripts/groth16_verify.py` +ran all checks in section 2 with exit code 0. + +| Cost | Gas | +| --- | --- | +| Verification transaction | 233,450 | +| of which calldata (388-byte `verify` call, 260-byte packet) | 5,092 | +| Execution (verification transaction minus 21,000 base and calldata) | 207,358 | +| Deployment, Groth16Verifier | 1,135,523 | +| Deployment, ZirenGroth16ProofVerifier | 326,771 | + +The calldata figure counts the full ABI-encoded `verify(bytes,bytes32)` call at 16 gas per non-zero +byte and 4 per zero byte. The proof changes with each export, so calldata and execution gas vary a +little between runs. + +## Caveats + +- **Recursion root.** The adapter takes the root from the proof's `public_inputs[2]`, computed + by the prover from its `vk_map.bin` as for the shrink. It is `0x007ad394…2349` for the + fibonacci run. +- **Exit code.** The Groth16 public inputs do not include the exit code. The recursion + core circuit asserts `exit_code == 0` (`Ziren/crates/recursion/circuit/src/machine/core_jagged.rs`), + but this document does not trace the full wrap chain to confirm that the constraint + holds for every path. +- **Digest mapping.** `input[1]` is the output digest with its top three bits cleared. + This matches the statement fixture for the fibonacci run (`0xd0ab…` masks to `0x10ab…`), + but the Metis aggregation outputs have not been run through this path. +- **Verifier pragma.** The copy in `contracts/ziren-groth16-verifier/src/` has pragma `0.8.30`. diff --git a/scripts/groth16_args.py b/scripts/groth16_args.py new file mode 100644 index 0000000..f06127a --- /dev/null +++ b/scripts/groth16_args.py @@ -0,0 +1,44 @@ +"""Convert an exported Groth16 proof JSON into verifier arguments. + +Prints the selector, the uint256[8] proof, the uint256[3] public inputs and the +packet (selector followed by the 256-byte proof) that ZirenGroth16ProofVerifier expects. + +Usage: python3 scripts/groth16_args.py +""" + +import json +import sys +from dataclasses import dataclass +from pathlib import Path + + +@dataclass(frozen=True) +class Arguments: + selector: str + proof: list[str] + inputs: list[str] + packet: str + + +def arguments(proof: dict) -> Arguments: + encoded = bytes.fromhex(proof["encoded_proof"]) + assert len(encoded) == 256, len(encoded) + selector = "0x" + bytes(proof["groth16_vkey_hash"][:4]).hex() + return Arguments( + selector=selector, + proof=["0x" + encoded[i : i + 32].hex() for i in range(0, 256, 32)], + inputs=["0x" + format(int(x), "064x") for x in proof["public_inputs"]], + packet=selector + encoded.hex(), + ) + + +def main() -> None: + args = arguments(json.loads(Path(sys.argv[1]).read_text())) + print("selector", args.selector) + print("proof", "[" + ",".join(args.proof) + "]") + print("input", "[" + ",".join(args.inputs) + "]") + print("packet", args.packet) + + +if __name__ == "__main__": + main() diff --git a/scripts/groth16_verify.py b/scripts/groth16_verify.py new file mode 100644 index 0000000..8abe01a --- /dev/null +++ b/scripts/groth16_verify.py @@ -0,0 +1,169 @@ +#!/usr/bin/env python3 +"""Deploy the Groth16 verifier and adapter, then verify a proof on a local EVM. + +Builds contracts/ziren-groth16-verifier, deploys Groth16Verifier and +ZirenGroth16ProofVerifier, checks that the adapter accepts the proof and +rejects the negative cases, and prints the gas used. The recursion root is +taken from the proof's public inputs. + +The output digest is computed from the committed public values: SHA-256 of the +bytes after the 8-byte little-endian length prefix in `public_values.bin`. Its top +three bits are cleared and must equal the proof's `input[1]`. + +Usage: python3 scripts/groth16_verify.py --proof \ + --public-values +""" + +import argparse +import hashlib +import json +import subprocess +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from groth16_args import arguments # noqa: E402 + +ROOT = Path(__file__).resolve().parents[1] +PROJECT = ROOT / "contracts" / "ziren-groth16-verifier" +ANVIL_DEPLOYER = "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266" # anvil account 0, local node only +ADAPTER_CALL = "verify(bytes,bytes32)(bool)" +ADAPTER_SEND = "verify(bytes,bytes32)" + + +def output_digest(public_values: Path) -> str: + data = public_values.read_bytes() + length = int.from_bytes(data[:8], "little") + if len(data) != 8 + length: + sys.exit(f"{public_values}: length prefix {length} does not match {len(data) - 8} bytes") + return "0x" + hashlib.sha256(data[8:]).hexdigest() + + +def cast(*args: str) -> str: + result = subprocess.run(["cast", *args], capture_output=True, text=True) + if result.returncode != 0: + sys.exit(f"cast {args[0]} failed: {result.stderr.strip()}") + return result.stdout.strip() + + +def call(rpc: str, address: str, signature: str, *args: str) -> str: + return cast("call", address, signature, *args, "--rpc-url", rpc) + + +def to_int(value) -> int: + return int(value, 16) if isinstance(value, str) and value.startswith("0x") else int(value) + + +def deploy(rpc: str, deployer: str, bytecode: str, gas_limit: int) -> tuple[str, int]: + receipt = json.loads( + cast("send", "--unlocked", "--from", deployer, "--rpc-url", rpc, + "--gas-limit", str(gas_limit), "--create", bytecode, "--json") + ) + if to_int(receipt["status"]) != 1: + sys.exit(f"deployment reverted: {receipt['transactionHash']}") + return receipt["contractAddress"], to_int(receipt["gasUsed"]) + + +def bytecode(artifact: str) -> str: + return json.loads((PROJECT / "out" / artifact).read_text())["bytecode"]["object"] + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("--proof", type=Path, required=True, + help="groth16_proof.json from export_groth16") + parser.add_argument("--public-values", type=Path, required=True, + help="public_values.bin of the statement the proof commits to") + parser.add_argument("--rpc", default="http://127.0.0.1:18602") + parser.add_argument("--deployer", default=ANVIL_DEPLOYER) + parser.add_argument("--report", type=Path, help="optional JSON file for the results") + args = parser.parse_args() + + subprocess.run(["forge", "build", "--silent"], cwd=PROJECT, check=True) + proof = arguments(json.loads(args.proof.read_text())) + app_key, committed, root = proof.inputs + digest = output_digest(args.public_values) + if int(digest, 16) & ((1 << 253) - 1) != int(committed, 16): + sys.exit(f"output digest {digest} does not match the proof's committed value {committed}") + + verifier, verifier_gas = deploy( + args.rpc, args.deployer, + bytecode("Groth16Verifier.sol/Groth16Verifier.json"), 8_000_000, + ) + ctor = cast("abi-encode", "constructor(address,bytes4,bytes32,uint256)", + verifier, proof.selector, app_key, root) + adapter, adapter_gas = deploy( + args.rpc, args.deployer, + bytecode("ZirenGroth16ProofVerifier.sol/ZirenGroth16ProofVerifier.json") + ctor[2:], + 5_000_000, + ) + + packet = proof.packet + flipped = digest[:-1] + ("0" if digest[-1] != "0" else "1") + proof_words = f"[{','.join(proof.proof)}]" + public_inputs = f"[{','.join(proof.inputs)}]" + + # Each check maps a name to (expected, actual). + checks = { + "direct Groth16Verifier.Verify (no revert)": ( + "0x", + call(args.rpc, verifier, "Verify(uint256[8],uint256[3])", proof_words, public_inputs), + ), + "adapter verify": ( + "true", + call(args.rpc, adapter, ADAPTER_CALL, packet, digest), + ), + "tampered last proof byte": ( + "false", + call(args.rpc, adapter, ADAPTER_CALL, packet[:-2] + "00", digest), + ), + "digest changed": ( + "false", + call(args.rpc, adapter, ADAPTER_CALL, packet, flipped), + ), + "selector replaced": ( + "false", + call(args.rpc, adapter, ADAPTER_CALL, "0x00000000" + packet[10:], digest), + ), + "truncated packet": ( + "false", + call(args.rpc, adapter, ADAPTER_CALL, packet[:100], digest), + ), + } + + receipt = json.loads( + cast("send", "--unlocked", "--from", args.deployer, "--rpc-url", args.rpc, + "--gas-limit", "2000000", adapter, ADAPTER_SEND, packet, digest, "--json") + ) + verify_gas = to_int(receipt["gasUsed"]) + succeeded = to_int(receipt["status"]) == 1 + checks["adapter verify transaction"] = ("success", "success" if succeeded else "reverted") + + results = { + "verifier": verifier, + "adapter": adapter, + "gas": { + "verifier_deployment": verifier_gas, + "adapter_deployment": adapter_gas, + "verify_transaction": verify_gas, + "verify_calldata_packet_bytes": (len(packet) - 2) // 2, + }, + "checks": { + name: {"expected": want, "actual": got, "ok": got == want} + for name, (want, got) in checks.items() + }, + } + + for name, check in results["checks"].items(): + print(f"{'ok ' if check['ok'] else 'FAIL'} {name}: {check['actual']}") + for name, value in results["gas"].items(): + print(f"gas {name}: {value}") + if args.report: + args.report.write_text(json.dumps(results, indent=2) + "\n") + if not all(check["ok"] for check in results["checks"].values()): + sys.exit(1) + + +if __name__ == "__main__": + main()