-
Notifications
You must be signed in to change notification settings - Fork 39
refactor: thiserror enums in keys #349
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
refactor: thiserror enums in keys #349
Conversation
The latest updates on your projects. Learn more about Vercel for Git ↗︎
|
WalkthroughThis change replaces the use of the generic Changes
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>
Possibly related PRs
Suggested reviewers
Poem
📜 Recent review detailsConfiguration used: CodeRabbit UI 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
⏰ Context from checks skipped due to timeout of 90000ms (3)
✨ Finishing Touches
🧪 Generate Unit Tests
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. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed 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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this 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 aGeneralError
variant, which doesn't provide much more error specificity than the previousanyhow
usage. Consider adding more specific variants likeUnsupportedAlgorithmOid
,UnsupportedEllipticCurveOid
, andParameterParsingError
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 failurescrates/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 appropriateVerificationError
variants:
InvalidSignError
for signature type mismatchesVerifyError
for cryptographic verification failuresSignatureError
for algorithm-specific signature issuesGeneralError
for wrapped errors from other modulesThe 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
⛔ 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 theVerifyError
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 errorsIntoRefError
for algorithm-specific key conversion failuresNotImplementedError
for unsupported algorithmsThis provides excellent error granularity for debugging SPKI parsing issues.
There was a problem hiding this 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 methodsThe methods
extract_commitments
,verify_commitments
, andverify_snark_proof
are no longer used since verification is now handled by theVerifiableEpoch
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 importsThe 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 traitWhile 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 numberThe 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 constructorThe
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
⛔ 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()
andheight()
methods instead of direct field access. This aligns with the broader refactoring towardVerifiableEpoch
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>
toVerifyingKey
, 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 fromOption<VerifyingKey>
toVerifyingKey
.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>
toVerifyingKey
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 unnecessarySome()
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 ofLightClient
improves code readability.
25-25
: Good simplification by removing the Option wrapper.Removing the
Option
wrapper fromevent_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 theSome()
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
toPrismEvent
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 toDataAvailabilityError
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 variantsSignatureError
andCommitmentError
for specialized error cases- Proper use of
#[from]
for automatic error conversionThis 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 objectivesThe PR objectives state that this PR is about "replacing references to the
anyhow
crate within thekeys
folder" and "refactoring error handling by substitutinganyhow
withthiserror
enums". However, this file is in thecrates/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 conversionThe conversion from concrete
FinalizedEpoch
toVerifiableEpoch
trait objects is implemented correctly, with proper error handling for blob parsing failures.
139-140
: Good addition of event publishingPublishing 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 goodThe
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 conversionThe 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 correctThe 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 objectivesThis import of specific error types from
prism_errors
shows the move away from genericanyhow
errors to domain-specific error enums, which aligns with the stated PR objectives of usingthiserror
enums.
40-79
: Well-designed abstraction for epoch verificationThe
VerifiableStateTransition
trait andEpochCommitments
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 handlingThe 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 testingAdding the
#[automock]
attribute enables easy mocking of theLightDataAvailabilityLayer
trait, which will improve testability.crates/node_types/lightclient/src/lightclient.rs (2)
37-37
: Field visibility change looks goodRemoving the
pub
modifier fromprover_pubkey
improves encapsulation since this field doesn't need to be publicly accessible.
260-272
: Clean abstraction using the trait methodThe 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.
fdd6350
to
8aa6846
Compare
There was a problem hiding this 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 betweenInvalidSignError
andSignatureError
. 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:
InvalidSignError
→SignatureTypeMismatch
SignatureError
→UnsupportedSignatureType
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
⛔ 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 appropriateVerificationError
variants.
280-284
: Trait implementation correctly updated.The
TryFrom<CryptoPayload>
implementation properly uses the newVerificationError
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.
There was a problem hiding this 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 aerrors.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
There was a problem hiding this 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
⛔ 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.
There was a problem hiding this 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
There was a problem hiding this 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 theSignatureError
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
📒 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.
Replacement of anyhow references in the keys folder.
Summary by CodeRabbit
New Features
Bug Fixes
Refactor