diff --git a/src/libraries/verifier/IOpenVmHalo2Verifier.sol b/src/libraries/verifier/IOpenVmHalo2Verifier.sol new file mode 100644 index 00000000..4f710cb9 --- /dev/null +++ b/src/libraries/verifier/IOpenVmHalo2Verifier.sol @@ -0,0 +1,25 @@ +// SPDX-License-Identifier: MIT + +pragma solidity ^0.8.24; + +/// @notice Typed entry point of the OpenVM Halo2 verifier wrapper +/// (`OpenVmHalo2Verifier`, selector `0x24270d54`). +/// @dev The wrapper formats the payload and self-calls its inherited +/// `Halo2Verifier` fallback. Reaching it through this typed function means the +/// call selector is fixed by the compiler, never taken from caller bytes. +interface IOpenVmHalo2Verifier { + /// @param publicValues The public values revealed by the guest program. For + /// Scroll this is the 32-byte `publicInputHash`. + /// @param proofData `abi.encodePacked(kzgAccumulator, proofSuffix)`, i.e. the + /// bundle proof exactly as `ScrollChain` forwards it. + /// @param appExeCommit Commitment to the application executable. For Scroll + /// this is the fixed `verifierDigest1`. + /// @param appVmCommit Commitment to the VM configuration. For Scroll this is + /// the fixed `verifierDigest2`. + function verify( + bytes calldata publicValues, + bytes calldata proofData, + bytes32 appExeCommit, + bytes32 appVmCommit + ) external view; +} diff --git a/src/libraries/verifier/ZkEvmVerifierPostFeynman.sol b/src/libraries/verifier/ZkEvmVerifierPostFeynman.sol index 44d1f744..c4ecd2e0 100644 --- a/src/libraries/verifier/ZkEvmVerifierPostFeynman.sol +++ b/src/libraries/verifier/ZkEvmVerifierPostFeynman.sol @@ -3,8 +3,9 @@ pragma solidity =0.8.24; import {IZkEvmVerifierV2} from "./IZkEvmVerifier.sol"; +import {IOpenVmHalo2Verifier} from "./IOpenVmHalo2Verifier.sol"; -// solhint-disable no-inline-assembly +// solhint-disable no-empty-blocks contract ZkEvmVerifierPostFeynman is IZkEvmVerifierV2 { /********** @@ -14,10 +15,19 @@ contract ZkEvmVerifierPostFeynman is IZkEvmVerifierV2 { /// @dev Thrown when bundle recursion zk proof verification is failed. error VerificationFailed(); + /// @dev Thrown when a verifier digest is not an element of the BN254 scalar field. + error InvalidVerifierDigest(); + + /// @dev Thrown when the plonk verifier address has no code. + error InvalidPlonkVerifier(); + /************* * Constants * *************/ + /// @dev The BN254 scalar field modulus. The wrapper rejects commitments at or above it. + uint256 private constant BN254_SCALAR_MODULUS = 0x30644e72e131a029b85045b68181585d2833e84879b9709143e1f593f0000001; + /// @notice The address of highly optimized plonk verifier contract. address public immutable plonkVerifier; @@ -42,6 +52,10 @@ contract ZkEvmVerifierPostFeynman is IZkEvmVerifierV2 { bytes32 _verifierDigest2, uint256 _protocolVersion ) { + if (_verifier.code.length == 0) revert InvalidPlonkVerifier(); + if (uint256(_verifierDigest1) >= BN254_SCALAR_MODULUS) revert InvalidVerifierDigest(); + if (uint256(_verifierDigest2) >= BN254_SCALAR_MODULUS) revert InvalidVerifierDigest(); + plonkVerifier = _verifier; verifierDigest1 = _verifierDigest1; verifierDigest2 = _verifierDigest2; @@ -60,47 +74,20 @@ contract ZkEvmVerifierPostFeynman is IZkEvmVerifierV2 { /// | 8 bytes | 32 bytes | 4 bytes | 32 bytes | 32 bytes | 32 bytes | 32 bytes | 32 bytes | 33 bytes | /// ``` function verify(bytes calldata bundleProof, bytes calldata publicInput) external view override { - address _verifier = plonkVerifier; - bytes32 _verifierDigest1 = verifierDigest1; - bytes32 _verifierDigest2 = verifierDigest2; bytes32 publicInputHash = keccak256(abi.encodePacked(protocolVersion, publicInput)); - bool success; - - // 1. the first 12 * 32 (0x180) bytes of `bundleProof` is `accumulator` - // 2. the rest bytes of `bundleProof` is the actual `bundle_proof` - // 3. Inserted between `accumulator` and `bundle_proof` are - // 32 * 34 (0x440) bytes, such that: - // | start | end | field | - // |---------------|---------------|-------------------------| - // | 0x00 | 0x180 | bundleProof[0x00:0x180] | - // | 0x180 | 0x180 + 0x20 | verifierDigest1 | - // | 0x180 + 0x20 | 0x180 + 0x40 | verifierDigest2 | - // | 0x180 + 0x40 | 0x180 + 0x60 | publicInputHash[0] | - // | 0x180 + 0x60 | 0x180 + 0x80 | publicInputHash[1] | - // ... - // | 0x180 + 0x420 | 0x180 + 0x440 | publicInputHash[31] | - // | 0x180 + 0x440 | dynamic | bundleProof[0x180:] | - assembly { - let p := mload(0x40) - // 1. copy the accumulator's 0x180 bytes - calldatacopy(p, bundleProof.offset, 0x180) - // 2. insert the public input's 0x440 bytes - mstore(add(p, 0x180), _verifierDigest1) // verifierDigest1 - mstore(add(p, 0x1a0), _verifierDigest2) // verifierDigest2 - for { - let i := 0 - } lt(i, 0x400) { - i := add(i, 0x20) - } { - mstore(add(p, sub(0x5a0, i)), and(publicInputHash, 0xff)) - publicInputHash := shr(8, publicInputHash) - } - // 3. copy all remaining bytes from bundleProof - calldatacopy(add(p, 0x5c0), add(bundleProof.offset, 0x180), sub(bundleProof.length, 0x180)) - // 4. call plonk verifier - success := staticcall(gas(), _verifier, p, add(bundleProof.length, 0x440), 0x00, 0x00) - } - if (!success) { + + // Use the wrapper's typed entry point, never a raw call: the wrapper has a function + // dispatcher, so raw calldata led by `bundleProof` could select `verify` itself with + // attacker-chosen public values. The wrapper lays out the same payload for its + // Halo2 fallback that this contract used to build by hand. + try + IOpenVmHalo2Verifier(plonkVerifier).verify( + abi.encodePacked(publicInputHash), + bundleProof, + verifierDigest1, + verifierDigest2 + ) + {} catch { revert VerificationFailed(); } } diff --git a/src/test/ZkEvmVerifierPostFeynman.t.sol b/src/test/ZkEvmVerifierPostFeynman.t.sol new file mode 100644 index 00000000..b480de08 --- /dev/null +++ b/src/test/ZkEvmVerifierPostFeynman.t.sol @@ -0,0 +1,164 @@ +// SPDX-License-Identifier: MIT + +pragma solidity =0.8.24; + +import {DSTestPlus} from "solmate/test/utils/DSTestPlus.sol"; +import {Vm} from "forge-std/Vm.sol"; + +import {ZkEvmVerifierPostFeynman} from "../libraries/verifier/ZkEvmVerifierPostFeynman.sol"; +import {IOpenVmHalo2Verifier} from "../libraries/verifier/IOpenVmHalo2Verifier.sol"; + +/// @dev Faithful stand-in for the OpenVM 2.0 `OpenVmHalo2Verifier` wrapper. It is +/// `view`, like the real one, and reproduces its external surface: the typed +/// `verify(...)` with selector 0x24270d54, the same length and BN254-modulus checks, +/// and the `proofData[0:4] == 0` assertion. A proof "verifies" only when the tuple +/// (publicValues, proofData, appExeCommit, appVmCommit) equals the one the honest +/// prover produced; this models that the wrapper binds the values it is given, the +/// property Option A' relies on. +contract MockOpenVmWrapper { + uint256 internal constant BN254_SCALAR_MODULUS = 0x30644e72e131a029b85045b68181585d2833e84879b9709143e1f593f0000001; + uint256 internal constant PROOF_DATA_LENGTH = (12 + 43) * 32; // 1760 + uint256 internal constant PUBLIC_VALUES_LENGTH = 32; + + error InvalidPublicValuesLength(uint256 expected, uint256 actual); + error InvalidProofDataLength(uint256 expected, uint256 actual); + error InvalidAppExeCommit(bytes32 actual); + error InvalidAppVmCommit(bytes32 actual); + error ProofVerificationFailed(); + + bytes32 public immutable expExe; + bytes32 public immutable expVm; + bytes32 public immutable expPublicValuesHash; + bytes32 public immutable expProofHash; + + constructor( + bytes32 _expExe, + bytes32 _expVm, + bytes32 _expPublicValuesHash, + bytes32 _expProofHash + ) { + expExe = _expExe; + expVm = _expVm; + expPublicValuesHash = _expPublicValuesHash; + expProofHash = _expProofHash; + } + + function verify( + bytes calldata publicValues, + bytes calldata proofData, + bytes32 appExeCommit, + bytes32 appVmCommit + ) external view { + if (publicValues.length != PUBLIC_VALUES_LENGTH) { + revert InvalidPublicValuesLength(PUBLIC_VALUES_LENGTH, publicValues.length); + } + if (proofData.length != PROOF_DATA_LENGTH) revert InvalidProofDataLength(PROOF_DATA_LENGTH, proofData.length); + if (uint256(appExeCommit) >= BN254_SCALAR_MODULUS) revert InvalidAppExeCommit(appExeCommit); + if (uint256(appVmCommit) >= BN254_SCALAR_MODULUS) revert InvalidAppVmCommit(appVmCommit); + assert(bytes4(proofData[0:4]) == bytes4(0x00000000)); + + bool ok = appExeCommit == expExe && + appVmCommit == expVm && + keccak256(publicValues) == expPublicValuesHash && + keccak256(proofData) == expProofHash; + if (!ok) revert ProofVerificationFailed(); + } + + fallback() external {} +} + +contract ZkEvmVerifierPostFeynmanTest is DSTestPlus { + Vm internal constant vm = Vm(address(uint160(uint256(keccak256("hevm cheat code"))))); + + uint256 internal constant PROOF_DATA_LENGTH = (12 + 43) * 32; // 1760 + uint256 internal constant PROTOCOL_VERSION = 10; + + bytes32 internal constant DIGEST1 = bytes32(uint256(0x1111)); + bytes32 internal constant DIGEST2 = bytes32(uint256(0x2222)); + + MockOpenVmWrapper internal wrapper; + ZkEvmVerifierPostFeynman internal verifier; + + bytes internal honestProof; + bytes internal honestPublicInput; + bytes32 internal honestPiHash; + + function setUp() public { + // A well-formed bundle proof: 1760 bytes, first 4 bytes zero (accumulator limb). + honestProof = new bytes(PROOF_DATA_LENGTH); + for (uint256 i = 4; i < PROOF_DATA_LENGTH; i++) honestProof[i] = bytes1(uint8(((i * 7) % 251) + 1)); + + honestPublicInput = abi.encodePacked(uint64(534352), keccak256("pi"), uint32(1)); + honestPiHash = keccak256(abi.encodePacked(uint256(PROTOCOL_VERSION), honestPublicInput)); + + wrapper = new MockOpenVmWrapper( + DIGEST1, + DIGEST2, + keccak256(abi.encodePacked(honestPiHash)), + keccak256(honestProof) + ); + verifier = new ZkEvmVerifierPostFeynman(address(wrapper), DIGEST1, DIGEST2, PROTOCOL_VERSION); + } + + /// The call must reach the wrapper through selector 0x24270d54, carrying the + /// public-input hash as `publicValues` and the fixed digests as the commitments. + /// `bundleProof` is passed as the `proofData` argument, so its bytes can never + /// become the call selector — the old attack is structurally impossible. + function test_typedCall_dispatchAndArgs() external { + bytes memory expectedCalldata = abi.encodeWithSelector( + IOpenVmHalo2Verifier.verify.selector, + abi.encodePacked(honestPiHash), + honestProof, + DIGEST1, + DIGEST2 + ); + vm.expectCall(address(wrapper), expectedCalldata); + verifier.verify(honestProof, honestPublicInput); // must not revert + } + + /// Public-input binding: the same proof is rejected for a different public input, + /// because `publicInputHash` (passed as publicValues) no longer matches. This is + /// the property the vulnerable raw path lost. + function test_forgedPublicInputRejected() external { + bytes memory forged = abi.encodePacked(honestPublicInput, uint8(1)); + hevm.expectRevert(ZkEvmVerifierPostFeynman.VerificationFailed.selector); + verifier.verify(honestProof, forged); + } + + /// A wrapper-side revert (wrong length, bad commitment, failed proof) surfaces as + /// VerificationFailed rather than bubbling the raw error. + function test_wrapperRevertSurfacedAsVerificationFailed() external { + bytes memory wrongLen = new bytes(PROOF_DATA_LENGTH - 32); // fails the length check + hevm.expectRevert(ZkEvmVerifierPostFeynman.VerificationFailed.selector); + verifier.verify(wrongLen, honestPublicInput); + } + + /// The constructor accepts a digest if and only if it is below the BN254 scalar field modulus. + function testFuzz_constructorDigestRange(uint256 digest1, uint256 digest2) external { + uint256 modulus = 0x30644e72e131a029b85045b68181585d2833e84879b9709143e1f593f0000001; + if (digest1 >= modulus || digest2 >= modulus) { + hevm.expectRevert(ZkEvmVerifierPostFeynman.InvalidVerifierDigest.selector); + } + new ZkEvmVerifierPostFeynman(address(wrapper), bytes32(digest1), bytes32(digest2), PROTOCOL_VERSION); + } + + function test_constructorDigestBoundary() external { + uint256 modulus = 0x30644e72e131a029b85045b68181585d2833e84879b9709143e1f593f0000001; + new ZkEvmVerifierPostFeynman(address(wrapper), bytes32(modulus - 1), bytes32(modulus - 1), PROTOCOL_VERSION); + + hevm.expectRevert(ZkEvmVerifierPostFeynman.InvalidVerifierDigest.selector); + new ZkEvmVerifierPostFeynman(address(wrapper), bytes32(modulus), DIGEST2, PROTOCOL_VERSION); + + hevm.expectRevert(ZkEvmVerifierPostFeynman.InvalidVerifierDigest.selector); + new ZkEvmVerifierPostFeynman(address(wrapper), DIGEST1, bytes32(modulus), PROTOCOL_VERSION); + } + + /// The constructor rejects a plonk verifier without code, including the zero address. + function test_constructorRejectsVerifierWithoutCode() external { + hevm.expectRevert(ZkEvmVerifierPostFeynman.InvalidPlonkVerifier.selector); + new ZkEvmVerifierPostFeynman(address(0), DIGEST1, DIGEST2, PROTOCOL_VERSION); + + hevm.expectRevert(ZkEvmVerifierPostFeynman.InvalidPlonkVerifier.selector); + new ZkEvmVerifierPostFeynman(address(0xBEEF), DIGEST1, DIGEST2, PROTOCOL_VERSION); + } +} diff --git a/src/test/ZkEvmVerifierPostFeynmanEncoding.t.sol b/src/test/ZkEvmVerifierPostFeynmanEncoding.t.sol new file mode 100644 index 00000000..fa070eca --- /dev/null +++ b/src/test/ZkEvmVerifierPostFeynmanEncoding.t.sol @@ -0,0 +1,97 @@ +// SPDX-License-Identifier: MIT + +pragma solidity =0.8.24; + +import {Test} from "forge-std/Test.sol"; +import {Vm, VmSafe} from "forge-std/Vm.sol"; + +import {ZkEvmVerifierPostFeynmanLegacy} from "./legacy/ZkEvmVerifierPostFeynmanLegacy.sol"; +import {ZkEvmVerifierPostFeynman} from "../libraries/verifier/ZkEvmVerifierPostFeynman.sol"; +// Vendored verbatim from scroll-tech/zkvm-prover@bf88715 releases/dev/verifier/verifier.sol +// (identical to openvm-solidity-sdk src/v2.0-base); only the pragma is relaxed. Its +// `Halo2Verifier` base is a stub that accepts every payload. +import {OpenVmHalo2Verifier} from "./openvm/OpenVmHalo2Verifier.sol"; + +/// Differential test: the payload that reaches the Halo2 fallback must be byte-identical +/// whether it is built by the old raw path (`ZkEvmVerifierPostFeynmanLegacy`) or by the OpenVM +/// wrapper's `_constructProof` behind the typed call (`ZkEvmVerifierPostFeynman`). +contract ZkEvmVerifierPostFeynmanEncodingTest is Test { + uint256 internal constant BN254_SCALAR_MODULUS = 0x30644e72e131a029b85045b68181585d2833e84879b9709143e1f593f0000001; + uint256 internal constant ACCUMULATOR_WORDS = 12; + uint256 internal constant SUFFIX_WORDS = 43; + + OpenVmHalo2Verifier internal wrapper; + + function setUp() public { + wrapper = new OpenVmHalo2Verifier(); + } + + function testFuzz_oldAndTypedPayloadsMatch( + bytes32 seed, + bytes calldata publicInput, + uint256 digest1, + uint256 digest2, + uint256 protocolVersion + ) external { + // The wrapper rejects commitments outside the scalar field; the live digests are inside. + bytes32 d1 = bytes32(bound(digest1, 0, BN254_SCALAR_MODULUS - 1)); + bytes32 d2 = bytes32(bound(digest2, 0, BN254_SCALAR_MODULUS - 1)); + bytes memory bundleProof = _bundleProof(seed); + + ZkEvmVerifierPostFeynmanLegacy oldVerifier = new ZkEvmVerifierPostFeynmanLegacy( + address(wrapper), + d1, + d2, + protocolVersion + ); + ZkEvmVerifierPostFeynman newVerifier = new ZkEvmVerifierPostFeynman(address(wrapper), d1, d2, protocolVersion); + + // Old path: the raw staticcall from the verifier into the wrapper's fallback. + vm.startStateDiffRecording(); + oldVerifier.verify(bundleProof, publicInput); + bytes memory oldPayload = _calldataOf(vm.stopAndReturnStateDiff(), address(oldVerifier)); + + // New path: the wrapper's self-call into its own fallback. + vm.startStateDiffRecording(); + newVerifier.verify(bundleProof, publicInput); + bytes memory newPayload = _calldataOf(vm.stopAndReturnStateDiff(), address(wrapper)); + + assertEq(oldPayload.length, (ACCUMULATOR_WORDS + 2 + 32 + SUFFIX_WORDS) * 32); + assertEq(newPayload, oldPayload); + } + + /// The single call from `accessor` into the wrapper, which must be a successful staticcall. + function _calldataOf(VmSafe.AccountAccess[] memory accesses, address accessor) + internal + view + returns (bytes memory) + { + bytes memory data; + uint256 found; + for (uint256 i = 0; i < accesses.length; i++) { + VmSafe.AccountAccess memory a = accesses[i]; + if (a.account != address(wrapper) || a.accessor != accessor) continue; + assertEq(uint256(a.kind), uint256(VmSafe.AccountAccessKind.StaticCall)); + assertFalse(a.reverted); + data = a.data; + found++; + } + assertEq(found, 1); + return data; + } + + /// A 1760-byte bundle proof. Every word is random except that the first accumulator + /// word has its top 4 bytes cleared: a valid proof always has this (88-bit limbs), and + /// it is what makes the old raw call reach the fallback. + function _bundleProof(bytes32 seed) internal pure returns (bytes memory proof) { + uint256 words = ACCUMULATOR_WORDS + SUFFIX_WORDS; + proof = new bytes(words * 32); + for (uint256 i = 0; i < words; i++) { + uint256 word = uint256(keccak256(abi.encode(seed, i))); + if (i == 0) word >>= 32; + assembly { + mstore(add(add(proof, 0x20), mul(i, 0x20)), word) + } + } + } +} diff --git a/src/test/legacy/ZkEvmVerifierPostFeynmanLegacy.sol b/src/test/legacy/ZkEvmVerifierPostFeynmanLegacy.sol new file mode 100644 index 00000000..d71112fc --- /dev/null +++ b/src/test/legacy/ZkEvmVerifierPostFeynmanLegacy.sol @@ -0,0 +1,109 @@ +// SPDX-License-Identifier: MIT + +pragma solidity =0.8.24; + +import {IZkEvmVerifierV2} from "../../libraries/verifier/IZkEvmVerifier.sol"; + +// solhint-disable no-inline-assembly + +/// @dev Frozen copy of `ZkEvmVerifierPostFeynman` before the typed-call fix (raw `staticcall` +/// whose leading bytes come from `bundleProof`). Test-only reference for the encoding fuzz. +contract ZkEvmVerifierPostFeynmanLegacy is IZkEvmVerifierV2 { + /********** + * Errors * + **********/ + + /// @dev Thrown when bundle recursion zk proof verification is failed. + error VerificationFailed(); + + /************* + * Constants * + *************/ + + /// @notice The address of highly optimized plonk verifier contract. + address public immutable plonkVerifier; + + /// @notice A predetermined digest for the `plonkVerifier`. + bytes32 public immutable verifierDigest1; + + /// @notice A predetermined digest for the `plonkVerifier`. + bytes32 public immutable verifierDigest2; + + /// @notice The version of the protocol. + /// @dev The protocol version for Validium@v1 onwards encodes `domain` and `version` such that + /// @dev protocolVersion = (domain << 6) + version. + uint256 public immutable protocolVersion; + + /*************** + * Constructor * + ***************/ + + constructor( + address _verifier, + bytes32 _verifierDigest1, + bytes32 _verifierDigest2, + uint256 _protocolVersion + ) { + plonkVerifier = _verifier; + verifierDigest1 = _verifierDigest1; + verifierDigest2 = _verifierDigest2; + protocolVersion = _protocolVersion; + } + + /************************* + * Public View Functions * + *************************/ + + /// @inheritdoc IZkEvmVerifierV2 + /// + /// @dev Encoding for `publicInput`. And this is exactly the same as `ZkEvmVerifierV2`. + /// ```text + /// | layer2ChainId | msgQueueHash | numBatches | prevStateRoot | prevBatchHash | postStateRoot | batchHash | withdrawRoot | validium ? encryptionKey | + /// | 8 bytes | 32 bytes | 4 bytes | 32 bytes | 32 bytes | 32 bytes | 32 bytes | 32 bytes | 33 bytes | + /// ``` + function verify(bytes calldata bundleProof, bytes calldata publicInput) external view override { + address _verifier = plonkVerifier; + bytes32 _verifierDigest1 = verifierDigest1; + bytes32 _verifierDigest2 = verifierDigest2; + bytes32 publicInputHash = keccak256(abi.encodePacked(protocolVersion, publicInput)); + bool success; + + // 1. the first 12 * 32 (0x180) bytes of `bundleProof` is `accumulator` + // 2. the rest bytes of `bundleProof` is the actual `bundle_proof` + // 3. Inserted between `accumulator` and `bundle_proof` are + // 32 * 34 (0x440) bytes, such that: + // | start | end | field | + // |---------------|---------------|-------------------------| + // | 0x00 | 0x180 | bundleProof[0x00:0x180] | + // | 0x180 | 0x180 + 0x20 | verifierDigest1 | + // | 0x180 + 0x20 | 0x180 + 0x40 | verifierDigest2 | + // | 0x180 + 0x40 | 0x180 + 0x60 | publicInputHash[0] | + // | 0x180 + 0x60 | 0x180 + 0x80 | publicInputHash[1] | + // ... + // | 0x180 + 0x420 | 0x180 + 0x440 | publicInputHash[31] | + // | 0x180 + 0x440 | dynamic | bundleProof[0x180:] | + assembly { + let p := mload(0x40) + // 1. copy the accumulator's 0x180 bytes + calldatacopy(p, bundleProof.offset, 0x180) + // 2. insert the public input's 0x440 bytes + mstore(add(p, 0x180), _verifierDigest1) // verifierDigest1 + mstore(add(p, 0x1a0), _verifierDigest2) // verifierDigest2 + for { + let i := 0 + } lt(i, 0x400) { + i := add(i, 0x20) + } { + mstore(add(p, sub(0x5a0, i)), and(publicInputHash, 0xff)) + publicInputHash := shr(8, publicInputHash) + } + // 3. copy all remaining bytes from bundleProof + calldatacopy(add(p, 0x5c0), add(bundleProof.offset, 0x180), sub(bundleProof.length, 0x180)) + // 4. call plonk verifier + success := staticcall(gas(), _verifier, p, add(bundleProof.length, 0x440), 0x00, 0x00) + } + if (!success) { + revert VerificationFailed(); + } + } +} diff --git a/src/test/openvm/Halo2Verifier.sol b/src/test/openvm/Halo2Verifier.sol new file mode 100644 index 00000000..5768cecf --- /dev/null +++ b/src/test/openvm/Halo2Verifier.sol @@ -0,0 +1,12 @@ +// SPDX-License-Identifier: MIT + +pragma solidity ^0.8.19; + +// solhint-disable no-empty-blocks + +/// @dev Test stub for the `snark-verifier` output. It accepts every payload, so the +/// vendored `OpenVmHalo2Verifier` wrapper runs unchanged and its self-call calldata +/// can be recorded. The wrapper ignores the fallback's return data. +contract Halo2Verifier { + fallback() external {} +} diff --git a/src/test/openvm/OpenVmHalo2Verifier.sol b/src/test/openvm/OpenVmHalo2Verifier.sol new file mode 100644 index 00000000..e3cb8295 --- /dev/null +++ b/src/test/openvm/OpenVmHalo2Verifier.sol @@ -0,0 +1,175 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.19; + +import {Halo2Verifier} from "./Halo2Verifier.sol"; +import {IOpenVmHalo2Verifier} from "./interfaces/IOpenVmHalo2Verifier.sol"; + +type MemoryPointer is uint256; + +// BN254 scalar field modulus (Fr), as specified in EIP-197: +// https://eips.ethereum.org/EIPS/eip-197 +uint256 constant BN254_SCALAR_MODULUS = 0x30644e72e131a029b85045b68181585d2833e84879b9709143e1f593f0000001; + +/// @notice This contract provides a thin wrapper around the Halo2 verifier +/// outputted by `snark-verifier`, exposing a more user-friendly interface. +contract OpenVmHalo2Verifier is Halo2Verifier, IOpenVmHalo2Verifier { + /// @dev Invalid public values length + error InvalidPublicValuesLength(uint256 expected, uint256 actual); + + /// @dev Invalid proof data length + error InvalidProofDataLength(uint256 expected, uint256 actual); + + /// @dev Invalid app executable commitment + error InvalidAppExeCommit(bytes32 actual); + + /// @dev Invalid app VM commitment + error InvalidAppVmCommit(bytes32 actual); + + /// @dev Proof verification failed + error ProofVerificationFailed(); + + /// @dev The length of the proof data, in bytes. + uint256 private constant PROOF_DATA_LENGTH = (12 + 43) * 32; + + /// @dev The length of the public values, in bytes. This value is set by + /// OpenVM and is guaranteed to be no larger than 8192. + uint256 private constant PUBLIC_VALUES_LENGTH = 32; + + /// @dev The length of the full proof, in bytes + uint256 private constant FULL_PROOF_LENGTH = (12 + 2 + PUBLIC_VALUES_LENGTH + 43) * 32; + + /// @dev The version of OpenVM that generated this verifier. + string private constant OPENVM_VERSION = "2.0"; + + /// @notice A wrapper that constructs the proof into the right format for + /// use with the `snark-verifier` verification. + /// + /// @dev The verifier expected proof format is: + /// proof[..12 * 32]: KZG accumulator + /// proof[12 * 32..13 * 32]: app exe commit + /// proof[13 * 32..14 * 32]: app vm commit + /// proof[14 * 32..(14 + PUBLIC_VALUES_LENGTH) * 32]: publicValues[0..PUBLIC_VALUES_LENGTH] + /// proof[(14 + PUBLIC_VALUES_LENGTH) * 32..]: Proof Suffix + /// + /// @param publicValues The PVs revealed by the OpenVM guest program. + /// @param proofData All components of the proof except the public values and + /// app exe and vm commits. The expected format is: + /// `abi.encodePacked(kzgAccumulator, proofSuffix)` + /// @param appExeCommit The commitment to the OpenVM application executable whose execution + /// is being verified. + /// @param appVmCommit The commitment to the VM configuration. + function verify( + bytes calldata publicValues, + bytes calldata proofData, + bytes32 appExeCommit, + bytes32 appVmCommit + ) external view { + if (publicValues.length != PUBLIC_VALUES_LENGTH) { + revert InvalidPublicValuesLength(PUBLIC_VALUES_LENGTH, publicValues.length); + } + if (proofData.length != PROOF_DATA_LENGTH) revert InvalidProofDataLength(PROOF_DATA_LENGTH, proofData.length); + if (uint256(appExeCommit) >= BN254_SCALAR_MODULUS) revert InvalidAppExeCommit(appExeCommit); + if (uint256(appVmCommit) >= BN254_SCALAR_MODULUS) revert InvalidAppVmCommit(appVmCommit); + + // Other than the fallback() in `Halo2Verifier`, there is only one + // function selector on the external ABI: `verify(..)`, which has + // selector 0x24270d54. If `proofData` ever began with 0x24270d54, this + // function would be called again instead of hitting the fallback. + // + // If a valid proof ever began with 0x24270d54, it would fail to verify. + // However, `snark-verifier`'s proof structure guarantees that the first + // 12 words of the proof are the KZG accumulator limbs. Each limb holds + // 88 bits, so the first 4 bytes of the proof will always be + // 0x00000000. + // + // As an extra layer of protection, we assert that the first 4 bytes of + // `proofData` are 0x00000000 before self-calling into the fallback + // verifier. + assert(bytes4(proofData[0:4]) == bytes4(0x00000000)); + + // We will format the public values and construct the full proof payload + // below. + + MemoryPointer proofPtr = _constructProof(publicValues, proofData, appExeCommit, appVmCommit); + + uint256 fullProofLength = FULL_PROOF_LENGTH; + + /// @solidity memory-safe-assembly + assembly { + // Self-call using the proof as calldata + if iszero(staticcall(gas(), address(), proofPtr, fullProofLength, 0, 0)) { + mstore(0x00, 0xd611c318) // ProofVerificationFailed() + revert(0x1c, 0x04) + } + } + } + + /// @dev The assembly code should perform the same function as the following + /// solidity code: + // + /// ```solidity + /// bytes memory proof = + /// abi.encodePacked(proofData[0:0x180], appExeCommit, appVmCommit, publicValuesPayload, proofData[0x180:]); + /// ``` + // + /// where `publicValuesPayload` is a memory payload with each byte in + /// `publicValues` separated into its own `bytes32` word. + /// + /// This function does not clean the memory it allocates. Since it is the + /// only memory write that occurs in the call frame, we know that + /// the memory region cannot have been dirtied. + /// + /// @return proofPtr Memory pointer to the beginning of the constructed + /// proof. This pointer does not follow `bytes memory` semantics. + function _constructProof( + bytes calldata publicValues, + bytes calldata proofData, + bytes32 appExeCommit, + bytes32 appVmCommit + ) internal pure returns (MemoryPointer proofPtr) { + uint256 fullProofLength = FULL_PROOF_LENGTH; + + // The expected proof format using hex offsets: + // + // proof[..0x180]: KZG accumulator + // proof[0x180..0x1a0]: app exe commit + // proof[0x1a0..0x1c0]: app vm commit + // proof[0x1c0..(0x1c0 + PUBLIC_VALUES_LENGTH * 32)]: publicValues[0..PUBLIC_VALUES_LENGTH] + // proof[(0x1c0 + PUBLIC_VALUES_LENGTH * 32)..]: Proof Suffix + + /// @solidity memory-safe-assembly + assembly { + proofPtr := mload(0x40) + // Allocate the memory as a safety measure. + mstore(0x40, add(proofPtr, fullProofLength)) + + // Copy the KZG accumulator (length 0x180) into the beginning of + // the memory buffer + calldatacopy(proofPtr, proofData.offset, 0x180) + + // Copy the App Exe Commit and App Vm Commit into the memory buffer + mstore(add(proofPtr, 0x180), appExeCommit) + mstore(add(proofPtr, 0x1a0), appVmCommit) + + // Copy the Proof Suffix (length 43 * 32 = 0x560) into the + // end of the memory buffer, leaving PUBLIC_VALUES_LENGTH words in + // between for the publicValuesPayload. + // + // Begin copying from the end of the KZG accumulator in the + // calldata buffer (0x180) + let proofSuffixOffset := add(0x1c0, shl(5, PUBLIC_VALUES_LENGTH)) + calldatacopy(add(proofPtr, proofSuffixOffset), add(proofData.offset, 0x180), 0x560) + + // Copy each byte of the public values into the proof. It copies the + // most significant bytes of public values first. + let publicValuesMemOffset := add(add(proofPtr, 0x1c0), 0x1f) + for { + let i := 0 + } iszero(eq(i, PUBLIC_VALUES_LENGTH)) { + i := add(i, 1) + } { + calldatacopy(add(publicValuesMemOffset, shl(5, i)), add(publicValues.offset, i), 0x01) + } + } + } +} diff --git a/src/test/openvm/interfaces/IOpenVmHalo2Verifier.sol b/src/test/openvm/interfaces/IOpenVmHalo2Verifier.sol new file mode 100644 index 00000000..ab759789 --- /dev/null +++ b/src/test/openvm/interfaces/IOpenVmHalo2Verifier.sol @@ -0,0 +1,11 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.0; + +interface IOpenVmHalo2Verifier { + function verify( + bytes calldata publicValues, + bytes calldata proofData, + bytes32 appExeCommit, + bytes32 appVmCommit + ) external view; +}