Skip to content

fix: load private keys when loading a user identity#12

Merged
QuantumExplorer merged 1 commit into
masterfrom
fix/identity-private-key
Oct 21, 2024
Merged

fix: load private keys when loading a user identity#12
QuantumExplorer merged 1 commit into
masterfrom
fix/identity-private-key

Conversation

@pauldelucia
Copy link
Copy Markdown
Member

@pauldelucia pauldelucia commented Oct 21, 2024

Loading the private keys when adding a new user identity was not implemented

Summary by CodeRabbit

  • New Features

    • Enhanced identity loading functionality with improved error handling for user identities.
    • Updated user interface to clarify input expectations by changing "Key" to "Private Key."
    • Added buttons to fill identity fields with random data for testing purposes.
    • Improved loading status display to show elapsed time during the process.
  • Bug Fixes

    • Refined logic for removing keys to enhance safety and clarity.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Oct 21, 2024

Walkthrough

The changes in this pull request involve updates to the load_identity method in the AppContext implementation and modifications to the AddExistingIdentityScreen struct. The load_identity method now includes handling for keys_input, enhancing error handling and validation for user identities. In the UI component, the input field labels have been clarified, and methods for populating identity data with random values have been added. Overall, these modifications aim to improve functionality and user experience in identity management.

Changes

File Path Change Summary
src/platform/identity/load_identity.rs Updated load_identity method to include keys_input handling, enhanced error handling, and validation logic.
src/ui/identities/add_existing_identity_screen.rs Updated AddExistingIdentityScreen struct; modified render_keys_input label; refined key removal logic; added methods for random data population and enhanced loading status display.

Poem

🐇 In the meadow where identities bloom,
New keys are added, dispelling the gloom.
With labels clearer, and functions anew,
We hop through the changes, all fresh and true!
A sprinkle of random, a dash of delight,
In our code garden, everything feels right! 🌼


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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 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
Copy Markdown
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: 2

🧹 Outside diff range and nitpick comments (1)
src/ui/identities/add_existing_identity_screen.rs (1)

Line range hint 228-258: LGTM: Added methods for populating fields with random testnet data.

The fill_random_hpmn and fill_random_masternode methods are great additions for testing purposes. They allow quick population of fields with valid data from testnet nodes.

However, consider adding error handling in case the chosen node doesn't have all required fields. This would prevent potential panics or unexpected behavior.

Here's a suggestion for improving error handling in fill_random_hpmn:

fn fill_random_hpmn(&mut self) {
    if let Some(testnet_nodes) = &self.testnet_loaded_nodes {
        if let Some((name, hpmn)) = testnet_nodes.hp_masternodes.iter().choose(&mut thread_rng()) {
            self.identity_id_input = hpmn.protx_tx_hash.clone();
            self.identity_type = IdentityType::Evonode;
            self.alias_input = name.clone();
            self.voting_private_key_input = hpmn.voter.private_key.clone();
            self.owner_private_key_input = hpmn.owner.private_key.clone();
            self.payout_address_private_key_input = hpmn.payout.private_key.clone();
        } else {
            // Handle the case where no HPMN is available
            println!("No HPMN available in testnet nodes");
        }
    } else {
        // Handle the case where testnet nodes are not loaded
        println!("Testnet nodes not loaded");
    }
}

Apply similar changes to fill_random_masternode as well.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 7b175c8 and 0075bcf.

📒 Files selected for processing (2)
  • src/platform/identity/load_identity.rs (3 hunks)
  • src/ui/identities/add_existing_identity_screen.rs (1 hunks)
🧰 Additional context used
🔇 Additional comments (5)
src/ui/identities/add_existing_identity_screen.rs (2)

162-162: LGTM: Improved label clarity for key input.

The change from "Key" to "Private Key" enhances user understanding by clearly specifying the expected input type. This aligns well with the PR's objective of fixing private key loading.


Line range hint 270-346: LGTM: Enhanced UI with testing utilities and improved loading feedback.

The additions to the ui method are well-implemented and provide valuable improvements:

  1. The new buttons for filling random HPMN and Masternode data enhance testing efficiency.
  2. The enhanced loading status display provides better user feedback, showing elapsed time in a user-friendly format.

These changes align well with the PR's objectives and improve overall user experience.

src/platform/identity/load_identity.rs (3)

3-3: Approved: Importing PrivateKeyOnMainIdentity and PrivateKeyOnVoterIdentity

The imported variants are necessary for handling encrypted private keys associated with main and voter identities.


10-10: Approved: Importing IdentityGettersV0

Importing IdentityGettersV0 provides access to essential getter methods for identity operations.


30-30: Approved: Including keys_input in parameter destructuring

Adding keys_input to the input parameters allows the function to handle user identity keys effectively.

let key_id = i as u32;
let public_key = match identity.public_keys().get(&key_id) {
Some(key) => key,
None => return Err("No public key matching key id {key_id}".to_string()),
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Correct error messages to include actual key_id values

The error messages use {key_id} as a placeholder, but without variable interpolation, it will not display the actual key_id value.

Update the error messages using format! to properly include the key_id:

- None => return Err("No public key matching key id {key_id}".to_string()),
+ None => return Err(format!("No public key matching key ID {}", key_id)),

...

- return Err("Private key input length is 0 for key id {key_id}".to_string())
+ return Err(format!("Private key input length is 0 for key ID {}", key_id))

Also applies to: 131-131

Comment on lines +118 to +139
if identity_type == IdentityType::User {
for (i, private_key_input) in keys_input.into_iter().enumerate() {
let key_id = i as u32;
let public_key = match identity.public_keys().get(&key_id) {
Some(key) => key,
None => return Err("No public key matching key id {key_id}".to_string()),
};
let private_key_bytes = match verify_key_input(
private_key_input,
&public_key.key_type().to_string(),
)? {
Some(bytes) => bytes,
None => {
return Err("Private key input length is 0 for key id {key_id}".to_string())
}
};
encrypted_private_keys.insert(
(EncryptedPrivateKeyTarget::PrivateKeyOnMainIdentity, key_id),
(public_key.clone(), private_key_bytes),
);
}
}
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Ensure correct mapping between keys_input and identity public keys

The current implementation assumes that the key IDs are sequential and match the indices of keys_input. This may not always be the case if the identity has non-sequential or custom key IDs, leading to potential mismatches.

Consider modifying the code to explicitly map each provided private key to its corresponding key ID. This ensures accurate association between private keys and their respective public keys.

Proposed changes:

- for (i, private_key_input) in keys_input.into_iter().enumerate() {
-     let key_id = i as u32;
+ for (key_id_str, private_key_input) in keys_input {
+     let key_id = key_id_str.parse::<u32>().map_err(|e| format!("Invalid key ID: {}", e))?;
      let public_key = match identity.public_keys().get(&key_id) {
          Some(key) => key,
          None => return Err(format!("No public key matching key ID {}", key_id)),
      };
      let private_key_bytes = match verify_key_input(
          private_key_input,
          &public_key.key_type().to_string(),
      )? {
          Some(bytes) => bytes,
          None => {
-             return Err("Private key input length is 0 for key id {key_id}".to_string())
+             return Err(format!("Private key input length is 0 for key ID {}", key_id))
          }
      };
      encrypted_private_keys.insert(
          (EncryptedPrivateKeyTarget::PrivateKeyOnMainIdentity, key_id),
          (public_key.clone(), private_key_bytes),
      );
  }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if identity_type == IdentityType::User {
for (i, private_key_input) in keys_input.into_iter().enumerate() {
let key_id = i as u32;
let public_key = match identity.public_keys().get(&key_id) {
Some(key) => key,
None => return Err("No public key matching key id {key_id}".to_string()),
};
let private_key_bytes = match verify_key_input(
private_key_input,
&public_key.key_type().to_string(),
)? {
Some(bytes) => bytes,
None => {
return Err("Private key input length is 0 for key id {key_id}".to_string())
}
};
encrypted_private_keys.insert(
(EncryptedPrivateKeyTarget::PrivateKeyOnMainIdentity, key_id),
(public_key.clone(), private_key_bytes),
);
}
}
if identity_type == IdentityType::User {
for (key_id_str, private_key_input) in keys_input {
let key_id = key_id_str.parse::<u32>().map_err(|e| format!("Invalid key ID: {}", e))?;
let public_key = match identity.public_keys().get(&key_id) {
Some(key) => key,
None => return Err(format!("No public key matching key ID {}", key_id)),
};
let private_key_bytes = match verify_key_input(
private_key_input,
&public_key.key_type().to_string(),
)? {
Some(bytes) => bytes,
None => {
return Err(format!("Private key input length is 0 for key ID {}", key_id))
}
};
encrypted_private_keys.insert(
(EncryptedPrivateKeyTarget::PrivateKeyOnMainIdentity, key_id),
(public_key.clone(), private_key_bytes),
);
}
}

@QuantumExplorer QuantumExplorer merged commit 4a06d2f into master Oct 21, 2024
@coderabbitai coderabbitai Bot mentioned this pull request Oct 22, 2024
@pauldelucia pauldelucia deleted the fix/identity-private-key branch November 12, 2024 04:33
shumkov added a commit that referenced this pull request Apr 13, 2026
#12: Replace identities.as_ref().unwrap() with if-let-Some guard
  in the flush_inner identity top-level drops logging block.

#13: Fix 5 stale doc comments:
  - Module header: updated scope from "Phase 9b" to current coverage
    (core, asset_locks, contacts, profiles, payments)
  - flush_inner: says "writes core + identity subset + asset locks +
    contacts" instead of "only core"
  - write_identity_dashpay_subset: removed duplicate first line
  - test_load_returns_empty_changeset: removed "no-op" description

#14: Log dropped dashpay_profiles and dashpay_payments_overlay
  overlay fields in flush_inner for consistency with the
  platform_addresses and token_balances drop gates.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
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