Skip to content

Conversation

@ljttl3q04t
Copy link
Member

@ljttl3q04t ljttl3q04t commented Jun 30, 2025

Summary by CodeRabbit

  • New Features

    • Introduced new certificate types related to committee authorization, decentralized representatives (DReps), and vote delegation, with corresponding public structures and enums.
    • Added support for DRep entities, including creation methods and serialization.
    • Implemented a new Vote Delegation certificate type, including serialization and deserialization.
    • Added a method to check for script hash presence in stake credentials.
  • Bug Fixes

    • Corrected redeemer byte handling during transaction building.
  • Tests

    • Added unit tests for DRep serialization and Vote Delegation certificate round-tripping.
  • Documentation

    • Extended error reporting for deserialization failures with more detailed mismatch information.

@ljttl3q04t
Copy link
Member Author

@coderabbitai full review

@ljttl3q04t ljttl3q04t requested a review from Copilot June 30, 2025 13:26
Copy link

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull Request Overview

This PR adds Vote Delegation support across multiple modules by updating certificate types, serialization/deserialization logic, and related API functions.

  • Updated tx_builder to properly extract redeemer bytes with tuple destructuring.
  • Introduced new serialization and deserialization routines for VoteDelegation and associated types such as DRep.
  • Extended CertificateKind and CertificateEnum with new variants and API methods for VoteDelegation.

Reviewed Changes

Copilot reviewed 6 out of 7 changed files in this pull request and generated no comments.

Show a summary per file
File Description
rust/src/tx_builder.rs Adjusted iteration mapping and added handling for VoteDelegation certificates.
rust/src/serialization.rs Added new helper functions for index checks and VoteDelegation serialization/deserialization; updated CertificateEnum serialization to include VoteDelegation.
rust/src/lib.rs Extended certificate enums with additional variants and new VoteDelegation API methods.
rust/src/error.rs Added FixedValuesMismatch variant to DeserializeFailure.
rust/src/address.rs Introduced has_script_hash method for StakeCredential.
rust/Cargo.toml Updated dependency revision for uplc.
Comments suppressed due to low confidence (2)

rust/src/serialization.rs:1984

  • Avoid panicking on unhandled certificate variants in the serialization logic. Consider returning a Result with an appropriate error instead for better API resilience.
            CertificateEnum::VoteDelegation(x) => x.serialize(serializer),

rust/src/lib.rs:1240

  • Using panic for undefined certificate kinds may lead to unexpected shutdowns at runtime. It is recommended to handle this case gracefully, possibly by returning a default value or error.
            // For all other variants, return a default or placeholder value, or handle as needed.

@ljttl3q04t
Copy link
Member Author

@CodeRabbit full review

@ljttl3q04t
Copy link
Member Author

@coderabbitai help

@coderabbitai
Copy link

coderabbitai bot commented Jul 1, 2025

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.

@ljttl3q04t
Copy link
Member Author

@coderabbitai full review

@coderabbitai
Copy link

coderabbitai bot commented Jul 1, 2025

✅ Actions performed

Full review triggered.

@coderabbitai
Copy link

coderabbitai bot commented Jul 1, 2025

Walkthrough

The changes introduce new certificate types and related structures for vote delegation and decentralized representatives (DReps) in the Rust codebase. Serialization, deserialization, and transaction witness logic are extended to handle these new variants. Additional utility functions and unit tests are added to support and validate the new functionality.

Changes

File(s) Change Summary
rust/Cargo.toml Updated uplc dependency revision hash.
rust/src/address.rs Added has_script_hash method to StakeCredential.
rust/src/error.rs Added FixedValuesMismatch variant to DeserializeFailure enum and updated its Display implementation.
rust/src/lib.rs Introduced new certificate variants, DRep enums and structs, vote delegation structs, and integrated them into public APIs.
rust/src/serialization.rs Added serialization/deserialization for DRep and VoteDelegation; utility functions for CBOR structure checks; extended CertificateEnum serialization.
rust/src/tx_builder.rs Fixed redeemer bytes handling; extended witness key extraction to support VoteDelegation certificates; added unit tests for DRep and VoteDelegation.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Certificate
    participant VoteDelegation
    participant DRep

    User->>Certificate: new_vote_delegation(VoteDelegation)
    Certificate->>VoteDelegation: Access stake_credential, drep
    VoteDelegation->>DRep: kind(), to_key_hash(), to_script_hash()
    Certificate->>Certificate: kind() (returns VoteDelegation)
Loading
sequenceDiagram
    participant Serializer
    participant VoteDelegation
    participant DRep

    Serializer->>VoteDelegation: serialize()
    VoteDelegation->>Serializer: serialize stake_credential
    VoteDelegation->>DRep: serialize()
    DRep->>Serializer: serialize DRepEnum variant
Loading

Poem

🐇
New delegates hop into view,
DReps and votes, a shiny crew!
With hashes, keys, and scripts in tow,
Serialization’s all aglow.
Tests confirm each bunny’s leap—
The code is strong, the changes deep!
Hooray for features, crisp and neat!

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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.

Copy link

@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: 5

🔭 Outside diff range comments (3)
rust/src/serialization.rs (2)

2015-2102: Add VoteDelegation deserialization to CertificateEnum

The CertificateEnum deserialization is missing the VoteDelegation variant. This will cause deserialization failures for vote delegation certificates.

Add the following match arm after line 2096:

         };
+        match (|raw: &mut Deserializer<_>| -> Result<_, DeserializeError> {
+            Ok(VoteDelegation::deserialize_as_embedded_group(raw, len)?)
+        })(raw)
+        {
+            Ok(variant) => return Ok(CertificateEnum::VoteDelegation(variant)),
+            Err(_) => raw
+                .as_mut_ref()
+                .seek(SeekFrom::Start(initial_position))
+                .unwrap(),
+        };
         Err(DeserializeError::new(
             "CertificateEnum",
             DeserializeFailure::NoVariantMatched.into(),

5124-5739: Missing tests for VoteDelegation and DRep

We’ve confirmed there are no #[test] functions covering the new VoteDelegation or DRep types. To ensure reliability, please add unit tests that cover:

• VoteDelegation
– Round-trip CBOR serialization/deserialization via VoteDelegation::to_bytes() / from_bytes()
– Integration in CertificateEnum::VoteDelegation round trips
– Edge cases (e.g. votes for different credentials, invalid inputs)

• DRep
– Round-trip CBOR serialization/deserialization via DRep::to_bytes() / from_bytes()
– All enum variants (Key, Script, Abstain, NoConfidence)
– Integration in any surrounding structures (e.g. transaction builder)

Would you like example test stubs to get started?

rust/src/lib.rs (1)

1187-1294: Add accessor methods for new certificate types.

While new_vote_delegation constructor is added, the Certificate struct is missing accessor methods (like as_vote_delegation) for the new certificate types. This inconsistency with existing patterns (e.g., as_stake_registration, as_pool_registration) should be addressed.

Add accessor methods following the existing pattern:

pub fn as_vote_delegation(&self) -> Option<VoteDelegation> {
    match &self.0 {
        CertificateEnum::VoteDelegation(x) => Some(x.clone()),
        _ => None,
    }
}
🧹 Nitpick comments (3)
rust/src/address.rs (1)

141-146: LGTM! Consider consistency with existing patterns.

The implementation is correct and follows the established pattern of using pattern matching on the internal enum. The method provides a convenient boolean check for script hash presence.

Note: This method could also be implemented as self.kind() == StakeCredKind::Script for consistency with the existing kind() method, but the current approach is equally valid and potentially more readable.

rust/src/serialization.rs (2)

6-6: Remove unnecessary import

The use core::panic; import is unnecessary as panic! is already available in the standard prelude.

-use core::panic;

1714-1727: Consider optimizing error message allocation

The format! macro allocates a String on every error, which could impact performance in hot paths. Consider using a static error message or implementing a custom error type.

-        None => Err(cbor_event::Error::CustomError(format!(
-            "unknown index of {}",
-            name
-        ))),
+        None => Err(cbor_event::Error::CustomError(
+            "unknown index for serialization".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 5fb4c0e and 5793bfc.

⛔ Files ignored due to path filters (1)
  • rust/Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (6)
  • rust/Cargo.toml (1 hunks)
  • rust/src/address.rs (1 hunks)
  • rust/src/error.rs (2 hunks)
  • rust/src/lib.rs (5 hunks)
  • rust/src/serialization.rs (4 hunks)
  • rust/src/tx_builder.rs (3 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
rust/src/tx_builder.rs (3)
rust/src/address.rs (2)
  • from_bytes (236-240)
  • from_keyhash (112-114)
rust/src/utils.rs (1)
  • from_bytes (28-31)
rust/src/lib.rs (23)
  • new_always_abstain (1108-1110)
  • new_key_hash (1100-1102)
  • stake_credential (683-685)
  • stake_credential (706-708)
  • stake_credential (730-732)
  • stake_credential (1153-1155)
  • new (96-101)
  • new (147-157)
  • new (175-177)
  • new (208-210)
  • new (276-278)
  • new (518-529)
  • new (582-587)
  • new (661-668)
  • new (687-691)
  • new (710-714)
  • new (738-743)
  • new (756-758)
  • new (791-793)
  • new (864-886)
  • new (905-909)
  • new (933-938)
  • new_vote_delegation (1187-1189)
🔇 Additional comments (9)
rust/Cargo.toml (1)

38-38: Manual verification required: inspect uplc v1.1.13 diff

Our attempt to list commits between 3d77b5c378ce404cddd9a1f111906d72fd46fc83 and 900bf91216deff19be9b3582a9fccd03be0d485c returned no output—likely due to a shallow clone. Please manually confirm that moving to tag v1.1.13:

  • Only includes the intended vote delegation changes
  • Does not introduce other breaking changes

Location to check:

  • rust/Cargo.toml, line 38:
    uplc = { git = "https://github.com/aiken-lang/aiken.git", rev = "900bf91216deff19be9b3582a9fccd03be0d485c", default-features = false }
rust/src/error.rs (2)

37-40: LGTM! Enhanced error reporting capability.

The new FixedValuesMismatch variant properly extends the error handling to support multiple expected values, which is useful for cases where several valid options exist.


111-113: LGTM! Consistent error message formatting.

The Display implementation correctly handles the new variant by formatting the expected values using debug representation, which is appropriate for showing a vector of keys.

rust/src/tx_builder.rs (4)

104-108: LGTM! Vote delegation certificate handling looks correct.

The implementation properly extracts the stake credential from the vote delegation certificate and adds the key hash to the witness set when present. This follows the established pattern for other certificate types and correctly handles the optional nature of key hashes.


2052-2057: LGTM! Basic DRep serialization test is appropriate.

The test verifies that DRep::new_always_abstain() serializes to the expected CBOR hex value. The test is simple and focused on the core functionality.


2059-2076: LGTM! Comprehensive vote delegation test with good coverage.

The test thoroughly validates the vote delegation certificate creation and serialization process:

  • Creates DRep with key hash
  • Creates stake credential from key hash
  • Constructs VoteDelegation certificate
  • Verifies final CBOR encoding

The test covers the end-to-end flow and uses realistic hex values for validation.


71-71: I need to inspect how redeemers_bytes is produced and the surrounding context to confirm the tuple structure. Let me pull in the relevant section of rust/src/tx_builder.rs.

rust/src/lib.rs (2)

1076-1138: Well-structured DRep implementation.

The DRep type is properly implemented with all necessary constructors, conversion methods, and a clear enum structure for different DRep variants.


1168-1170: has_script_hash is already implemented on StakeCredential

StakeCredential defines has_script_hash in rust/src/address.rs (at line 141), so the call to self.stake_credential.has_script_hash() is valid. No changes required.

Likely an incorrect or invalid review comment.

@ljttl3q04t
Copy link
Member Author

@coderabbitai thanks for review, I pushed commit ca4eb146fe71f3cfe80815539b7de533a4903ac3 to fixed your reviews, please help check

@coderabbitai
Copy link

coderabbitai bot commented Jul 1, 2025

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

@ljttl3q04t I'll help you check the commit to verify that the fixes address the review concerns. Let me examine the changes in that commit.


🏁 Script executed:

#!/bin/bash
# First, let's look at the specific commit to see what changes were made
git show ca4eb146fe71f3cfe80815539b7de533a4903ac3 --stat

echo "=== Detailed changes in the commit ==="
git show ca4eb146fe71f3cfe80815539b7de533a4903ac3

Length of output: 268870


@ljttl3q04t Got it — I’ll run an up-to-date diff on the key files and re-check the earlier review points now.


🧠 Learnings used
Learnt from: ljttl3q04t
PR: minswap/cardano-serialization-lib#45
File: rust/src/lib.rs:1050-1074
Timestamp: 2025-07-01T03:53:00.461Z
Learning: In the minswap/cardano-serialization-lib repository, dummy/placeholder structs for certificate types (like CommitteeHotAuth, CommitteeColdResign, etc.) are acceptable when they are not currently used and are intended as placeholders for future implementation.

Learnt from: ljttl3q04t
PR: minswap/cardano-serialization-lib#45
File: rust/src/serialization.rs:1983-1985
Timestamp: 2025-07-01T03:57:39.025Z
Learning: In the minswap/cardano-serialization-lib repository, using panic! for unknown/unused CertificateEnum variants in serialization is acceptable as a simple solution when those certificate types are never used in the codebase.

Copy link

@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)
rust/src/serialization.rs (1)

1770-1778: Consider clarifying the error message for DRepEnum array length validation.

The error message specifies expected length as 2, but the code actually accepts both 1 and 2 element arrays depending on the variant. Consider making this more descriptive:

                    return Err(DeserializeFailure::CBOR(cbor_event::Error::WrongLen(
-                        2,
+                        1,  // or update message to indicate "1 or 2"
                        len,
-                        "[id, hash] or [id] (for abstain and no confidence)",
+                        "[id] for abstain/no confidence or [id, hash] for key/script variants",
                    ))
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 5793bfc and ca4eb14.

📒 Files selected for processing (2)
  • rust/src/lib.rs (5 hunks)
  • rust/src/serialization.rs (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • rust/src/lib.rs
🧰 Additional context used
🧠 Learnings (2)
📓 Common learnings
Learnt from: ljttl3q04t
PR: minswap/cardano-serialization-lib#45
File: rust/src/lib.rs:1050-1074
Timestamp: 2025-07-01T03:53:00.461Z
Learning: In the minswap/cardano-serialization-lib repository, dummy/placeholder structs for certificate types (like CommitteeHotAuth, CommitteeColdResign, etc.) are acceptable when they are not currently used and are intended as placeholders for future implementation.
Learnt from: ljttl3q04t
PR: minswap/cardano-serialization-lib#45
File: rust/src/serialization.rs:1983-1985
Timestamp: 2025-07-01T03:57:39.025Z
Learning: In the minswap/cardano-serialization-lib repository, using panic! for unknown/unused CertificateEnum variants in serialization is acceptable as a simple solution when those certificate types are never used in the codebase.
rust/src/serialization.rs (2)

undefined

<retrieved_learning>
Learnt from: ljttl3q04t
PR: #45
File: rust/src/serialization.rs:1983-1985
Timestamp: 2025-07-01T03:57:39.025Z
Learning: In the minswap/cardano-serialization-lib repository, using panic! for unknown/unused CertificateEnum variants in serialization is acceptable as a simple solution when those certificate types are never used in the codebase.
</retrieved_learning>

<retrieved_learning>
Learnt from: ljttl3q04t
PR: #45
File: rust/src/lib.rs:1050-1074
Timestamp: 2025-07-01T03:53:00.461Z
Learning: In the minswap/cardano-serialization-lib repository, dummy/placeholder structs for certificate types (like CommitteeHotAuth, CommitteeColdResign, etc.) are acceptable when they are not currently used and are intended as placeholders for future implementation.
</retrieved_learning>

🧬 Code Graph Analysis (1)
rust/src/serialization.rs (1)
rust/src/error.rs (2)
  • from (144-146)
  • from (150-155)
🔇 Additional comments (5)
rust/src/serialization.rs (5)

1684-1725: LGTM: Well-designed utility functions for serialization validation.

These utility functions provide excellent error handling and consistent interfaces for index and serialization validation. The error propagation and conversion logic is correct, and the functions will help ensure consistency across different certificate types.


1727-1811: LGTM: Comprehensive DRep serialization implementation.

The DRep serialization correctly handles all four variants with appropriate CBOR array structures:

  • KeyHash/ScriptHash variants use 2-element arrays with index + data
  • AlwaysAbstain/AlwaysNoConfidence use 1-element arrays with just the index
  • Deserialization properly validates array lengths and variant indices
  • Error handling uses the appropriate FixedValuesMismatch for multiple expected values

1813-1826: LGTM: VoteDelegation index consistency resolved.

The VoteDelegation implementation now consistently uses index 9 across all serialization methods:

  • serialize() uses index 9 (line 1820)
  • serialize_as_embedded_group() uses index 9 (line 1915)
  • deserialize_as_embedded_group() expects index 9 (line 1954)

This addresses the index mismatch issue mentioned in previous reviews.

Also applies to: 1910-1920, 1948-1967


1892-1908: LGTM: Useful length validation utility.

The check_len function provides good validation for CBOR array lengths with descriptive error messages. The implementation correctly handles both definite and indefinite length arrays.


1982-1982: LGTM: Proper integration with existing certificate serialization.

The VoteDelegation variant is correctly added to the CertificateEnum serialization dispatch. The placement and pattern matches the existing code structure.

@ljttl3q04t
Copy link
Member Author

@coderabbitai hey, if you have no concern then approve this PR please

@coderabbitai
Copy link

coderabbitai bot commented Jul 1, 2025

Tip

For best results, initiate chat on the files or code changes.

@ljttl3q04t I appreciate your confidence in my review! However, I need to clarify that as an AI assistant, I cannot actually approve PRs on GitHub. Only human reviewers with the appropriate repository permissions can approve pull requests.

What I can do is:

  1. Provide a final review to check if the previous concerns were addressed in your latest commit
  2. Give you feedback on the code quality and implementation
  3. Help identify any remaining issues

Based on the commit you pushed (ca4eb146fe71f3cfe80815539b7de533a4903ac3), it looks like you've made substantial changes to address the review feedback. The implementation of vote delegation functionality appears well-structured with proper serialization, deserialization, and test coverage.

To get your PR approved, you should:

  • Wait for human reviewers/maintainers to review and approve it
  • Consider reaching out to the repository maintainers if needed
  • Make sure all CI checks are passing

Would you like me to do a final review check to ensure everything looks good before the maintainers take a look?

@ljttl3q04t ljttl3q04t merged commit b4adab9 into minswap-11 Jul 1, 2025
3 checks passed
@ljttl3q04t ljttl3q04t deleted the tony/certs branch July 1, 2025 04:06
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