Skip to content

feat: remove index tracking from commitment mask index #7373

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

Open
wants to merge 1 commit into
base: development
Choose a base branch
from

Conversation

SWvheerden
Copy link
Collaborator

@SWvheerden SWvheerden commented Jul 25, 2025

Description

Removes index tracking from commitment mask index

Motivation and Context

This used to be very important before we started using the key manager and we needed to keep track of more than one spend wallet on the same cipher seed. Trying to keep the indexes in sync causes massive performance issues accorss view wallets, offline singing etc. We can jut decryt the key and save it when we detect it.

Summary by CodeRabbit

  • Refactor

    • Simplified key index management by removing key chain searching and index updating logic.
    • Restricted special handling in key generation to only the PRE_MINE branch; all others now use random indices.
    • Recovered keys are now directly imported without searching for existing key indices.
  • Bug Fixes

    • Removed outdated tests and methods related to key index searching and updating.
  • Tests

    • Removed tests covering key index finding, updating, and cross-branch index consistency.

No user-facing features were added or removed.

@SWvheerden SWvheerden requested a review from a team as a code owner July 25, 2025 14:21
Copy link
Contributor

coderabbitai bot commented Jul 25, 2025

Walkthrough

This update removes all key index searching and updating logic from the key manager and transaction key manager modules. Several methods and their trait definitions for finding key indices, updating them, and retrieving spending key IDs are eliminated. Related tests are deleted, and the logic for output key recovery and next key generation is simplified, with special handling now only for the "PRE_MINE" branch.

Changes

File(s) Change Summary
.../transaction_key_manager/inner.rs Removed key index search/update logic, deleted several async methods, simplified get_next_key and try_output_key_recovery.
.../transaction_key_manager/interface.rs
.../key_manager_service/interface.rs
Removed trait methods for finding/updating key indices and getting spending key ID.
.../transaction_key_manager/wrapper.rs
.../key_manager_service/handle.rs
Removed corresponding async methods from trait implementations.
.../key_manager_service/service.rs Removed key index search/update methods and related constants/imports.
.../wallet/tests/key_manager_service_tests/service.rs Deleted three async tests covering key index finding, updating, and cross-branch index consistency.
.../wallet/tests/transaction_service_tests/service.rs Removed code and assertion related to spending key ID retrieval and comparison in a transaction burn test.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant TransactionKeyManager

    Client->>TransactionKeyManager: get_next_key(branch)
    alt branch == "PRE_MINE"
        TransactionKeyManager->>TransactionKeyManager: Increment key index
        TransactionKeyManager-->>Client: Return new key and ID
    else branch != "PRE_MINE"
        TransactionKeyManager->>TransactionKeyManager: Generate random key index
        TransactionKeyManager-->>Client: Return new key and ID
    end
Loading
sequenceDiagram
    participant Client
    participant TransactionKeyManager

    Client->>TransactionKeyManager: try_output_key_recovery(commitment, encrypted_data, custom_recovery_key_id)
    TransactionKeyManager->>TransactionKeyManager: Decrypt private key
    TransactionKeyManager->>TransactionKeyManager: Import private key (as imported key ID)
    TransactionKeyManager-->>Client: Return imported key ID, value, memo
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~18 minutes

Poem

In the warren of keys, old paths swept away,
No more do we search for the index or stray.
With PRE_MINE in mind and randomness anew,
The bunny hops forward, the logic now true.
Simpler the tunnels, less digging to do—
Oh, what a joy for this code-review crew!
🐇✨

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a 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 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.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (1)
base_layer/core/src/transactions/transaction_key_manager/inner.rs (1)

183-197: Consider documenting the indexing strategy.

The shift from sequential to random index generation (except for PRE_MINE) is a significant architectural change. Consider adding a comment explaining why PRE_MINE uses sequential indexing while others use random indices.

 pub async fn get_next_key(&self, branch: &str) -> Result<TariKeyAndId, KeyManagerServiceError> {
     let index = {
         match branch {
+            // PRE_MINE branch maintains sequential indexing for deterministic key generation
             PRE_MINE => {
                 let mut km = self
                     .key_managers
                     .get(branch)
                     .ok_or_else(|| self.unknown_key_branch_error("get_next_key", branch))?
                     .write()
                     .await;
                 self.db.increment_key_index(branch)?;
                 km.increment_key_index(1)
             },
+            // Other branches use random indices to avoid index synchronization overhead
             _ => OsRng.next_u64(),
         }
     };
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8809224 and 5294d90.

📒 Files selected for processing (8)
  • base_layer/core/src/transactions/transaction_key_manager/inner.rs (4 hunks)
  • base_layer/core/src/transactions/transaction_key_manager/interface.rs (0 hunks)
  • base_layer/core/src/transactions/transaction_key_manager/wrapper.rs (0 hunks)
  • base_layer/key_manager/src/key_manager_service/handle.rs (0 hunks)
  • base_layer/key_manager/src/key_manager_service/interface.rs (0 hunks)
  • base_layer/key_manager/src/key_manager_service/service.rs (0 hunks)
  • base_layer/wallet/tests/key_manager_service_tests/service.rs (0 hunks)
  • base_layer/wallet/tests/transaction_service_tests/service.rs (1 hunks)
💤 Files with no reviewable changes (6)
  • base_layer/wallet/tests/key_manager_service_tests/service.rs
  • base_layer/core/src/transactions/transaction_key_manager/wrapper.rs
  • base_layer/key_manager/src/key_manager_service/service.rs
  • base_layer/key_manager/src/key_manager_service/handle.rs
  • base_layer/core/src/transactions/transaction_key_manager/interface.rs
  • base_layer/key_manager/src/key_manager_service/interface.rs
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (8)
  • GitHub Check: ledger build tests
  • GitHub Check: test (mainnet, stagenet)
  • GitHub Check: ci
  • GitHub Check: test (nextnet, nextnet)
  • GitHub Check: cargo check with stable
  • GitHub Check: test (testnet, esmeralda)
  • GitHub Check: Cucumber tests / FFI
  • GitHub Check: Cucumber tests / Base Layer
🔇 Additional comments (3)
base_layer/wallet/tests/transaction_service_tests/service.rs (1)

1548-1548: LGTM! Test correctly adapted to API changes.

The destructuring pattern change properly adapts to the updated try_output_key_recovery method signature while maintaining the essential test functionality. The spending key ID is now intentionally ignored (with underscore prefix), which aligns with the PR objective to remove index tracking from the commitment mask index.

base_layer/core/src/transactions/transaction_key_manager/inner.rs (2)

1543-1563: Excellent optimization for output recovery!

The direct key import approach eliminates the expensive index search and update operations, which aligns perfectly with the PR's performance improvement goals. This is a much cleaner solution when the actual private key is already available from decryption.


183-197: Could not locate any explicit collision detection or duplicate‐index checks in the codebase. Since all non–PRE_MINE branches now use a random u64 for the key index (with no tracking in the DB or in memory), collisions—while astronomically unlikely—are neither checked nor guarded against. This change also makes it impossible to enumerate or replay‐derive non–PRE_MINE keys.

Please confirm that:

  • You accept relying on the statistical improbability of u64 collisions without explicit guards.
  • There are no wallet recovery or auditing features that expect sequential, trackable indices for non–PRE_MINE branches.
  • Key enumeration (e.g., for backups or key exports) is not required for these branches.

If any of the above is unacceptable, we should restore index tracking or introduce collision detection.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant