Skip to content

feat: add ZK authorizations to CW #346

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 20 commits into from
May 26, 2025
Merged

feat: add ZK authorizations to CW #346

merged 20 commits into from
May 26, 2025

Conversation

keyleu
Copy link
Contributor

@keyleu keyleu commented May 13, 2025

Add ZK Authorizations in a similar fashion than the EVM solution.
This allows creating authorizations with a specific VK and Registry.

Once executed, the proof is verified and registry is checked to validate that the the message is correct and was proven by the guest program.

Allows executing any processor message and the creation of the message is now done and validated inside the guest program so the authorization contract doesn't perform any validations except the proof verification.

Adds a verification-gateway contract that does simple proof verifications, decoupling the verification from the authorization contract, which just sets this contract to eventually query it. For now only SP1 4.2.0 verifier is set up to use on this gateway, but can easily be extended to verify proofs generated by other provers.

Kinda hard to test right now without writing a guest program, so next steps will be writing a guest program and generate proofs with the right inputs and verify that the interaction works as expected.

Summary by CodeRabbit

  • New Features

    • Introduced support for zero-knowledge (ZK) authorizations, enabling creation, modification, execution, and querying of ZK authorizations.
    • Added management and configuration of a verification gateway contract for ZK proof verification.
    • Enabled execution of contract actions based on ZK proofs, including integration with external verification gateways.
    • Added new query options for retrieving ZK authorizations and the verification gateway address.
  • Bug Fixes

    • None.
  • Documentation

    • Added documentation and schema files for the new verification gateway contract.
  • Tests

    • Added comprehensive tests for creating, querying, and executing ZK authorizations, including processor control via ZK proofs.
  • Chores

    • Added new contract and utility modules for ZK proof verification and updated dependencies to support new features.

Copy link
Contributor

coderabbitai bot commented May 13, 2025

Walkthrough

This update introduces a zero-knowledge (ZK) authorization framework to the codebase. It adds a new verification-gateway contract for ZK proof validation, extends the authorization contract to manage and execute ZK authorizations, and updates message schemas, state, and error handling to support ZK workflows. Related utilities and test helpers are also enhanced.

Changes

File(s) Change Summary
Cargo.toml, packages/authorization-utils/Cargo.toml Add valence-verification-gateway as workspace/package dependency; minor formatting.
contracts/authorization/Cargo.toml Add ZK gateway and related dev dependencies.
contracts/authorization/schema/valence-authorization.json Extend schema for ZK authorization management, execution, and queries.
contracts/authorization/src/authorization.rs Refactor: move permission validation to standalone function.
contracts/authorization/src/contract.rs Integrate ZK authorization: storage, execution, verification, and gateway management.
contracts/authorization/src/error.rs Add ZK-specific error variants and enum.
contracts/authorization/src/state.rs Add state items for ZK authorizations and verification gateway.
contracts/processor/src/contract.rs, packages/processor-utils/src/msg.rs Update imports to use shared AuthorizationMsg enum; remove local definition.
packages/authorization-utils/src/authorization.rs Add AuthorizationMsg enum for message queue management.
packages/authorization-utils/src/lib.rs Export new zk_authorization module.
packages/authorization-utils/src/msg.rs Add ZK-related message and query variants.
packages/authorization-utils/src/zk_authorization.rs New module: ZK authorization structs, logic, and message types.
contracts/authorization/src/tests/helpers.rs Add helper to instantiate and set verification gateway in tests.
contracts/authorization/src/tests/user_actions.rs Add integration test for ZK-based pause/resume processor actions.
contracts/middleware/verification-gateway/.cargo/config.toml New Cargo config: build and schema aliases.
contracts/middleware/verification-gateway/Cargo.toml New manifest for verification-gateway contract.
contracts/middleware/verification-gateway/README.md New README describing verification gateway purpose.
contracts/middleware/verification-gateway/schema/valence-verification-gateway.json New schema: define contract API for ZK proof verification.
contracts/middleware/verification-gateway/src/bin/schema.rs New file: generates contract schema.
contracts/middleware/verification-gateway/src/contract.rs New contract: ZK proof verification logic and entrypoints.
contracts/middleware/verification-gateway/src/error.rs New error type for contract.
contracts/middleware/verification-gateway/src/lib.rs Export contract, error, and msg modules.
contracts/middleware/verification-gateway/src/msg.rs Define instantiate, execute, and query messages for contract.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant AuthorizationContract
    participant VerificationGateway

    User->>AuthorizationContract: ExecuteZkAuthorization { label, message, proof }
    AuthorizationContract->>VerificationGateway: Query VerifyProof { vk, proof, inputs }
    VerificationGateway-->>AuthorizationContract: Verification result (bool)
    AuthorizationContract-->>User: Execution response (success/error)
Loading

Suggested reviewers

  • vlopes11

Poem

In the warren of code, a new path appears,
With ZK proofs hopping, dispelling old fears.
A gateway now stands, to verify with care,
And authorizations leap—secure, swift, and rare.
The rabbits all cheer as the tests run through,
For privacy and safety, a garden anew!
🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@keyleu keyleu marked this pull request as ready for review May 14, 2025 08:51
@keyleu keyleu requested review from bekauz and vlopes11 and removed request for bekauz May 14, 2025 08:52
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 7

🔭 Outside diff range comments (2)
packages/authorization-utils/src/lib.rs (1)

1-9: 💡 Verification agent

🧩 Analysis chain

Verify test coverage for the ZK authorization module

While the code structure looks good, the PR mentions limited testing due to the absence of a guest program. Consider adding unit tests that don't require a guest program to ensure the basic functionality works as expected.


🏁 Script executed:

#!/bin/bash
# Check if there are any tests for the zk_authorization module
find . -name "zk_authorization.rs" -o -name "*zk_authorization*_test.rs" | grep -v "target"
find . -type f -name "*.rs" -exec grep -l "zk_authorization" {} \; | grep -v "target" | grep "test"

Length of output: 243


Add Missing Unit Tests for zk_authorization Module

No existing tests reference the zk_authorization module. To ensure core functionality is covered without relying on a guest program, please:

• Create unit tests for packages/authorization-utils/src/zk_authorization.rs
• Focus on the module’s public API (e.g., key generation, proof verification)
• Use Rust’s #[cfg(test)] framework so tests can run in CI without external dependencies

contracts/authorization/src/contract.rs (1)

571-609: ⚠️ Potential issue

Unvalidated recipient addresses in mint_authorizations

Each Mint entry’s address is forwarded directly into a token-factory message without deps.api.addr_validate, risking invalid bech32 strings and downstream failure.

Insert validation:

for mint in &mints {
-    mint_msg(
-        env.contract.address.to_string(),
-        mint.address.clone(),
+    deps.api.addr_validate(&mint.address)?;       // new
+    mint_msg(
+        env.contract.address.to_string(),
+        mint.address.clone(),
         mint.amount.u128(),
         build_tokenfactory_denom(env.contract.address.as_str(), &label),
     )
}

This mirrors the strict checking done elsewhere in the file.

🧹 Nitpick comments (8)
contracts/verification-gateway/README.md (2)

3-3: Consider adding a comma for better readability.

There's a potential grammatical improvement in this sentence.

-This contract is a simple contract that will perform the verification of ZK proofs. It's separated into a singleton contract to decouple the verification to the rest of the contracts and therefore can be extended with different verifying methods for different types of proofs.
+This contract is a simple contract that will perform the verification of ZK proofs. It's separated into a singleton contract to decouple the verification to the rest of the contracts, and therefore can be extended with different verifying methods for different types of proofs.
🧰 Tools
🪛 LanguageTool

[uncategorized] ~3-~3: Possible missing comma found.
Context: ...ple the verification to the rest of the contracts and therefore can be extended with diff...

(AI_HYDRA_LEO_MISSING_COMMA)


1-3: Enhance documentation with usage examples and API details.

As this is a new component in the system, consider expanding the documentation to include:

  • Example usage patterns
  • Supported proof systems (currently SP1 4.2.0 as mentioned in the PR description)
  • Interface details for implementers who will interact with this gateway
🧰 Tools
🪛 LanguageTool

[uncategorized] ~3-~3: Possible missing comma found.
Context: ...ple the verification to the rest of the contracts and therefore can be extended with diff...

(AI_HYDRA_LEO_MISSING_COMMA)

contracts/verification-gateway/src/error.rs (1)

4-8: Consider adding specific error variants for verification failures.

As this contract's primary responsibility is verification of ZK proofs, consider adding specialized error variants for different verification failure scenarios. This would provide more granular error reporting and make debugging easier.

#[derive(Error, Debug)]
pub enum ContractError {
    #[error("{0}")]
    Std(#[from] StdError),
    
    #[error("Invalid proof format")]
    InvalidProofFormat,
    
    #[error("Verification failed: proof is not valid")]
    VerificationFailed,
    
    #[error("Unsupported verification method")]
    UnsupportedVerificationMethod,
    
    #[error("Invalid verification key")]
    InvalidVerificationKey,
}
contracts/verification-gateway/Cargo.toml (1)

21-21: Consider adding a version comment for sp1-verifier

The sp1-verifier dependency is pinned to version 4.2.0 directly rather than using workspace versioning. This is likely intentional but may require manual updates in the future.

-sp1-verifier    = "4.2.0"
+sp1-verifier    = "4.2.0" # Pinned for compatibility with SP1 ZK proof system
contracts/verification-gateway/src/lib.rs (1)

7-10: Add documentation for the VerifyingKey enum

Adding documentation would clarify the purpose of this enum and how it's intended to be extended for future proof systems.

 #[cw_serde]
+/// Represents different types of verification keys supported by the gateway.
+/// Currently only supports SP1 verifying key hashes, but can be extended
+/// to support other ZK proof systems in the future.
 pub enum VerifyingKey {
+    /// SP1 verifying key hash as a string
     SP1VerifyingKeyHash(String),
 }
contracts/verification-gateway/src/contract.rs (1)

46-63: ZK proof verification logic is limited to one proof system

Currently, the implementation only supports the SP1VerifyingKeyHash variant and returns Ok(true) for successful verification without considering other verifying key types that might be needed in the future.

As the codebase evolves, consider:

  1. Adding support for additional proof systems
  2. Enhancing error handling for each proof system type
  3. Implementing a proper return for the verification result rather than always returning true after verification

The return statement on line 62 should be removed, as the function already returns a boolean from the match statement. The current implementation could lead to confusion since it always returns true regardless of the match result.

packages/authorization-utils/src/zk_authorization.rs (1)

58-63: ZkMessage structure may need additional validation

The ZkMessage structure contains information about the message to be executed but lacks validation parameters to ensure the message can only be executed once per block if that's the intention with validate_last_block_execution.

Consider adding a mechanism to track the last executed block for each authorization, or include a nonce to ensure messages can't be replayed.

contracts/authorization/schema/valence-authorization.json (1)

1387-1421: Consider expanding modifiable fields
The modify_zk_authorization variant allows updating max_concurrent_executions and validate_last_block_execution, keyed by label. Should updates to the registry or the vk be supported here? If not, it would be helpful to document that those fields are immutable after creation.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6cc2d00 and a78bca2.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (23)
  • Cargo.toml (3 hunks)
  • contracts/authorization/Cargo.toml (1 hunks)
  • contracts/authorization/schema/valence-authorization.json (7 hunks)
  • contracts/authorization/src/authorization.rs (2 hunks)
  • contracts/authorization/src/contract.rs (15 hunks)
  • contracts/authorization/src/error.rs (2 hunks)
  • contracts/authorization/src/state.rs (1 hunks)
  • contracts/processor/src/contract.rs (2 hunks)
  • contracts/verification-gateway/.cargo/config.toml (1 hunks)
  • contracts/verification-gateway/Cargo.toml (1 hunks)
  • contracts/verification-gateway/README.md (1 hunks)
  • contracts/verification-gateway/schema/valence-verification-gateway.json (1 hunks)
  • contracts/verification-gateway/src/bin/schema.rs (1 hunks)
  • contracts/verification-gateway/src/contract.rs (1 hunks)
  • contracts/verification-gateway/src/error.rs (1 hunks)
  • contracts/verification-gateway/src/lib.rs (1 hunks)
  • contracts/verification-gateway/src/msg.rs (1 hunks)
  • packages/authorization-utils/Cargo.toml (1 hunks)
  • packages/authorization-utils/src/authorization.rs (2 hunks)
  • packages/authorization-utils/src/lib.rs (1 hunks)
  • packages/authorization-utils/src/msg.rs (5 hunks)
  • packages/authorization-utils/src/zk_authorization.rs (1 hunks)
  • packages/processor-utils/src/msg.rs (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
contracts/authorization/src/authorization.rs (1)
contracts/authorization/src/contract.rs (1)
  • build_tokenfactory_denom (1726-1728)
🪛 LanguageTool
contracts/verification-gateway/README.md

[uncategorized] ~3-~3: Possible missing comma found.
Context: ...ple the verification to the rest of the contracts and therefore can be extended with diff...

(AI_HYDRA_LEO_MISSING_COMMA)

🔇 Additional comments (47)
packages/authorization-utils/src/authorization.rs (1)

187-212: Well-structured enum for authorization message management

The new AuthorizationMsg enum provides a clear structure for managing message operations like enqueueing, evicting, and inserting messages in the authorization queue. This supports the ZK authorization workflow where proofs need to be verified before execution.

packages/authorization-utils/Cargo.toml (1)

15-15: Appropriate dependency for the ZK verification integration

Adding the valence-verification-gateway dependency aligns with the PR objectives of separating verification logic from authorization logic.

contracts/authorization/Cargo.toml (1)

26-26: Proper dependency for ZK authorization implementation

The addition of valence-verification-gateway is consistent with the PR objective to separate verification logic from the authorization contract.

packages/authorization-utils/src/lib.rs (1)

8-8: Good modularization of ZK authorization functionality

Exposing the zk_authorization module makes the ZK-specific structures and functions available to external crates, supporting a clean separation of concerns.

contracts/verification-gateway/README.md (1)

1-3: Clear introduction to the verification gateway concept.

The README provides a concise explanation of the verification gateway's purpose and design philosophy.

🧰 Tools
🪛 LanguageTool

[uncategorized] ~3-~3: Possible missing comma found.
Context: ...ple the verification to the rest of the contracts and therefore can be extended with diff...

(AI_HYDRA_LEO_MISSING_COMMA)

contracts/verification-gateway/.cargo/config.toml (1)

1-3: Standard Cargo configuration for CosmWasm contracts.

This configuration follows best practices for CosmWasm contract development with appropriate aliases for WebAssembly building and schema generation.

contracts/processor/src/contract.rs (2)

10-15: Good refactoring of imports to centralize authorization code.

Moving the AuthorizationMsg import from processor utils to authorization utils improves code organization by centralizing authorization-related code.


17-22: Consistent import update following the authorization refactoring.

This change correctly removes AuthorizationMsg from the processor utils import to avoid duplication.

contracts/verification-gateway/src/error.rs (1)

1-8: Basic error handling foundation for the verification gateway.

The error module establishes a solid foundation with standard error handling patterns, wrapping the CosmWasm StdError.

contracts/verification-gateway/Cargo.toml (1)

1-20: LGTM - New verification gateway contract configured correctly

The Cargo.toml is properly structured with appropriate workspace inheritance and CosmWasm dependencies.

contracts/verification-gateway/src/lib.rs (1)

1-6: LGTM - Module structure is clear and well-organized

The module structure follows CosmWasm conventions with clear separation of contract, error, and message types.

Cargo.toml (2)

10-10: LGTM - Verification gateway added to workspace members

The new contract is correctly added to the workspace members list.


116-116: LGTM - Verification gateway correctly added as a workspace dependency

The dependency entry is properly configured with the library feature enabled, consistent with other contract dependencies.

contracts/verification-gateway/src/bin/schema.rs (1)

1-10: LGTM - Schema generation is correctly implemented

The schema generation file follows the standard CosmWasm pattern and will generate the necessary JSON schema files for contract integration.

contracts/authorization/src/state.rs (3)

5-5: LGTM - Added import for ZkAuthorization

The ZkAuthorization import is added to support the new ZK authorization features.


11-12: LGTM - Added storage for verification gateway address

The VERIFICATION_GATEWAY Item will store the address of the contract that handles ZK proof verification.


18-19:

✅ Verification successful

Verify concurrency control for registry executions

The REGISTRY_LAST_BLOCK_EXECUTION map tracks the last block execution per registry ID, which appears to be for preventing replay or ensuring message ordering.


🏁 Script executed:

#!/bin/bash
# Search for code that uses this registry execution tracking to understand the concurrency control
rg -A 10 "REGISTRY_LAST_BLOCK_EXECUTION" --type rust

Length of output: 2717


Concurrency control for REGISTRY_LAST_BLOCK_EXECUTION is correct

The load–compare–save pattern in contracts/authorization/src/contract.rs ensures that any message with a block number ≤ the last saved value is rejected (preventing replay), and valid messages atomically update the stored block number. Given CosmWasm’s single-threaded, atomic execution model, there’s no risk of concurrent writes for the same registry. No changes needed.

contracts/authorization/src/error.rs (2)

27-28: Well-structured error handling integration for ZK authorizations.

The addition of the ZK variant to ContractError follows the established pattern of other error types, providing a clear way to propagate ZK-specific errors.


139-155: Comprehensive error enumeration for ZK features.

The ZKErrorReason enum provides well-defined error variants for the ZK authorization flow, covering key validation scenarios: verification gateway configuration, proof validation, registry validation, proof expiration, and domain validation.

This error structure aligns well with the PR objective of supporting ZK authorizations that verify proofs and check registries. Each error case has a clear, descriptive message.

packages/processor-utils/src/msg.rs (1)

3-3: Good refactoring to centralize AuthorizationMsg definition.

Importing AuthorizationMsg and Priority from the shared package rather than defining them locally improves code maintainability by establishing a single source of truth for these types.

This change supports the broader integration of ZK functionality across the codebase by ensuring consistent message types are used throughout the system.

contracts/verification-gateway/schema/valence-verification-gateway.json (1)

1-83: Well-defined schema for the new ZK verification gateway contract.

The schema properly defines:

  • An empty instantiate message (stateless contract)
  • No execute messages (query-only contract)
  • A single query method for proof verification
  • Clear definitions for the verification key structure

The contract being query-only aligns well with its focused responsibility of proof verification.

However, the PR objectives mention the gateway is "designed to be extensible for other proof systems," but the schema currently only supports the SP1 verifier through the s_p1_verifying_key_hash field.

Could you confirm if the VerifyingKey type (lines 56-71) is designed to be extensible with additional variants in the future for other proof systems?

contracts/verification-gateway/src/msg.rs (3)

1-5: Clean import structure for the verification gateway.

The imports are minimal and focused on what's needed for the contract's message types.


6-11: Empty InstantiateMsg and ExecuteMsg align with contract's query-only role.

Creating a stateless, query-only contract for verification is a good architectural choice that separates concerns.


12-21: Well-structured query message for proof verification.

The VerifyProof query message is properly designed with all necessary components:

  • A verification key (vk)
  • The proof data
  • The proof inputs

The #[returns(bool)] annotation correctly specifies the return type.

This implementation aligns with the PR objective of having "a new verification-gateway contract added to handle simple proof verifications."

contracts/authorization/src/authorization.rs (2)

384-386: Correct usage of the extracted validate_permission function

The code correctly uses the newly extracted validate_permission function, passing all required parameters from the authorization object. This change supports the addition of ZK authorizations by making permission validation more flexible.


468-502: Well-structured permission validation logic

The extracted validate_permission function properly implements the permission validation logic based on different authorization modes. This refactoring enables better support for ZK authorizations while maintaining the existing validation flow.

packages/authorization-utils/src/msg.rs (6)

17-17: Properly imported ZK authorization types

The import of ZkAuthorization and ZkAuthorizationInfo types is correctly added to support the new ZK authorization functionality.


186-188: Good addition of ZK authorization creation message

This message variant allows for creating multiple ZK authorizations at once, following the same pattern as the existing CreateAuthorizations variant.


196-200: ZK authorization modification parameters are appropriate

The ModifyZkAuthorization message allows updating specific ZK authorization attributes. The inclusion of validate_last_block_execution flag is a good addition for ensuring sequence validation.


240-242: Gateway configuration message is clear and well-documented

The SetVerificationGateway message provides a clean way to configure the verification gateway contract address used for ZK proof validation.


269-273: ZK authorization execution message has all required components

The ExecuteZkAuthorization message contains all necessary information: label to identify the authorization, the message to be executed, and the proof to be verified.


366-372: Query messages are well-structured and consistent

The added query messages for ZK authorizations and verification gateway follow the same pattern as existing queries, maintaining consistency in the API.

contracts/verification-gateway/src/contract.rs (3)

12-14: Good practice using environment variables for contract metadata

Using environment variables for contract name and version ensures these values are synchronized with the Cargo.toml definitions.


16-25: Clean instantiation implementation

The instantiate function properly sets the contract version and returns an appropriate response with an action attribute.


37-44: Properly structured query function

The query function correctly handles the VerifyProof query variant and returns a binary JSON response.

packages/authorization-utils/src/zk_authorization.rs (3)

1-11: Clean imports for ZK authorization module

The imports correctly reference the necessary dependencies including the verification gateway contract for VerifyingKey.


12-29: Well-documented ZK authorization info structure

The ZkAuthorizationInfo struct is well-documented with clear comments explaining each field's purpose. The inclusion of optional fields with documented defaults is good practice.


31-44: The conversion method properly handles optional values

The into_zk_authorization method correctly handles optional fields by providing default values. Good practice setting a default of 1 for max_concurrent_executions.

contracts/authorization/schema/valence-authorization.json (8)

1304-1327: Correctly models batch creation of ZK authorizations
The new create_zk_authorizations variant in PermissionedMsg aligns with the ZkAuthorizationInfo definition, enforcing an array of well-typed items and prohibiting extra fields. Verify that the contract’s Rust handler matches this structure and properly deserializes the zk_authorizations array.


1709-1738: Schema for execute_zk_authorization is valid
The new execute_zk_authorization permissionless action correctly requires the label, a Base64-encoded message, and a Base64-encoded proof, with additionalProperties: false. This matches the guest-program interface.


2052-2069: Introduce VerifyingKey definition
The VerifyingKey schema wraps the SP1 verifying key hash (s_p1_verifying_key_hash) in a strict one-field object. Ensure the Rust struct and serde attributes use the same field name so JSON round-trips correctly.


2070-2111: Define ZkAuthorizationInfo clearly
This definition enforces required fields (domain, label, mode, registry, validate_last_block_execution, vk) with optional max_concurrent_executions. It mirrors the Rust type and ensures invalid payloads are rejected.


2223-2251: Add query for listing ZK authorizations
The zk_authorizations query variant cleanly supports pagination via limit and start_after. Confirm that the contract’s Rust implementation uses the same cursor type (string) for the start_after parameter.


2252-2264: Add query for verification gateway address
The verification_gateway query provides a simple way to retrieve the gateway address. This pattern is consistent with other address-only queries in the schema.


4307-4313: Response schema for verification_gateway
The new top-level verification_gateway response type correctly returns a single string address. Double-check client stubs to ensure this matches expected response shapes.


4314-4325: Response schema for ZK authorizations
The zk_authorizations response array (items → #/definitions/ZkAuthorization) matches state and includes state, validate_last_block_execution, vk, and registry. Verify that any future additions to ZkAuthorizationInfo are mirrored here.

contracts/authorization/src/contract.rs (1)

1828-1862: Nice utility helper

assign_execution_id cleanly rewrites the ID field while leaving the rest of the message intact.
Good defensive programming here. 👍

Copy link

@vlopes11 vlopes11 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good overall, I have more questions than changes requested

Comment on lines 20 to 21
// Domain this needs to be sent to
pub domain: Domain,

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm unsure about this one. Each proof will be indeed domain specific, but it will also be a list per program. Is this authorization per domain? Or per program? If the latter, we need this to be a list

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I need this to be able to route it to the correct processor. Indeed each authorization be per domain. We can either add it to the authorization here or add it to the ZkMessage

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

answering your question, authorizations are per domain and guest program specific (there is a VK and a registry associated to it)

Comment on lines 7 to 10
#[cw_serde]
pub enum VerifyingKey {
SP1VerifyingKeyHash(String),
}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd prefer to be agnostic about this and treat the verifying key just as Vec<u8> (or String, if better compatibility). This way, we don't statically define who will verify what, and it will be up to the on-chain verification contract to decide.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

OK, removed this and made it an array of bytes. The verification contract decides what do with it

Comment on lines 18 to 19
// Default will be 1, defines how many times a specific authorization can be executed concurrently
pub max_concurrent_executions: Option<u64>,

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

More of a question: do we eliminate this with ZK? Since everything is precomputed off-chain, I'm not sure we should rate limit on-chain.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure, removed it for now. If we eventually find a reason to add this we can add.

Comment on lines +398 to +400
// If Authorization is permissioned we need to create the tokenfactory token and mint the corresponding amounts to the addresses that can
// execute the authorization
if let AuthorizationMode::Permissioned(permission_type) = &zk_authorization.mode {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We might change this in the future, when we finish co-processor identification and gas charging.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, this can be made all permissionless in the future

@keyleu keyleu requested a review from vlopes11 May 14, 2025 11:19
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (1)
contracts/authorization/src/tests/user_actions.rs (1)

756-793: Incomplete test scaffold for ZK authorizations.

The test provides a good foundation for testing ZK authorization flows, but is intentionally incomplete as noted in the TODO comment.

Suggestions:

  1. Consider adding assertions on the deserialized proof structure instead of just printing it
  2. Add comments explaining what the base64-encoded values represent in more detail
  3. Outline the remaining test steps that will be added when valid proofs can be generated

Once you have the capability to generate valid Groth16 proofs, ensure this test is completed to verify:

  • Proof verification works correctly
  • The processor can be paused using a valid ZK proof
  • The processor can be resumed using a valid ZK proof
  • Proper error handling for invalid proofs
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Lite
Cache: Disabled due to data retention organization setting
Knowledge Base: Disabled due to data retention organization setting

📥 Commits

Reviewing files that changed from the base of the PR and between b3f0ea3 and 51379c8.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (3)
  • contracts/authorization/Cargo.toml (1 hunks)
  • contracts/authorization/src/tests/helpers.rs (2 hunks)
  • contracts/authorization/src/tests/user_actions.rs (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • contracts/authorization/Cargo.toml
🧰 Additional context used
🧬 Code Graph Analysis (1)
contracts/authorization/src/tests/helpers.rs (4)
contracts/authorization/src/tests/user_actions.rs (16)
  • wasm (52-52)
  • wasm (60-60)
  • wasm (71-72)
  • wasm (93-94)
  • wasm (150-150)
  • wasm (159-160)
  • wasm (184-185)
  • wasm (209-210)
  • wasm (247-247)
  • wasm (256-257)
  • wasm (280-281)
  • wasm (304-305)
  • wasm (369-369)
  • wasm (378-379)
  • wasm (400-401)
  • wasm (424-425)
packages/osmosis-utils/src/suite.rs (1)
  • new (53-59)
contracts/authorization/src/tests/builders.rs (1)
  • new (12-18)
packages/processor-utils/src/queue.rs (1)
  • new (16-26)
🔇 Additional comments (4)
contracts/authorization/src/tests/helpers.rs (2)

13-13: Clean addition of necessary imports.

The expanded import statement includes all the required types for the new helper function.


199-242: Well-structured helper function for setting up verification gateway.

This function follows the established pattern of other helpers in the codebase, handling the deployment and configuration of the verification gateway contract consistently. It correctly:

  1. Reads the WASM bytecode
  2. Stores and instantiates the contract
  3. Links it to the authorization contract via the permissioned action
contracts/authorization/src/tests/user_actions.rs (2)

5-5: Added SP1 SDK dependency import.

Properly imported the required type for ZK proof deserialization.


21-26: Clean import organization.

The imports have been properly updated to include the necessary functions and libraries for ZK authorization testing.

@keyleu keyleu requested a review from bekauz May 16, 2025 13:16
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

♻️ Duplicate comments (1)
contracts/verification-gateway/src/contract.rs (1)

27-34: unimplemented!() will panic – consider graceful error handling

Even though the contract is intended to be query-only, calling this entry-point will panic!, causing an abrupt abort instead of a standard CosmWasm error. A simple Err(ContractError::Unsupported {}) (or similar) avoids panics and makes debugging on-chain a lot easier.

🧹 Nitpick comments (1)
contracts/verification-gateway/src/contract.rs (1)

67-182: Huge inline binary blobs bloat the test – consider include_bytes!

Embedding ~3 KB of proof/VK data directly in the source inflates compile times and obscures the test logic. A lightweight improvement is to store them under tests/fixtures/ and load with:

let hello_vk: Vec<u8> = include_bytes!("../fixtures/hello_vk.bin").to_vec();
let hello_proof: Vec<u8> = include_bytes!("../fixtures/hello_proof.bin").to_vec();

This keeps the test readable and avoids recompiling large constants when the file changes.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Lite
Cache: Disabled due to data retention organization setting
Knowledge Base: Disabled due to data retention organization setting

📥 Commits

Reviewing files that changed from the base of the PR and between 51379c8 and 562f614.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (2)
  • contracts/verification-gateway/Cargo.toml (1 hunks)
  • contracts/verification-gateway/src/contract.rs (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • contracts/verification-gateway/Cargo.toml

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (4)
contracts/authorization/src/tests/user_actions.rs (4)

24-27: Avoid tight coupling to helpers from other test modules

The new call to instantiate_and_set_verification_gateway() brings an implicit dependency on test helper internals living in another file.
Consider exposing the gateway initialisation behind a small TestFixtureBuilder struct so future refactors of helper signatures do not require touching every individual test.


780-787: Extract oversized base-64 constants into test fixtures for readability

Keeping ±1 KB base-64 strings in-line makes the test hard to scan and maintain.
Recommended pattern:

-    let program_vk = "LONG_BASE64 …";
-    let full_proof_pause = "LONG_BASE64 …";
-    let full_proof_resume = "LONG_BASE64 …";
+    let program_vk       = include_str!("fixtures/program_vk.b64").trim();
+    let full_proof_pause = include_str!("fixtures/proof_pause.b64").trim();
+    let full_proof_resume= include_str!("fixtures/proof_resume.b64").trim();

The dedicated fixtures/ folder improves diff-size, enables reuse between tests, and lets you regenerate proofs with a helper script without touching Rust code.


792-798: Verify both proofs for full end-to-end coverage

Only proof_pause is fed into Groth16Verifier::verify.
If the resume proof encoding were to degrade, the test would still pass.
Consider duplicating the call or turning it into a helper:

for (bytes, inputs) in [
    (&proof_pause_bytes, &proof_pause_inputs),
    (&proof_resume_bytes, &proof_resume_inputs),
] {
    Groth16Verifier::verify(bytes, inputs, &sp1_vk.bytes32(), &GROTH16_VK_BYTES)
        .expect("Groth16 verification failed");
}

This keeps the sanity-check symmetrical.


840-850: Consider using expect() instead of bare unwrap() for actionable failure messages

Example:

-).unwrap();
+).expect("Failed to execute ZK pause authorization");

When a proof or contract call fails, the explicit message pin-points which phase went wrong, speeding up debugging.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Lite

📥 Commits

Reviewing files that changed from the base of the PR and between c2c1455 and 978c76d.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (5)
  • Cargo.toml (3 hunks)
  • contracts/authorization/Cargo.toml (1 hunks)
  • contracts/authorization/schema/valence-authorization.json (7 hunks)
  • contracts/authorization/src/tests/user_actions.rs (3 hunks)
  • packages/authorization-utils/src/zk_authorization.rs (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (4)
  • Cargo.toml
  • contracts/authorization/Cargo.toml
  • packages/authorization-utils/src/zk_authorization.rs
  • contracts/authorization/schema/valence-authorization.json

Copy link

@vlopes11 vlopes11 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM!

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
contracts/middleware/verification-gateway/src/contract.rs (1)

75-181: Enhance test coverage with additional test cases.

The current test only covers the happy path. Consider adding:

  • Test cases for invalid proofs that should fail verification
  • Test cases for malformed inputs (invalid UTF-8 in VK, empty inputs, etc.)
  • Consider moving the large test vectors to separate files or constants to improve readability

Example additional test:

#[test]
fn test_verify_proof_invalid_vk() {
    // Test with invalid UTF-8 in VK
    let invalid_vk = Binary::new(vec![0xFF, 0xFE, 0xFD]); // Invalid UTF-8
    let proof = Binary::new(vec![0; 100]);
    let inputs = Binary::new(vec![0; 32]);
    
    let result = verify_proof(&invalid_vk, proof, inputs);
    assert!(result.is_err());
    assert!(result.unwrap_err().to_string().contains("Failed to parse vk hash"));
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7802d31 and e894f3f.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (10)
  • Cargo.toml (3 hunks)
  • contracts/middleware/verification-gateway/.cargo/config.toml (1 hunks)
  • contracts/middleware/verification-gateway/Cargo.toml (1 hunks)
  • contracts/middleware/verification-gateway/README.md (1 hunks)
  • contracts/middleware/verification-gateway/schema/valence-verification-gateway.json (1 hunks)
  • contracts/middleware/verification-gateway/src/bin/schema.rs (1 hunks)
  • contracts/middleware/verification-gateway/src/contract.rs (1 hunks)
  • contracts/middleware/verification-gateway/src/error.rs (1 hunks)
  • contracts/middleware/verification-gateway/src/lib.rs (1 hunks)
  • contracts/middleware/verification-gateway/src/msg.rs (1 hunks)
✅ Files skipped from review due to trivial changes (9)
  • contracts/middleware/verification-gateway/.cargo/config.toml
  • contracts/middleware/verification-gateway/src/lib.rs
  • contracts/middleware/verification-gateway/README.md
  • contracts/middleware/verification-gateway/Cargo.toml
  • contracts/middleware/verification-gateway/src/bin/schema.rs
  • Cargo.toml
  • contracts/middleware/verification-gateway/src/error.rs
  • contracts/middleware/verification-gateway/schema/valence-verification-gateway.json
  • contracts/middleware/verification-gateway/src/msg.rs
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: build-and-deploy
  • GitHub Check: solidity contracts
  • GitHub Check: setup-local-ic
🔇 Additional comments (1)
contracts/middleware/verification-gateway/src/contract.rs (1)

51-56: Consider the implications of hardcoded GROTH16_VK_BYTES.

The contract uses a hardcoded verification key (GROTH16_VK_BYTES) which means it only supports proofs generated with one specific trusted setup. This design choice should be documented.

If this limitation is intentional, consider adding a comment explaining that this contract is designed for a specific SP1 verifier setup. If extensibility is desired in the future, you might want to store the verification key bytes in contract state or accept them as a parameter.

@bekauz bekauz self-requested a review May 26, 2025 16:39
@@ -157,6 +172,11 @@ pub fn execute(
PermissionlessMsg::RetryBridgeCreation { domain_name } => {
retry_bridge_creation(deps, env, domain_name)
}
PermissionlessMsg::ExecuteZkAuthorization {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

regarding the enum variant naming here, we don't actually execute the underlying authorization, do we? just verify the zkp & send the msg to processor?

Copy link
Contributor Author

@keyleu keyleu May 26, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yeah. Authorizations don't really get executed per se, they send the msg to the processor, although we Call/Execute the authorization contract to somehow indirectly trigger the execution with the eventual tick

Copy link
Contributor

@bekauz bekauz left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

left one question about the zk authorization message naming but other than that this makes sense to me!

@keyleu keyleu merged commit cd135e4 into main May 26, 2025
19 checks passed
@keyleu keyleu deleted the keyne/cw-zk-auth branch May 26, 2025 17:31
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants