Skip to content
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

docs(crypto): update docs #22247

Merged
merged 3 commits into from
Oct 14, 2024
Merged

docs(crypto): update docs #22247

merged 3 commits into from
Oct 14, 2024

Conversation

xujikks
Copy link
Contributor

@xujikks xujikks commented Oct 12, 2024

Description

Closes: #XXXX


Author Checklist

All items are required. Please add a note to the item if the item is not applicable and
please add links to any relevant follow up issues.

I have...

  • included the correct type prefix in the PR title, you can find examples of the prefixes below:
  • confirmed ! in the type prefix if API or client breaking change
  • targeted the correct branch (see PR Targeting)
  • provided a link to the relevant issue or specification
  • reviewed "Files changed" and left comments if necessary
  • included the necessary unit and integration tests
  • added a changelog entry to CHANGELOG.md
  • updated the relevant documentation or specification, including comments for documenting Go code
  • confirmed all CI checks have passed

Reviewers Checklist

All items are required. Please add a note if the item is not applicable and please add
your handle next to the items reviewed if you only reviewed selected items.

Please see Pull Request Reviewer section in the contributing guide for more information on how to review a pull request.

I have...

  • confirmed the correct type prefix in the PR title
  • confirmed all author checklist items have been addressed
  • reviewed state machine logic, API design and naming, documentation is accurate, tests and test coverage

Summary by CodeRabbit

  • New Features

    • Introduced functions for converting between JSON and protobuf public key formats.
    • Added a method to extract private keys from local records.
    • Enhanced Quad key handling with new methods for creating ranges based on Quad prefixes.
  • Bug Fixes

    • Enhanced error handling for private key extraction.
    • Improved robustness of JSON encoding and decoding for Quad keys.
  • Documentation

    • Improved comments and documentation for keyring methods to clarify functionality and parameters.

Copy link
Contributor

coderabbitai bot commented Oct 12, 2024

📝 Walkthrough
📝 Walkthrough

Walkthrough

The changes in this pull request introduce new functionality to the crypto package, specifically within the codec, hd, and keyring components. Key additions include two functions for converting public keys between JSON and protobuf formats, modifications to the key derivation process by removing an outdated dependency, enhancements to method documentation in the keyring package, and the introduction of a new function for extracting private keys from records.

Changes

File Path Change Summary
crypto/codec/pubkey.go Added functions PubKeyToProto and PubKeyFromProto for converting between JSON and protobuf public keys.
crypto/hd/hdpath.go Removed commented-out code related to tendermint/crypto/secp256k1 and updated comments regarding the use of btcec.
crypto/keyring/keyring.go Enhanced documentation for Sign, NewMnemonic, and MigrateAll methods; added convertFromLegacyInfo method.
crypto/keyring/record.go Introduced extractPrivKeyFromLocal function for extracting private keys, modified extractPrivKeyFromRecord to use it.
collections/quad.go Updated methods in quadKeyCodec for improved encoding/decoding and added new methods for creating Quad key ranges.

Possibly related PRs

  • docs(collections): add comments for funcs #22214: This PR adds comments for functions in collections/quad.go and collections/triple.go, which are relevant to the changes made in the main PR that introduces new functions in crypto/codec/pubkey.go. Both PRs involve enhancements to the functionality and documentation of key handling in the Cosmos SDK.

Suggested labels

C:collections

Suggested reviewers

  • julienrbrt
  • tac0turtle
  • akhilkumarpilli

📜 Recent review details

Configuration used: .coderabbit.yml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 25a9bb0 and fe3f060.

📒 Files selected for processing (2)
  • collections/quad.go (0 hunks)
  • crypto/hd/hdpath.go (1 hunks)
💤 Files with no reviewable changes (1)
  • collections/quad.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • crypto/hd/hdpath.go

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.

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: 1

🧹 Outside diff range and nitpick comments (6)
crypto/codec/pubkey.go (2)

Line range hint 14-38: LGTM with a minor suggestion for error handling

The PubKeyToProto function is well-implemented and follows good practices:

  • Clear and descriptive function name
  • Comprehensive documentation
  • Proper error handling for unsupported key types
  • Follows the Uber Go Style Guide

A minor suggestion to improve error handling:

Consider using a custom error type or error code for unsupported key types. This would make it easier for callers to programmatically handle this specific error case. For example:

var ErrUnsupportedKeyType = errors.Register(ModuleName, 2, "unsupported key type")

// In the default case of the switch statement
return nil, errors.Wrapf(ErrUnsupportedKeyType, "cannot convert %v to proto public key", pk)

This approach allows for more granular error handling while maintaining the context provided by errors.Wrapf.


Line range hint 41-69: LGTM with a minor suggestion for error handling

The PubKeyFromProto function is well-implemented and follows good practices:

  • Clear and descriptive function name
  • Comprehensive documentation
  • Proper error handling for unsupported key types
  • Follows the Uber Go Style Guide
  • Symmetric implementation to PubKeyToProto, which enhances consistency

A minor suggestion to improve error handling:

Similar to the suggestion for PubKeyToProto, consider using a custom error type or error code for unsupported key types. This would make it easier for callers to programmatically handle this specific error case. For example:

var ErrUnsupportedKeyType = errors.Register(ModuleName, 2, "unsupported key type")

// In the default case of the switch statement
return cryptokeys.JSONPubkey{}, errors.Wrapf(ErrUnsupportedKeyType, "cannot convert %v from proto public key", pk)

This approach allows for more granular error handling while maintaining the context provided by errors.Wrapf.

crypto/keyring/record.go (1)

Line range hint 131-150: LGTM with a minor suggestion for improvement

The new extractPrivKeyFromLocal function is well-implemented and documented. It correctly handles potential errors and follows good practices for private key extraction.

A minor suggestion for improvement:

Consider wrapping the ErrPrivKeyNotAvailable error with additional context. This can be done using errorsmod.Wrap:

 if rl.PrivKey == nil {
-    return nil, ErrPrivKeyNotAvailable
+    return nil, errorsmod.Wrap(ErrPrivKeyNotAvailable, "in extractPrivKeyFromLocal")
 }

This change would provide more context in error messages, potentially aiding in debugging.

crypto/keyring/keyring.go (3)

Line range hint 550-594: Well-implemented mnemonic generation with room for improvement.

The NewMnemonic function is well-structured and correctly implements mnemonic generation and account creation. The comprehensive comments are excellent. Consider wrapping the errors returned from bip39.NewEntropy and bip39.NewMnemonic with custom errors for better error handling and debugging.

Consider updating the error handling as follows:

 entropy, err := bip39.NewEntropy(defaultEntropySize)
 if err != nil {
-    return nil, "", err
+    return nil, "", errorsmod.Wrap(err, "failed to generate entropy")
 }

 mnemonic, err := bip39.NewMnemonic(entropy)
 if err != nil {
-    return nil, "", err
+    return nil, "", errorsmod.Wrap(err, "failed to generate mnemonic")
 }

Line range hint 734-831: Secure passphrase handling with room for improvement.

The newRealPrompt function implements secure passphrase handling using bcrypt for hashing. The logic for both new passphrase creation and existing passphrase verification is well-implemented.

However, there's a potential security concern:

The maxPassphraseEntryAttempts is defined as a package-level variable. Consider making it a configurable parameter to allow for different security policies in various contexts.

