Skip to content

P0.1 Canonical zkVM Guest Program with consensus-critical types#3

Merged
Mehd1b merged 3 commits into
mainfrom
dev
Jan 21, 2026
Merged

P0.1 Canonical zkVM Guest Program with consensus-critical types#3
Mehd1b merged 3 commits into
mainfrom
dev

Conversation

@Mehd1b

@Mehd1b Mehd1b commented Jan 21, 2026

Copy link
Copy Markdown
Member

Summary

  • Implement P0.1 Canonical zkVM Guest Program as specified in SPECIFICATION.md
  • Add consensus-critical fields to kernel types for on-chain verifiability
  • Fix critical security vulnerabilities and agent execution issues

Key Changes

Kernel Types (consensus-critical)

  • KernelInputV1: Added kernel_version, agent_code_hash, constraint_set_hash, input_root, execution_nonce for binding proofs to code/policy/state
  • KernelJournalV1: Added identity fields for on-chain verifier binding
  • Structured ActionV1 format replacing opaque bytes with deterministic ordering
  • Separate error hierarchies: KernelError, AgentError, ConstraintError

Architecture

  • 5-crate workspace: kernel-core, kernel-guest, agent-traits, constraints, host-tests
  • Deterministic binary codec with explicit encoding layouts
  • SHA-256 commitments for input and action verification
  • Agent trait with full execution context

Testing

  • 24 comprehensive tests covering encoding, commitments, determinism, and error handling

Test plan

  • cargo test passes (24 tests)
  • cargo build --release succeeds
  • Review encoding layouts match specification
  • Verify journal contains all fields needed for on-chain verification

- KernelInputV1: Add kernel_version, agent_code_hash, constraint_set_hash,
  input_root, execution_nonce for binding proofs to code/policy/state
- KernelJournalV1: Add identity fields (agent_id, agent_code_hash,
  constraint_set_hash, input_root, execution_nonce) for verifier binding
- Replace opaque AgentOutput with structured ActionV1 format
  (action_type, target, payload) with deterministic ordering
- Introduce KernelError, AgentError, ConstraintError type hierarchy
- Update Agent trait with AgentContext containing full execution context
- Update codec with explicit encoding layouts and size documentation
- Expand test suite to 24 tests covering new fields and edge cases
@claude

claude Bot commented Jan 21, 2026

Copy link
Copy Markdown

Claude finished @Mehd1b's task —— View job


Code Review Complete ✅

Review Tasks

  • Read repository guidelines (CLAUDE.md)
  • Review kernel-core type definitions (consensus-critical)
  • Analyze deterministic codec implementation
  • Review agent-traits and constraints changes
  • Examine host-tests for coverage and quality
  • Check kernel-guest implementation
  • Assess security considerations
  • Evaluate performance implications
  • Provide comprehensive feedback

🔍 Code Review Summary

This PR implements a well-architected zkVM execution kernel with strong emphasis on determinism, security, and verifiability. The implementation follows the SPECIFICATION.md requirements closely and establishes a solid foundation for consensus-critical proof generation.

Strengths

Architecture & Design:

  • Clean 5-crate separation of concerns (kernel-core, kernel-guest, agent-traits, constraints, host-tests)
  • Consensus-critical fields properly included in KernelInputV1 and KernelJournalV1 for on-chain binding
  • Structured ActionV1 format replacing opaque bytes provides deterministic ordering
  • Well-defined error hierarchies separate parsing, execution, and constraint errors

Deterministic Encoding:

  • Little-endian encoding throughout for cross-platform consistency
  • Fixed-size journal (209 bytes) enables efficient on-chain verification
  • Proper bounds checking with clear limits (64KB inputs, 16KB action payloads, 64 max actions)
  • Length prefixes protect against buffer overflows

Security Features:

  • Input commitment (SHA-256(full_input_bytes)) ensures input integrity
  • Action commitment (SHA-256(agent_output_bytes)) binds proofs to specific outputs
  • Version validation prevents incompatible execution
  • Bounded execution with memory and loop limits

⚠️ Areas for Improvement

Critical Issues:

  1. Panic-based error handling in codec (crates/kernel-core/src/codec.rs:29, 293, 375, 377)

    if data_len > u32::MAX as usize {
        panic!("Input data too large for u32 length prefix");
    }

    Risk: Panics can cause non-deterministic behavior in zkVM environments
    Fix: Return Result<Vec<u8>, CodecError> and handle overflow gracefully

  2. Missing cryptographic hash validation

    • No validation that agent_code_hash matches actual agent code being executed
    • constraint_set_hash not verified against loaded constraint set
      Risk: Proofs could be generated with mismatched code/constraint hashes

Security Concerns:

  1. Hardcoded agent selection (crates/kernel-guest/src/lib.rs:62)

    let agent_output = TrivialAgent::run(&agent_ctx, &input.opaque_agent_inputs)

    Issue: Always uses TrivialAgent regardless of agent_code_hash
    Risk: Proof generation not bound to specific agent implementation

  2. Constraint checking disabled (crates/constraints/src/lib.rs:47-50)

    pub fn check(_output: &AgentOutput, _meta: &ConstraintMeta) -> Result<(), ConstraintError> {
        // P0.1: Stub implementation - always passes
        Ok(())
    }

    Risk: No policy enforcement in current implementation

Code Quality:

  1. Integer overflow potential in codec size calculations without checked arithmetic
  2. Test coverage gaps - no fuzz testing for codec edge cases or malformed inputs
  3. Magic numbers - constants like ACTION_TYPE_ECHO = 0x00000001 should be documented

📊 Performance Considerations

Positive:

  • Fixed-size journal enables O(1) verification
  • Pre-allocated buffers minimize memory allocations
  • Bounded execution prevents resource exhaustion

Areas for optimization:

  • Large action payloads (16KB max) could impact proof size
  • Sequential action encoding could be optimized for batch operations

🧪 Test Coverage Assessment

Good coverage for:

  • Encoding/decoding round-trips for all types
  • Basic size limit validation
  • Golden vector tests for commitment computation

Missing coverage:

  • Malformed input fuzzing
  • Integer overflow edge cases
  • Agent execution error scenarios
  • Constraint violation testing

📝 Recommendations

High Priority:

  1. Replace panics with proper error handling in codec implementations
  2. Implement agent code hash verification in kernel_main()
  3. Add constraint set hash validation
  4. Use checked arithmetic for size calculations

Medium Priority:

  1. Add comprehensive fuzz testing for codec edge cases
  2. Implement agent selection based on agent_code_hash
  3. Add integration tests with realistic constraint scenarios
  4. Document action type constants and their semantics

Low Priority:

  1. Consider action payload compression for large outputs
  2. Add performance benchmarks for encoding/decoding
  3. Optimize memory allocation patterns

🚀 Overall Assessment

This is a high-quality implementation that demonstrates strong understanding of zkVM requirements and consensus-critical design. The architecture is sound and the code follows best practices for deterministic execution. The main concerns are around error handling robustness and missing hash validation, which are addressable without major architectural changes.

Recommendation: Approve with required fixes for panic handling and hash validation.


- Change CanonicalEncode::encode() to return Result<Vec<u8>, CodecError>
- Add KernelError::EncodingFailed variant for encoding error propagation
- Enforce MAX_AGENT_INPUT_BYTES on encode side (not just decode)
- Use ArithmeticOverflow for u32 overflow edge cases
- Fix KernelJournalV1::decode offset tracking with debug_assert
- Update kernel_main to propagate encoding errors
- Update all tests to handle Result type
@claude

claude Bot commented Jan 21, 2026

Copy link
Copy Markdown

Claude finished @Mehd1b's task —— View job


🔍 Code Review Complete ✅

Review Tasks

  • Read repository guidelines and specification
  • Review kernel-core type definitions and codec implementation
  • Analyze agent-traits and constraints changes
  • Examine host-tests for coverage and quality
  • Check kernel-guest implementation
  • Assess security considerations
  • Evaluate performance implications
  • Provide comprehensive feedback

This PR implements a well-architected zkVM execution kernel with strong emphasis on determinism, security, and verifiability. The implementation follows the SPECIFICATION.md requirements closely and establishes a solid foundation for consensus-critical proof generation.

Strengths

Architecture & Design:

  • Clean 5-crate separation of concerns (kernel-core, kernel-guest, agent-traits, constraints, host-tests)
  • Consensus-critical fields properly included in KernelInputV1 and KernelJournalV1 for on-chain binding
  • Structured ActionV1 format replacing opaque bytes provides deterministic ordering
  • Well-defined error hierarchies separate parsing, execution, and constraint errors

Deterministic Encoding:

  • Little-endian encoding throughout for cross-platform consistency
  • Fixed-size journal (209 bytes) enables efficient on-chain verification
  • Proper bounds checking with clear limits (64KB inputs, 16KB action payloads, 64 max actions)
  • Length prefixes protect against buffer overflows

Security Features:

  • Input commitment (SHA-256(full_input_bytes)) ensures input integrity
  • Action commitment (SHA-256(agent_output_bytes)) binds proofs to specific outputs
  • Version validation prevents incompatible execution
  • Bounded execution with memory and loop limits

⚠️ Areas for Improvement

Critical Issues:

  1. Hardcoded agent selection (crates/kernel-guest/src/lib.rs:62)

    let agent_output = TrivialAgent::run(&agent_ctx, &input.opaque_agent_inputs)

    Issue: Always uses TrivialAgent regardless of agent_code_hash
    Risk: Proof generation not bound to specific agent implementation

  2. Missing cryptographic hash validation

    • No validation that agent_code_hash matches actual agent code being executed
    • constraint_set_hash not verified against loaded constraint set
      Risk: Proofs could be generated with mismatched code/constraint hashes

Security Concerns:

  1. Constraint checking disabled (crates/constraints/src/lib.rs:47-50)
    pub fn check(_output: &AgentOutput, _meta: &ConstraintMeta) -> Result<(), ConstraintError> {
        // P0.1: Stub implementation - always passes
        Ok(())
    }
    Risk: No policy enforcement in current implementation

Code Quality:

  1. Potential integer overflow in codec size calculations could benefit from checked arithmetic
  2. Magic numbers - constants like ACTION_TYPE_ECHO = 0x00000001 should be documented

📊 Performance Considerations

Positive:

  • Fixed-size journal enables O(1) verification
  • Pre-allocated buffers minimize memory allocations
  • Bounded execution prevents resource exhaustion

Areas for optimization:

  • Large action payloads (16KB max) could impact proof size
  • Sequential action encoding could be optimized for batch operations

🧪 Test Coverage Assessment

Excellent coverage for:

  • Encoding/decoding round-trips for all types (24 comprehensive tests)
  • Basic size limit validation
  • Golden vector tests for commitment computation
  • Determinism verification across multiple executions
  • Edge cases (empty inputs, max-size inputs, malformed data)
  • Version validation and error handling
  • Action canonicalization ordering

Missing coverage:

  • Malformed input fuzzing
  • Agent execution error scenarios
  • Constraint violation testing (when constraints become active)

📝 Recommendations

High Priority:

  1. Implement agent selection based on agent_code_hash in kernel_main()
  2. Add agent code hash verification against actual executed code
  3. Add constraint set hash validation

Medium Priority:

  1. Add comprehensive fuzz testing for codec edge cases
  2. Use checked arithmetic for size calculations to prevent integer overflow
  3. Add integration tests with realistic constraint scenarios
  4. Document action type constants and their semantics

Low Priority:

  1. Consider action payload compression for large outputs
  2. Add performance benchmarks for encoding/decoding
  3. Optimize memory allocation patterns

🚀 Overall Assessment

This is a high-quality implementation that demonstrates strong understanding of zkVM requirements and consensus-critical design. The architecture is sound, the code follows best practices for deterministic execution, and test coverage is comprehensive. The main concerns are around hash validation completeness and agent selection logic, which are addressable without major architectural changes.

The implementation successfully establishes the foundation for verifiable agent execution with proper cryptographic commitments and deterministic encoding. The consensus-critical fields in both input and journal types provide the necessary binding for on-chain verification.

Recommendation: Approve with required fixes for agent selection and hash validation.


@Mehd1b
Mehd1b merged commit cba777c into main Jan 21, 2026
1 check failed
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.

1 participant