Skip to content

Conversation

Zombeescott
Copy link
Contributor

@Zombeescott Zombeescott commented Jun 23, 2025

Replacement of anyhow references in the keys folder.

Summary by CodeRabbit

  • New Features

    • Introduced detailed, user-facing error messages for cryptographic operations, replacing generic error handling with specific error types for signing, verification, algorithm selection, and Cosmos operations.
    • Added a centralized error handling module exposing comprehensive error types and result aliases for cryptographic keys.
  • Bug Fixes

    • Improved consistency and clarity of error reporting across cryptographic key and signature management, making it easier to identify and understand issues during key creation, signing, and verification.
  • Refactor

    • Updated all cryptographic functions to use custom, domain-specific error types for improved error handling and maintainability.
    • Replaced generic error handling with explicit, typed error variants across signing keys, verifying keys, signatures, algorithms, and Cosmos-related operations.

Copy link

vercel bot commented Jun 23, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
prism ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jun 26, 2025 0:50am

Copy link
Contributor

coderabbitai bot commented Jun 23, 2025

Walkthrough

This change replaces the use of the generic anyhow error handling with explicit, custom error enums across the keys crate. All public and internal functions now return domain-specific error types, and the dependency on anyhow is removed in favor of thiserror. No core logic or control flow is altered.

Changes

File(s) Change Summary
crates/keys/Cargo.toml Removed anyhow.workspace = true, added thiserror.workspace = true under dependencies.
crates/keys/src/errors.rs Added comprehensive error enums (CryptoError, SignatureError, ParseError, VerificationError) and a crate-wide Result alias.
crates/keys/src/lib.rs Added public errors module and re-exported error types and Result at crate root.
crates/keys/src/algorithm.rs Replaced anyhow error handling with custom CryptoError and SignatureError enums; updated trait error types and method signatures.
crates/keys/src/cosmos.rs Replaced generic error handling with explicit mapping to SignatureError::CosmosError.
crates/keys/src/signatures.rs Replaced anyhow with SignatureError enum for error handling; updated method signatures and error conversions.
crates/keys/src/signing_keys.rs Replaced anyhow with custom error enums; updated all method signatures and error conversions to use detailed domain-specific errors.
crates/keys/src/verifying_keys.rs Replaced anyhow with VerificationError enum; updated all method signatures and error conversions; removed anyhow macros.

Sequence Diagram(s)

sequenceDiagram
    participant Caller
    participant SigningKey
    participant VerifyingKey
    participant Signature

    Caller->>SigningKey: new_with_algorithm()
    SigningKey-->>Caller: Result<SigningKey, KeysError>

    Caller->>SigningKey: sign(message)
    SigningKey-->>Caller: Result<Signature, KeysError>

    Caller->>VerifyingKey: verify_signature(message, signature)
    VerifyingKey-->>Caller: Result<(), VerificationError>

    Caller->>Signature: from_algorithm_and_bytes(algorithm, bytes)
    Signature-->>Caller: Result<Signature, SignatureError>
Loading

Possibly related PRs

  • #271: Refactors signing_keys.rs for PKCS#8 PEM support and introduces custom error types, directly related to this PR's error handling changes.
  • #188: Introduces the CryptoAlgorithm enum and updates method signatures to use it; this PR builds upon that by enhancing error handling around those components.
  • #256: Adds new signature algorithm variants and verification support; related through shared code areas but focuses on algorithm functionality while this PR focuses on error type restructuring.

Suggested reviewers

  • sebasti810
  • distractedm1nd

Poem

In the warren of code, where errors would sprawl,
Now custom enums answer each call.
No more "anyhow" hopping in fright—
Each bug and mishap gets handled just right!
With thiserror carrots, our crate feels robust,
And the rabbits all cheer, in error-handling trust!
🥕


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8f0c531 and b8fb92c.

📒 Files selected for processing (1)
  • crates/keys/src/signing_keys.rs (5 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • crates/keys/src/signing_keys.rs
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: unit-test
  • GitHub Check: integration-test
  • GitHub Check: coverage
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate Unit Tests
  • Create PR with Unit Tests
  • Post Copyable Unit Tests in Comment

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 auto-generate unit tests to generate unit tests for 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.

@Zombeescott Zombeescott marked this pull request as draft June 24, 2025 09:41
@Zombeescott Zombeescott changed the title refactor: thiserror enums in keys (In-Progress) refactor: thiserror enums in keys Jun 24, 2025
@Zombeescott Zombeescott marked this pull request as ready for review June 24, 2025 10:40
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 (4)
crates/keys/src/algorithm.rs (2)

91-95: Consider adding more specific error variants.

The AlgorithmError enum currently only has a GeneralError variant, which doesn't provide much more error specificity than the previous anyhow usage. Consider adding more specific variants like UnsupportedAlgorithmOid, UnsupportedEllipticCurveOid, and ParameterParsingError to improve error handling granularity.

 #[derive(Error, Clone, Debug)]
 pub enum AlgorithmError {
+    #[error("unsupported algorithm OID: {0}")]
+    UnsupportedAlgorithmOid(String),
+    #[error("unsupported elliptic curve OID: {0}")]
+    UnsupportedEllipticCurveOid(String),
+    #[error("failed to parse algorithm parameters: {0}")]
+    ParameterParsingError(String),
     #[error("error: {0}")]
     GeneralError(String),
 }

71-87: Error mappings are correct but could use specific variants.

The error mappings correctly convert underlying errors to AlgorithmError::GeneralError, but if you implement the more specific error variants suggested above, you could map these errors more precisely:

  • Line 73: Map to ParameterParsingError
  • Lines 79-81: Map to UnsupportedEllipticCurveOid
  • Lines 84-86: Map to UnsupportedAlgorithmOid
crates/keys/src/cosmos.rs (1)

136-140: Improve error message clarity and consider specific variants.

The error message "something went wrong: {0}" is quite generic. Consider making it more descriptive, and adding specific error variants for different failure modes in Cosmos operations.

 #[derive(Error, Clone, Debug)]
 pub enum CosmosError {
-    #[error("something went wrong: {0}")]
+    #[error("json serialization failed: {0}")]
+    SerializationError(String),
+    #[error("bech32 encoding failed: {0}")]
+    Bech32Error(String),
+    #[error("cosmos operation failed: {0}")]
     GeneralError(String),
 }

Then update the error mappings to use specific variants:

  • Line 80: Use SerializationError for JSON serialization failures
  • Line 101: Use SerializationError for JSON serialization failures
  • Line 132: Use Bech32Error for bech32 encoding failures
crates/keys/src/verifying_keys.rs (1)

131-194: Comprehensive signature verification with appropriate error handling.

The verify_signature method properly maps different error conditions to appropriate VerificationError variants:

  • InvalidSignError for signature type mismatches
  • VerifyError for cryptographic verification failures
  • SignatureError for algorithm-specific signature issues
  • GeneralError for wrapped errors from other modules

The commented-out anyhow error lines (154, 167) can be removed for cleaner code.

-                    // .map_err(|e| anyhow!("Failed to verify secp256k1 signature: {}", e))
                     .map_err(|e| {
                         VerificationError::VerifyError("secp256k1".to_string(), e.to_string())
                     })
-                    // .map_err(|e| anyhow!("Failed to verify secp256r1 signature: {}", e))
                     .map_err(|e| {
                         VerificationError::VerifyError("secp256r1".to_string(), e.to_string())
                     })
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 43b432b and 7fa11e4.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (4)
  • crates/keys/Cargo.toml (1 hunks)
  • crates/keys/src/algorithm.rs (2 hunks)
  • crates/keys/src/cosmos.rs (4 hunks)
  • crates/keys/src/verifying_keys.rs (5 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • crates/keys/Cargo.toml
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: coverage
  • GitHub Check: unit-test
  • GitHub Check: integration-test
🔇 Additional comments (6)
crates/keys/src/cosmos.rs (3)

69-83: Function signature and error handling updated correctly.

The refactor properly updates the return type and error handling. The error mapping on line 80 correctly converts nested errors, though it could benefit from the more specific error variants suggested above.


97-106: Consistent error handling implementation.

The function correctly uses the new CosmosError type and properly maps JSON serialization errors.


122-134: Proper error conversion for bech32 operations.

The error mapping correctly converts bech32 encoding errors to CosmosError::GeneralError.

crates/keys/src/verifying_keys.rs (3)

363-379: Excellent error enum design with comprehensive variants.

This VerificationError enum is well-designed with specific variants for different failure modes. The error messages are descriptive and provide good context for debugging. This is a great example of how the other error enums in the crate could be structured.


92-119: Consistent and well-structured error mappings.

The error mappings in from_algorithm_and_bytes properly use the VerifyError variant with descriptive algorithm names. The error handling is consistent across all algorithm types.


227-262: Proper SPKI parsing with detailed error context.

The from_spki method effectively uses different error variants based on the failure mode:

  • GeneralError for algorithm parsing and general SPKI errors
  • IntoRefError for algorithm-specific key conversion failures
  • NotImplementedError for unsupported algorithms

This provides excellent error granularity for debugging SPKI parsing issues.

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

🔭 Outside diff range comments (1)
crates/node_types/lightclient/src/lightclient.rs (1)

307-364: Remove unused helper methods

The methods extract_commitments, verify_commitments, and verify_snark_proof are no longer used since verification is now handled by the VerifiableEpoch trait. These should be removed to avoid confusion.

-    fn extract_commitments(&self, public_values: &[u8]) -> Result<(Digest, Digest)> {
-        let mut slice = [0u8; 32];
-        slice.copy_from_slice(&public_values[..32]);
-        let proof_prev_commitment = Digest::from(slice);
-
-        let mut slice = [0u8; 32];
-        slice.copy_from_slice(&public_values[32..64]);
-        let proof_current_commitment = Digest::from(slice);
-
-        Ok((proof_prev_commitment, proof_current_commitment))
-    }
-
-    fn verify_commitments(
-        &self,
-        finalized_epoch: &FinalizedEpoch,
-        proof_prev_commitment: Digest,
-        proof_current_commitment: Digest,
-    ) -> Result<()> {
-        if finalized_epoch.prev_commitment != proof_prev_commitment
-            || finalized_epoch.current_commitment != proof_current_commitment
-        {
-            // maybe we should forwards events for these kind of errors as well.
-            return Err(anyhow::anyhow!(
-                "Commitment mismatch: prev={:?}/{:?}, current={:?}/{:?}",
-                finalized_epoch.prev_commitment,
-                proof_prev_commitment,
-                finalized_epoch.current_commitment,
-                proof_current_commitment
-            ));
-        }
-        Ok(())
-    }
-
-    fn verify_snark_proof(
-        &self,
-        finalized_epoch: &FinalizedEpoch,
-        public_values: &[u8],
-    ) -> Result<()> {
-        #[cfg(target_arch = "wasm32")]
-        let finalized_epoch_proof = &finalized_epoch.proof;
-
-        #[cfg(not(target_arch = "wasm32"))]
-        let finalized_epoch_proof = &finalized_epoch.proof.bytes();
-
-        let vkey = if finalized_epoch.height == 0 {
-            &self.sp1_vkeys.base_vk
-        } else {
-            &self.sp1_vkeys.recursive_vk
-        };
-
-        Groth16Verifier::verify(
-            finalized_epoch_proof,
-            public_values,
-            vkey,
-            &sp1_verifier::GROTH16_VK_BYTES,
-        )
-        .map_err(|e| anyhow::anyhow!("SNARK verification failed: {:?}", e))
-    }
🧹 Nitpick comments (4)
crates/da/src/celestia/full_node.rs (1)

3-6: Consider grouping related imports

The imports could be better organized by grouping the event-related imports together.

 use crate::{
     FinalizedEpoch, LightDataAvailabilityLayer, VerifiableEpoch,
-    events::{EventChannel, PrismEvent},
 };
+use crate::events::{EventChannel, PrismEvent};

Also applies to: 20-20

crates/da/src/celestia/light_client.rs (1)

156-158: Consider making this method consistent with the trait

While this method provides convenient access to the event publisher, other implementations don't have this method. Consider if this should be part of the trait interface or if it's specific to this implementation.

crates/da/src/lib.rs (1)

143-144: Add context to magic number

The check for 64 bytes would benefit from a comment explaining why this specific length is required.

+        // Public values must contain at least 64 bytes: 32 for previous commitment + 32 for current commitment
         if self.public_values.len() < 64 {
             return Err(EpochVerificationError::InvalidPublicValues(
                 self.public_values.len(),
             ));
         }
crates/node_types/lightclient/src/lightclient.rs (1)

79-84: Consider extracting the initial sync state to a constructor

The SyncState initialization could be extracted to an associated function for better readability.

+impl SyncState {
+    fn new() -> Self {
+        Self {
+            current_height: 0,
+            initial_sync_completed: false,
+            initial_sync_in_progress: false,
+            latest_finalized_epoch: None,
+        }
+    }
+}

Then use it as:

-        let sync_state = Arc::new(RwLock::new(SyncState {
-            current_height: 0,
-            initial_sync_completed: false,
-            initial_sync_in_progress: false,
-            latest_finalized_epoch: None,
-        }));
+        let sync_state = Arc::new(RwLock::new(SyncState::new()));
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 7fa11e4 and 3f2b9f5.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (20)
  • crates/cli/src/cfg.rs (2 hunks)
  • crates/cli/src/main.rs (3 hunks)
  • crates/da/Cargo.toml (1 hunks)
  • crates/da/src/celestia/full_node.rs (8 hunks)
  • crates/da/src/celestia/light_client.rs (5 hunks)
  • crates/da/src/celestia/utils.rs (4 hunks)
  • crates/da/src/events.rs (5 hunks)
  • crates/da/src/lib.rs (4 hunks)
  • crates/da/src/memory.rs (9 hunks)
  • crates/da/src/utils.rs (1 hunks)
  • crates/errors/src/lib.rs (1 hunks)
  • crates/node_types/lightclient/src/lib.rs (0 hunks)
  • crates/node_types/lightclient/src/lightclient.rs (10 hunks)
  • crates/node_types/prover/src/prover/tests/mod.rs (1 hunks)
  • crates/node_types/prover/src/prover_engine.rs (2 hunks)
  • crates/node_types/prover/src/syncer.rs (4 hunks)
  • crates/node_types/uniffi-lightclient/src/lib.rs (4 hunks)
  • crates/node_types/uniffi-lightclient/src/types.rs (2 hunks)
  • crates/tests/src/lib.rs (2 hunks)
  • verification_keys/keys.json (1 hunks)
💤 Files with no reviewable changes (1)
  • crates/node_types/lightclient/src/lib.rs
✅ Files skipped from review due to trivial changes (4)
  • verification_keys/keys.json
  • crates/da/src/utils.rs
  • crates/da/Cargo.toml
  • crates/node_types/uniffi-lightclient/src/types.rs
🧰 Additional context used
🧠 Learnings (1)
crates/da/src/celestia/utils.rs (1)
Learnt from: sebasti810
PR: deltadevsde/prism#342
File: crates/cli/src/main.rs:152-155
Timestamp: 2025-06-17T07:14:03.223Z
Learning: In the Prism codebase, the verifying_key field in NetworkConfig was changed from Option<VerifyingKey> to VerifyingKey because it's always required by all node types (LightClient, Prover, FullNode) and a sensible default (generated key) can be provided when not explicitly configured.
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: unused dependencies
  • GitHub Check: coverage
  • GitHub Check: integration-test
  • GitHub Check: unit-test
🔇 Additional comments (35)
crates/node_types/prover/src/prover/tests/mod.rs (1)

114-122: LGTM! Test updated to use trait-based interface.

The test correctly adapts to the new trait-based interface using commitments() and height() methods instead of direct field access. This aligns with the broader refactoring toward VerifiableEpoch trait abstraction.

crates/tests/src/lib.rs (1)

103-103: LGTM! Simplified LightClient constructor.

The removal of the EventChannel parameter aligns with the refactoring that moved event handling internally within the LightClient.

crates/cli/src/main.rs (2)

93-93: LGTM! Simplified LightClient constructor.

Consistent with the event handling refactoring that moved EventChannel management internally.


152-152: LGTM! Simplified verifying_key handling.

The direct cloning without error handling aligns with the change from Option<VerifyingKey> to VerifyingKey, ensuring a verifying_key is always available.

crates/cli/src/cfg.rs (2)

20-20: LGTM! Removed unused import.

The removal of warn from the tracing import aligns with the removal of warning logs throughout the codebase.


298-298: LGTM! Improved verifying_key handling.

The change to .unwrap_or(network_config.verifying_key.clone()) is more efficient and aligns with the type change from Option<VerifyingKey> to VerifyingKey.

crates/da/src/celestia/utils.rs (3)

1-1: LGTM! Updated imports.

The additional imports support the new verifying_key functionality and are correctly added.

Also applies to: 9-9


56-56: LGTM! Changed verifying_key to required field.

The change from Option<VerifyingKey> to VerifyingKey aligns with the broader refactoring to make verifying_key always available, as confirmed by the retrieved learning.


89-92: LGTM! Removed unnecessary Option wrapper.

The direct VerifyingKey value is consistent with the type change and removes the unnecessary Some() wrapper.

crates/node_types/uniffi-lightclient/src/lib.rs (4)

9-13: LGTM! Import organization improves clarity.

The separation of EventSubscriber import and explicit import of LightClient improves code readability.


25-25: Good simplification by removing the Option wrapper.

Removing the Option wrapper from event_subscriber eliminates unnecessary null checks and simplifies the code, as the event subscriber is always initialized in the constructor.


54-63: Clean simplification of event subscription initialization.

The direct subscription from da.event_channel and removal of the Some() wrapper streamlines the initialization process, aligning with the unified event handling architecture.


84-89: Cleaner error handling in next_event method.

The simplified implementation correctly assumes the event subscriber is always initialized, removing unnecessary error cases and improving code clarity.

crates/node_types/prover/src/prover_engine.rs (1)

49-60: Well-designed verification keys accessor method.

The verification_keys() method correctly consolidates verification key retrieval with appropriate handling for when recursive proofs are disabled. This provides a clean interface for epoch verification.

crates/node_types/prover/src/syncer.rs (4)

216-216: Good abstraction using trait objects.

Using VerifiableEpoch trait object instead of a concrete type improves flexibility and supports different epoch implementations.


229-230: Clean encapsulation of verification logic.

The simplified verification using epoch.verify() centralizes all verification steps (signature, commitment, and SNARK proof) into a single method call, improving maintainability.


235-238: Improved error context for missing epochs.

Adding context to the error message helps with debugging when previous epochs are missing from the database.


277-277: Appropriate use of type conversion for storage.

The try_convert() method correctly handles the conversion from trait object to concrete type for database storage, maintaining compatibility with the existing storage layer.

crates/da/src/events.rs (3)

16-16: Appropriate rename to PrismEvent.

The rename from LightClientEvent to PrismEvent better reflects the system-wide nature of these events and improves naming consistency.


112-138: Well-implemented event forwarding mechanism.

The start_forwarding method correctly:

  • Spawns an async task for continuous event processing
  • Filters specific Lumina events to Prism events
  • Handles platform-specific behavior for WASM vs non-WASM targets
  • Gracefully exits when the channel is closed

141-147: Convenient From trait implementation.

The automatic setup of event forwarding when creating an EventChannel from a Lumina subscriber simplifies initialization and ensures forwarding is always configured.

crates/errors/src/lib.rs (2)

84-84: Good addition of specific epoch verification error variant.

Adding the EpochVerification variant to DataAvailabilityError properly categorizes epoch-related errors within the DA context.


89-125: Well-structured error hierarchy for epoch verification.

The new error enums provide excellent granularity for different verification failure modes:

  • EpochVerificationError as the top-level error with specific variants
  • SignatureError and CommitmentError for specialized error cases
  • Proper use of #[from] for automatic error conversion

This aligns perfectly with the PR objective of replacing generic errors with specific thiserror enums.

crates/da/src/celestia/full_node.rs (3)

3-6: Inconsistency with PR objectives

The PR objectives state that this PR is about "replacing references to the anyhow crate within the keys folder" and "refactoring error handling by substituting anyhow with thiserror enums". However, this file is in the crates/da module and the changes are related to event channel refactoring and epoch verification abstractions, not error handling in the keys module.

Are these the correct files for review? The changes don't match the stated PR objectives.

Likely an incorrect or invalid review comment.


76-97: LGTM! Clean trait object conversion

The conversion from concrete FinalizedEpoch to VerifiableEpoch trait objects is implemented correctly, with proper error handling for blob parsing failures.


139-140: Good addition of event publishing

Publishing the UpdateDAHeight event when headers are received enables other components to react to height updates through the unified event system.

crates/da/src/memory.rs (2)

114-117: Event publishing placement looks good

The UpdateDAHeight event is published at the right time - after the new block is created and the height is updated, ensuring consistency between the published event and the actual state.


131-136: Efficient trait object conversion

The conversion to VerifiableEpoch trait objects is implemented efficiently using iterator methods.

crates/da/src/celestia/light_client.rs (1)

106-109: Event channel forwarding setup looks correct

The conversion from Lumina's event subscriber to Prism's EventChannel is properly implemented in both constructors, ensuring events are forwarded correctly.

Also applies to: 142-145

crates/da/src/lib.rs (4)

8-8: Error handling improvement aligns with PR objectives

This import of specific error types from prism_errors shows the move away from generic anyhow errors to domain-specific error enums, which aligns with the stated PR objectives of using thiserror enums.


40-79: Well-designed abstraction for epoch verification

The VerifiableStateTransition trait and EpochCommitments struct provide a clean abstraction for epoch verification, enabling better testability through mocking and clearer separation of concerns.


133-169: Comprehensive verification with detailed error handling

The verification logic is well-structured with:

  • Clear separation of signature, commitment, and proof verification
  • Specific error types for each failure mode
  • Proper error propagation

This is a significant improvement in error handling granularity.


248-248: Good addition of automock for testing

Adding the #[automock] attribute enables easy mocking of the LightDataAvailabilityLayer trait, which will improve testability.

crates/node_types/lightclient/src/lightclient.rs (2)

37-37: Field visibility change looks good

Removing the pub modifier from prover_pubkey improves encapsulation since this field doesn't need to be publicly accessible.


260-272: Clean abstraction using the trait method

The epoch processing is now much cleaner, delegating all verification logic to the VerifiableEpoch trait. This improves separation of concerns and makes the code more maintainable.

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 (2)
crates/keys/src/verifying_keys.rs (2)

23-23: Remove unnecessary explicit Result import.

The std::result::Result type is available in the prelude and doesn't need to be explicitly imported.

-    result::Result,

363-379: Consider consolidating redundant error variants.

The VerificationError enum has good coverage of error cases, but there may be some redundancy between InvalidSignError and SignatureError. Consider whether both are needed or if they can be consolidated for better consistency.

If you decide to keep both variants, consider renaming them to be more descriptive:

  • InvalidSignErrorSignatureTypeMismatch
  • SignatureErrorUnsupportedSignatureType

Or consolidate them into a single variant:

-    #[error("invalid signature type")]
-    InvalidSignError,
-    #[error("verifying key for {0} can only verify secp256k1 signatures")]
-    SignatureError(String),
+    #[error("signature type mismatch: {0}")]
+    SignatureTypeMismatch(String),
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 3f2b9f5 and 8aa6846.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (6)
  • crates/keys/Cargo.toml (1 hunks)
  • crates/keys/src/algorithm.rs (2 hunks)
  • crates/keys/src/cosmos.rs (4 hunks)
  • crates/keys/src/signatures.rs (5 hunks)
  • crates/keys/src/signing_keys.rs (7 hunks)
  • crates/keys/src/verifying_keys.rs (5 hunks)
🚧 Files skipped from review as they are similar to previous changes (5)
  • crates/keys/Cargo.toml
  • crates/keys/src/algorithm.rs
  • crates/keys/src/cosmos.rs
  • crates/keys/src/signing_keys.rs
  • crates/keys/src/signatures.rs
⏰ Context from checks skipped due to timeout of 90000ms (5)
  • GitHub Check: clippy
  • GitHub Check: coverage
  • GitHub Check: integration-test
  • GitHub Check: unit-test
  • GitHub Check: unused dependencies
🔇 Additional comments (6)
crates/keys/src/verifying_keys.rs (6)

92-119: Good refactoring of error handling.

The function correctly maps underlying cryptographic errors to domain-specific VerificationError::VerifyError variants with appropriate context.


196-215: Good error handling for SPKI DER conversion.

The function appropriately handles not-implemented cases and maps conversion errors to GeneralError.


217-276: SPKI-related functions have consistent error handling.

The functions correctly propagate errors from the internal to_spki_der_doc function and map I/O and parsing errors to appropriate VerificationError variants.


280-284: Trait implementation correctly updated.

The TryFrom<CryptoPayload> implementation properly uses the new VerificationError type.


309-327: FromBase64 implementation correctly refactored.

The error handling properly maps base64 decoding errors and Ed25519 key creation errors to GeneralError variants.


330-335: TryFrom implementation correctly updated.

The trait implementation properly uses the new VerificationError type.

Copy link
Contributor

@distractedm1nd distractedm1nd left a comment

Choose a reason for hiding this comment

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

Good work so far, I think now we can actually zoom out one level further and it will reduce a lot of extra map_errs and be more clear:

Currently, the error structure is:
VerifyingKey methods produce KeysError
SigningKey methods produce VerificationError
Signature methods produce SignatureError
Cosmos sig impl produces CosmosError
Algorithm produces AlgorithmError

This makes conversions between the types inside the crate tedious, because you have to map_err while still being inside the same crate.

I suggest now that you've made the error types, we refactor it so:

  • All error types can go into a new errors mod in a errors.rs file
  • There is a top level error type, for example KeyError, that you use the thiserror from attribute with for conversion from the other error types (view error crate's errors to see example). This will prevent you from needing to map inside crate
  • Define Result type that is Result<G, KeyError>. All methods in the crate should return this top level error, so then the mapping is trivial, not only inside in the crate, but for its users as well

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)
crates/keys/src/errors.rs (1)

17-27: Consider more specific error message for CosmosError.

The SignatureError enum is well-structured, but the CosmosError variant uses a generic "Something went wrong" message. Consider making this more specific to the cosmos-related failure.

-    #[error("Something went wrong: {0}")]
+    #[error("Cosmos signature operation failed: {0}")]
     CosmosError(String),
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8aa6846 and 401675d.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (7)
  • crates/keys/src/algorithm.rs (3 hunks)
  • crates/keys/src/cosmos.rs (4 hunks)
  • crates/keys/src/errors.rs (1 hunks)
  • crates/keys/src/lib.rs (1 hunks)
  • crates/keys/src/signatures.rs (4 hunks)
  • crates/keys/src/signing_keys.rs (5 hunks)
  • crates/keys/src/verifying_keys.rs (6 hunks)
✅ Files skipped from review due to trivial changes (1)
  • crates/keys/src/lib.rs
🚧 Files skipped from review as they are similar to previous changes (5)
  • crates/keys/src/cosmos.rs
  • crates/keys/src/algorithm.rs
  • crates/keys/src/signatures.rs
  • crates/keys/src/verifying_keys.rs
  • crates/keys/src/signing_keys.rs
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: clippy
  • GitHub Check: coverage
  • GitHub Check: integration-test
  • GitHub Check: unit-test
🔇 Additional comments (3)
crates/keys/src/errors.rs (3)

1-3: LGTM! Clean error handling foundation.

The import and generic Result type alias provide a clean foundation for the error handling refactor. The type alias will make function signatures more concise throughout the codebase.


5-15: Well-designed error aggregation enum.

The CryptoError enum effectively aggregates domain-specific errors with automatic conversion via #[from]. The error messages clearly indicate the error domain, which will help with debugging.


29-43: LGTM! Well-defined key operation errors.

The KeysError enum comprehensively covers key-related operations with specific, actionable error messages. The variants clearly distinguish between different failure modes.

Copy link
Contributor

@distractedm1nd distractedm1nd left a comment

Choose a reason for hiding this comment

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

as discussed irl, lets do

CryptoError
> ParseError
> SignatureError

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

♻️ Duplicate comments (4)
crates/keys/src/errors.rs (4)

47-47: Consider renaming for consistency with user feedback.

Based on the past review comments, "DerParseError" appears to be the preferred naming. The current name aligns with this preference.


68-68: Naming aligns with user feedback.

The "VKCreationError" name matches the user's preferred naming convention from past comments.


64-66: Fix naming conflict with SignatureError enum.

The SignatureError variant name conflicts with the SignatureError enum defined at line 18, which can cause confusion and potential compilation issues.

Apply this diff to resolve the naming conflict:

-    #[error("Verifying key for {0} can only verify secp256k1 signatures")]
-    SignatureError(String),
+    #[error("Verifying key for {0} can only verify secp256k1 signatures")]
+    UnsupportedSignatureTypeError(String),

55-56: Replace generic error messages with more descriptive ones.

The GeneralError variants use generic messages like "A parsing error occurred" and "A verification error occurred" which aren't helpful for debugging.

Apply these diffs to improve error specificity:

-    #[error("A parsing error occured: {0}")]
-    GeneralError(String),
+    #[error("Parse operation failed: {0}")]
+    OperationFailedError(String),
-    #[error("A verification error occured: {0}")]
-    GeneralError(String),
+    #[error("Verification operation failed: {0}")]
+    OperationFailedError(String),

Also applies to: 76-77

🧹 Nitpick comments (1)
crates/keys/src/errors.rs (1)

55-55: Fix typo in error messages.

Both "GeneralError" variants contain a typo: "occured" should be "occurred".

Apply these diffs to fix the typos:

-    #[error("A parsing error occured: {0}")]
+    #[error("A parsing error occurred: {0}")]
-    #[error("A verification error occured: {0}")]
+    #[error("A verification error occurred: {0}")]

Also applies to: 76-76

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 401675d and 9e06ce8.

📒 Files selected for processing (3)
  • crates/keys/src/cosmos.rs (4 hunks)
  • crates/keys/src/errors.rs (1 hunks)
  • crates/keys/src/verifying_keys.rs (6 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • crates/keys/src/cosmos.rs
  • crates/keys/src/verifying_keys.rs
🧰 Additional context used
🧠 Learnings (2)
📓 Common learnings
Learnt from: distractedm1nd
PR: deltadevsde/prism#146
File: crates/common/src/hashchain.rs:164-174
Timestamp: 2024-11-01T07:51:25.629Z
Learning: In `crates/common/src/hashchain.rs`, extracting duplicated key validation logic between different operation types is not feasible without refactoring the underlying enum structs to use the same type.
Learnt from: CR
PR: deltadevsde/prism#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-23T12:18:00.367Z
Learning: Handle errors using Rust's Result types and provide descriptive error messages to aid debugging and user understanding.
crates/keys/src/errors.rs (6)
Learnt from: CR
PR: deltadevsde/prism#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-23T12:18:00.367Z
Learning: Handle errors using Rust's Result types and provide descriptive error messages to aid debugging and user understanding.
Learnt from: distractedm1nd
PR: deltadevsde/prism#141
File: crates/common/src/operation.rs:311-313
Timestamp: 2024-10-16T12:03:50.680Z
Learning: When implementing `AddSignedData` in `crates/common/src/operation.rs`, ensure that signatures cover the entire operation (including metadata like account ID) to prevent replay attacks or unauthorized data modifications. Including a `value_signature: Option<(VerifyingKey, Signature)>` allows for externally signed data while ensuring proper validation.
Learnt from: distractedm1nd
PR: deltadevsde/prism#146
File: crates/common/src/hashchain.rs:164-174
Timestamp: 2024-11-01T07:51:25.629Z
Learning: In `crates/common/src/hashchain.rs`, extracting duplicated key validation logic between different operation types is not feasible without refactoring the underlying enum structs to use the same type.
Learnt from: sebasti810
PR: deltadevsde/prism#342
File: crates/cli/src/main.rs:152-155
Timestamp: 2025-06-17T07:14:03.223Z
Learning: In the Prism codebase, the verifying_key field in NetworkConfig was changed from Option<VerifyingKey> to VerifyingKey because it's always required by all node types (LightClient, Prover, FullNode) and a sensible default (generated key) can be provided when not explicitly configured.
Learnt from: distractedm1nd
PR: deltadevsde/prism#193
File: crates/node_types/lightclient/src/lightclient.rs:68-74
Timestamp: 2025-01-08T09:35:23.121Z
Learning: In the LightClient implementation, signature verification failures should trigger a panic as clients must not proceed with potentially compromised data. This is a security measure rather than an error handling concern.
Learnt from: distractedm1nd
PR: deltadevsde/prism#150
File: crates/common/src/keys.rs:27-31
Timestamp: 2024-10-29T15:02:10.475Z
Learning: In the Rust codebase of `prism`, within the `VerifyingKey::as_bytes` method in `crates/common/src/keys.rs`, returning a `Vec<u8>` is necessary because the underlying key types (`Secp256k1VerifyingKey` and `Ed25519VerifyingKey`) provide their byte representations by value. Returning a `&[u8]` would involve borrowing from a temporary value, which is not feasible.
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: coverage
  • GitHub Check: unit-test
🔇 Additional comments (1)
crates/keys/src/errors.rs (1)

1-15: Well-structured error hierarchy with thiserror.

The main CryptoError enum effectively aggregates domain-specific error types with automatic conversions via #[from]. This provides a clean API while maintaining detailed error information.

@distractedm1nd distractedm1nd merged commit 5a646dc into deltadevsde:main Jun 26, 2025
5 of 8 checks passed
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.

2 participants