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: Module account address documentation #22289

Merged
merged 9 commits into from
Nov 4, 2024

Conversation

ziscky
Copy link
Contributor

@ziscky ziscky commented Oct 16, 2024

Description

Closes: #9916


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
    • Added a section on "Module Accounts" detailing their characteristics and address generation.
    • Expanded the "Public Keys" section to clarify definitions and serialization formats.
    • Elaborated on the "Keyring" section, including methods for signing messages and creating new accounts.
    • Introduced a new subsection on creating a new key type, with an example for the secp256r1 algorithm.

@julienrbrt julienrbrt changed the title feat(docs): Module account address documentation docs: Module account address documentation Oct 16, 2024
Copy link
Contributor

coderabbitai bot commented Oct 31, 2024

📝 Walkthrough

Walkthrough

The pull request introduces significant updates to the 03-accounts.md documentation, adding new sections on "Module Accounts," "Public Keys," and "Keyring," along with detailed subsections on address generation and creating new key types. It clarifies the process of deterministic account address generation, public key definitions, and the Keyring interface, including methods for signing messages and creating accounts. An example implementation for the secp256r1 algorithm is also included, enhancing the document's comprehensiveness regarding account management and key handling in the Cosmos SDK.

Changes

Files Change Summary
docs/learn/beginner/03-accounts.md - Added new section: "Module Accounts"
- Added subsection: "Address Generation" under "Module Accounts"
- Added new section: "Public Keys"
- Added new section: "Keyring"
- Added subsection: "Create New Key Type"
- Included example implementation for secp256r1

Assessment against linked issues

Objective Addressed Explanation
Update documentation with section about address generation (#[9916])

Possibly related PRs

  • docs(x/accounts): init of the x/accounts module docs. #22099: This PR enhances the documentation for the x/accounts module, which is directly related to the changes made in the main PR regarding account management and the introduction of new account types.
  • docs(x/accounts): fix doc #22295: This PR also focuses on improving the documentation for the x/accounts module, detailing the creation and management of accounts, which aligns with the updates made in the main PR about account handling and key types.

Suggested labels

C:x/accounts, Type: ADR

Suggested reviewers

  • tac0turtle
  • sontrinh16
  • julienrbrt
  • akhilkumarpilli

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.

@ziscky ziscky marked this pull request as ready for review October 31, 2024 13:38
@ziscky ziscky requested a review from a team as a code owner October 31, 2024 13:38
@ziscky ziscky requested a review from julienrbrt October 31, 2024 13:38

# Module Accounts

## Address Generation
Copy link
Member

Choose a reason for hiding this comment

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

That's a bit short for it to be in a dedicated page maybe. Having it in building modules is as well weird. Maybe an advanced concept?

@ziscky ziscky requested a review from julienrbrt November 4, 2024 10:51
@julienrbrt
Copy link
Member

Don't we have a page on accounts? If so let's add that content there maybe. Having a dedicated page is still weird.

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 (3)
docs/learn/beginner/03-accounts.md (3)

Line range hint 115-156: Add examples to clarify public key formats

The Public Keys section would benefit from concrete examples showing:

  1. Actual compressed public key format
  2. JSON representation of different key types
  3. How to work with the cryptotypes.PubKey interface

Consider adding examples like:

 This prefix is followed by the `x`-coordinate.
+
+For example, a secp256k1 public key might look like:
+```text
+// Compressed public key (hex)
+0x02a1633cafcc01ebfb6d78e39f687a1f0995c62fc95f51ead10a02ee0be551b5dc
+
+// JSON representation
+{
+  "@type": "/cosmos.crypto.secp256k1.PubKey",
+  "key": "AiFjPK/MAev7bXjjn2h6H5ZVxi/JX1Hq0QoC7gvlUbXc"
+}
+```

Line range hint 157-385: Enhance the secp256r1 implementation example

The secp256r1 implementation example would benefit from:

  1. Error handling best practices
  2. Comments explaining the cryptographic operations
  3. Security considerations

Consider enhancing the example:

 // NewPrivKeyFromSecret creates a private key derived for the secret number
 // represented in big-endian. The `secret` must be a valid ECDSA field element.
 func NewPrivKeyFromSecret(secret []byte) (*PrivKey, error) {
+    // Validate input
+    if len(secret) == 0 {
+        return nil, errorsmod.Wrap(errors.ErrInvalidRequest, "secret cannot be empty")
+    }
+
     var d = new(big.Int).SetBytes(secret)
     if d.Cmp(secp256r1.Params().N) >= 1 {
         return nil, errorsmod.Wrap(errors.ErrInvalidRequest, "secret not in the curve base field")
     }
+
+    // Initialize private key with proper security parameters
     sk := new(ecdsa.PrivKey)
     return &PrivKey{&ecdsaSK{*sk}}, nil
 }

Also consider adding a security note:

+// Security Note: This implementation assumes proper entropy in the input secret.
+// In production, always ensure the secret comes from a cryptographically secure
+// random number generator.
 func (s secp256r1Algo) Generate() GenerateFn {

107-113: Update code references to use tagged versions

The code references use specific commit hashes which may become outdated. Consider:

  1. Using tagged version references instead of commit hashes
  2. Adding more context around code examples
  3. Ensuring links are versioned consistently

Update the references to use tagged versions:

-https://github.com/cosmos/cosmos-sdk/blob/3a03804c148d0da8d6df1ad839b08c50f6896fa1/simapp/app.go#L130-L141
+https://github.com/cosmos/cosmos-sdk/blob/v0.52.0-beta.2/simapp/app.go#L130-L141
📜 Review details

Configuration used: .coderabbit.yml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 62a4e54 and 0f1d89b.

📒 Files selected for processing (1)
  • docs/learn/beginner/03-accounts.md (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
docs/learn/beginner/03-accounts.md (1)

Pattern **/*.md: "Assess the documentation for misspellings, grammatical errors, missing documentation and correctness"

Comment on lines 98 to 114

### Module Accounts

#### Address Generation

Module account addresses are generated deterministically from the module name, as defined in [ADR-028](../../architecture/adr-028-public-key-addresses.md)

Definition of account permissions is done during the app initialization.

```go reference
https://github.com/cosmos/cosmos-sdk/blob/3a03804c148d0da8d6df1ad839b08c50f6896fa1/simapp/app.go#L130-L141
```

```go reference
https://github.com/cosmos/cosmos-sdk/blob/3a03804c148d0da8d6df1ad839b08c50f6896fa1/simapp/app.go#L328
```

Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Enhance the Module Accounts section with more details

The Module Accounts section needs improvement in the following areas:

  1. Add explanation of what module accounts are and their purpose
  2. Provide specific examples of module account address generation
  3. Explain the permissions system and its implications
  4. Add context for the code references to help readers understand their purpose

Consider adding content like this before the code references:

 ### Module Accounts
+
+Module accounts are special-purpose accounts for modules to perform specific operations. Unlike regular accounts, they are controlled by the module's logic rather than private keys.
+
 #### Address Generation
 
-Module account addresses are generated deterministically from the module name, as defined in [ADR-028](../../architecture/adr-028-public-key-addresses.md) 
+Module account addresses are generated deterministically from the module name, as defined in [ADR-028](../../architecture/adr-028-public-key-addresses.md). For example, if a module is named "mint", its address would be derived using:
+```go
+authtypes.NewModuleAddress("mint")
+```
+
+This ensures that module accounts have consistent addresses across all chains using the same module name.
 
-Definition of account permissions is done during the app initialization.
+Module accounts can be granted specific permissions during app initialization. These permissions control what operations the module can perform, such as minting tokens or sending tokens to accounts.

@@ -95,6 +95,23 @@ https://github.com/cosmos/cosmos-sdk/blob/v0.52.0-beta.2/codec/address/bech32_co
| Validator Operator | cosmosvaloper |
| Consensus Nodes | cosmosvalcons |


### Module Accounts

Copy link
Member

Choose a reason for hiding this comment

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

let's have an intro on module accounts as well

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

🧹 Outside diff range and nitpick comments (3)
docs/learn/beginner/03-accounts.md (3)

101-102: Enhance the module accounts introduction with more technical details.

While the introduction provides a good overview, it would be beneficial to add:

  1. Explanation of how module accounts differ from regular accounts in terms of capabilities
  2. Common use cases and examples of module accounts (e.g., fee collector, bonded tokens pool)
  3. Security implications of module accounts

Line range hint 118-157: Add practical examples of public key usage.

The section would benefit from:

  1. Code examples showing how to work with different public key types
  2. Examples of public key serialization and deserialization
  3. Common use cases and best practices

Example addition:

 Public Keys are not used to reference accounts (or users) and in general are not used when composing transaction messages (with a few exceptions: `MsgCreateValidator`, `Validator` and `Multisig` messages).
+
+Here's an example of working with a secp256k1 public key:
+
+```go
+// Example of creating and serializing a public key
+pubKey := secp256k1.GenPrivKey().PubKey()
+pubKeyBytes := pubKey.Bytes()
+
+// Example of deserializing a public key
+recoveredPubKey := secp256k1.PubKey{
+    Key: pubKeyBytes,
+}
+```

Line range hint 159-385: Add security considerations for key implementation.

The secp256r1 implementation example should include:

  1. Security considerations when implementing new key types
  2. Best practices for key generation and storage
  3. Common pitfalls to avoid

Example addition:

 Finally, the algo must be added to the list of [supported algos](https://github.com/cosmos/cosmos-sdk/blob/v0.52.0-beta.2/crypto/keyring/keyring.go#L209) by the keyring.
+
+### Security Considerations
+
+When implementing a new key type:
+- Ensure the key generation uses a cryptographically secure random number generator
+- Implement proper key encryption at rest
+- Validate all inputs to prevent potential cryptographic weaknesses
+- Consider side-channel attacks in the implementation
+- Follow the principle of least privilege when exposing key operations
📜 Review details

Configuration used: .coderabbit.yml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 0f1d89b and 73865eb.

📒 Files selected for processing (1)
  • docs/learn/beginner/03-accounts.md (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
docs/learn/beginner/03-accounts.md (1)

Pattern **/*.md: "Assess the documentation for misspellings, grammatical errors, missing documentation and correctness"

Comment on lines +106 to +108
Module account addresses are generated deterministically from the module name, as defined in [ADR-028](../../architecture/adr-028-public-key-addresses.md)

Definition of account permissions is done during the app initialization.
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add practical examples of module account address generation.

The documentation should include:

  1. Concrete examples of how module account addresses are generated
  2. The specific format and structure of the generated addresses
  3. Example code showing how to generate and validate module account addresses

Example addition:

 Module account addresses are generated deterministically from the module name, as defined in [ADR-028](../../architecture/adr-028-public-key-addresses.md) 
+
+For example, to generate a module account address for the "mint" module:
+```go
+mintModuleAddr := authtypes.NewModuleAddress("mint")
+fmt.Printf("Mint module address: %s\n", mintModuleAddr)
+```
+
+Common module account names include:
+- "fee_collector": Collects transaction fees
+- "distribution": Handles reward distribution
+- "bonded_tokens_pool": Manages staked tokens
+- "not_bonded_tokens_pool": Manages unstaked tokens

Comment on lines +110 to +116
```go reference
https://github.com/cosmos/cosmos-sdk/blob/3a03804c148d0da8d6df1ad839b08c50f6896fa1/simapp/app.go#L130-L141
```

```go reference
https://github.com/cosmos/cosmos-sdk/blob/3a03804c148d0da8d6df1ad839b08c50f6896fa1/simapp/app.go#L328
```
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add context to code references.

The code references need explanatory text to help readers understand:

  1. What these code snippets demonstrate
  2. How they relate to module account initialization
  3. The significance of the permissions being set

Example addition:

+The following code demonstrates how module accounts are initialized in a Cosmos SDK application:
+
 ```go reference
 https://github.com/cosmos/cosmos-sdk/blob/3a03804c148d0da8d6df1ad839b08c50f6896fa1/simapp/app.go#L130-L141

+This initialization process:
+1. Creates module accounts with specific names
+2. Assigns appropriate permissions to each module account
+3. Registers the accounts in the auth keeper


<!-- This is an auto-generated comment by CodeRabbit -->

@julienrbrt julienrbrt added the backport/v0.52.x PR scheduled for inclusion in the v0.52's next stable release label Nov 4, 2024
@julienrbrt julienrbrt added this pull request to the merge queue Nov 4, 2024
Merged via the queue into main with commit 3ba4661 Nov 4, 2024
75 of 76 checks passed
@julienrbrt julienrbrt deleted the ziscky/9916-module-adress-gen-docs branch November 4, 2024 16:17
mergify bot pushed a commit that referenced this pull request Nov 4, 2024
julienrbrt pushed a commit that referenced this pull request Nov 4, 2024
Co-authored-by: Eric Mokaya <4112301+ziscky@users.noreply.github.com>
alpe added a commit that referenced this pull request Nov 6, 2024
* main: (24 commits)
  build(deps): upgrade to iavl@v1.3.1 (#22436)
  docs: Update tendermint validators query pagination documentation (#22412)
  refactor(client/v2): offchain uses client/v2/factory (#22344)
  feat: wire new handlers to grpc (#22333)
  fix(x/group): proper address rendering in error (#22425)
  refactor(serevr/v2/cometbft): update `RegisterQueryHandlers` and GRPC queries (#22403)
  docs: update ADR 59 (#22423)
  build(deps): Bump github.com/fsnotify/fsnotify from 1.7.0 to 1.8.0 in /tools/cosmovisor (#22407)
  docs: Module account address documentation (#22289)
  feat(baseapp): add per message telemetry (#22175)
  docs: Update Twitter Links to X in Documentation (#22408)
  docs: redirect the remote generation page (#22404)
  refactor(serverv2): remove unused interface methods, honuor context  (#22394)
  fix(server/v2): return ErrHelp (#22399)
  feat(indexer): implement `schema.HasModuleCodec` interface in the `bank` module (#22349)
  refactor(math): refactor ApproxRoot for readality (#22263)
  docs: fix KWallet Handbook (#22395)
  feat(client/v2): broadcast logic (#22282)
  refactor(server/v2): eager config loading (#22267)
  test(system): check feePayers signature (#22389)
  ...
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
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Update building a module documentation with section about address generation
4 participants