-var maxPassphraseEntryAttempts = 3
+
+func newRealPrompt(dir string, buf io.Reader, maxAttempts int) func(string) (string, error) {
+    if maxAttempts <= 0 {
+        maxAttempts = 3 // Default value
+    }
     return func(prompt string) (string, error) {
         // ... existing code ...
-        if failureCounter > maxPassphraseEntryAttempts {
+        if failureCounter > maxAttempts {
             return "", ErrMaxPassPhraseAttempts
         }
         // ... rest of the existing code ...
     }
 }

This change allows for more flexible security configurations while maintaining a sensible default.


Line range hint 932-960: Robust migration function with room for improvement in error reporting.

The MigrateAll function effectively migrates legacy key information to the new Record format. The use of sorting for consistent results is a good practice.

Consider aggregating errors instead of just printing them to stderr. This would provide a more comprehensive view of any issues encountered during migration. Here's a suggested improvement:

+import "go.uber.org/multierr"

 func (ks keystore) MigrateAll() ([]*Record, error) {
     // ... existing code ...
+    var errs error
     for _, key := range keys {
         // ... existing code ...
         rec, err := ks.migrate(key)
         if err != nil {
-            fmt.Fprintf(os.Stderr, "migrate err for key %s: %q\n", key, err)
+            errs = multierr.Append(errs, fmt.Errorf("migrate err for key %s: %w", key, err))
             continue
         }
         recs = append(recs, rec)
     }
-    return recs, nil
+    return recs, errs
 }

This change allows the caller to handle all migration errors comprehensively.

📜 Review details

Configuration used: .coderabbit.yml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 65ed5eb and 25a9bb0.

📒 Files selected for processing (4)
  • crypto/codec/pubkey.go (2 hunks)
  • crypto/hd/hdpath.go (1 hunks)
  • crypto/keyring/keyring.go (5 hunks)
  • crypto/keyring/record.go (1 hunks)
🧰 Additional context used
📓 Path-based instructions (4)
crypto/codec/pubkey.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

crypto/hd/hdpath.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

crypto/keyring/keyring.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

crypto/keyring/record.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

🔇 Additional comments (2)
crypto/keyring/record.go (1)

Line range hint 1-150: Request for additional context

The AI summary mentions modifications to the extractPrivKeyFromRecord function, but these changes are not visible in the provided code snippet. To provide a comprehensive review, I would need to see the actual changes made to this function.

Could you please provide the diff for the extractPrivKeyFromRecord function? This will allow me to review the changes and ensure they integrate well with the new extractPrivKeyFromLocal function.

crypto/keyring/keyring.go (1)

Line range hint 379-421: Well-documented and properly implemented signing function.

The Sign function is well-structured and correctly handles different key types (local, ledger, and multi/offline). The comprehensive comments explaining the function's purpose, parameters, and return values are particularly commendable.

Comment on lines 233 to 237
// By using btcec, we can remove the dependency on tendermint/crypto/secp256k1
// pubkey := secp256k1.PrivKeySecp256k1(privKeyBytes).PubKey()
// public := pubkey.(secp256k1.PubKeySecp256k1)
// data = public[:]

Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

Inconsistency Between Comment and Implementation

The comment mentions using btcec to remove the dependency on tendermint/crypto/secp256k1. However, the actual implementation still utilizes secp for public key derivation:

  • ecPub := secp.PrivKeyFromBytes(privKeyBytes[:]).PubKey()
  • pubkeyBytes := ecPub.SerializeCompressed()

Please update the implementation to use btcec as intended or revise the comment to accurately describe the current usage of secp.

🔗 Analysis chain

Clarify btcec usage and improve comment

The comment indicates that btcec is now being used to remove the dependency on tendermint/crypto/secp256k1, which is a good practice for reducing external dependencies. However, the actual implementation using btcec is not visible in this diff.

  1. Please clarify how btcec is being used in the current implementation.
  2. Consider improving the comment to explain the specific btcec functions or methods being used for public key derivation.
  3. Ensure that the comment accurately reflects the current implementation.

To verify the actual implementation, please run the following script:

This will help ensure that the comment accurately reflects the code and that btcec is being used as intended.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check the actual implementation of public key derivation using btcec

# Search for btcec usage in the file
echo "Searching for btcec usage in crypto/hd/hdpath.go:"
rg --type go -n 'btcec' crypto/hd/hdpath.go

# Search for public key derivation implementation
echo "\nSearching for public key derivation implementation:"
rg --type go -n 'PubKey|SerializeCompressed' crypto/hd/hdpath.go

Length of output: 656

@julienrbrt julienrbrt changed the title docs(crypto/): update docs docs(crypto): update docs Oct 13, 2024
@julienrbrt
Copy link
Member

Could you fix linting? (make lint-fix)

@sssf-jak
Copy link

Could you fix linting? (make lint-fix)

ok, I'll try it

@raynaudoe raynaudoe added the backport/v0.52.x PR scheduled for inclusion in the v0.52's next stable release label Oct 14, 2024
@raynaudoe raynaudoe added this pull request to the merge queue Oct 14, 2024
Merged via the queue into cosmos:main with commit 8c39f41 Oct 14, 2024
72 of 77 checks passed
mergify bot pushed a commit that referenced this pull request Oct 14, 2024
Co-authored-by: keke-ka <kkektkid@163.com>
(cherry picked from commit 8c39f41)

# Conflicts:
#	collections/quad.go
julienrbrt added a commit that referenced this pull request Oct 14, 2024
Co-authored-by: xujikks <xujikksjjfjf@163.com>
Co-authored-by: Julien Robert <julien@rbrt.fr>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
backport/v0.52.x PR scheduled for inclusion in the v0.52's next stable release C:collections
Projects
None yet
Development

Successfully merging this pull request may close these issues.

7 participants