Skip to content

Conversation

@Benzbeeb
Copy link
Collaborator

@Benzbeeb Benzbeeb commented Aug 4, 2025

…tests

  • Removed unused dependency on github.com/BurntSushi/toml from go.mod and go.sum.
  • Renamed validation functions for clarity: IsValidDNS to ValidateDNS, IsValidPeerOrSeed to ValidatePeerOrSeed, IsValidInteger to ValidateInteger, IsValidAddress to ValidateAddress, and IsValidAddresses to ValidateAddresses.
  • Introduced new validation functions: ValidateAnyHexAddressOrAddress and ValidateAddressesOrHexAddresses for improved address validation.
  • Added unit tests for hex address validation in a new test file bech32_test.go.

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
  • provided a link to the relevant issue or specification
  • reviewed "Files changed" and left comments if necessary
  • included the necessary unit and integration tests
  • 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.

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 support for entering addresses as either standard Bech32 or hex-encoded public keys, with automatic conversion to Bech32 format where needed.
    • Introduced validation for single and multiple addresses that accept both Bech32 and hex formats.
    • Added a function to convert hex-encoded public keys to Bech32 addresses.
  • Refactor

    • Standardized naming conventions for validation functions across the app.
  • Tests

    • Added tests for new address validation and conversion features.
  • Chores

    • Removed an unused dependency.

…tests

- Removed unused dependency on github.com/BurntSushi/toml from go.mod and go.sum.
- Renamed validation functions for clarity: IsValidDNS to ValidateDNS, IsValidPeerOrSeed to ValidatePeerOrSeed, IsValidInteger to ValidateInteger, IsValidAddress to ValidateAddress, and IsValidAddresses to ValidateAddresses.
- Introduced new validation functions: ValidateAnyHexAddressOrAddress and ValidateAddressesOrHexAddresses for improved address validation.
- Added unit tests for hex address validation in a new test file bech32_test.go.
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 4, 2025

Walkthrough

The changes standardize validation function naming from IsValid* to Validate*, add new validators for hex and Bech32 addresses, and enhance address handling in the minitia launch process to support hex-encoded public keys. New tests cover these validators, and a utility for converting hex public keys to Bech32 addresses is introduced.

Changes

Cohort / File(s) Change Summary
Validation Function Refactor & Enhancements
common/validate.go, models/opinit_bots/init.go, models/initia/run_l1_node.go
Renamed all IsValid* validators to Validate*, updated all usages. Added ValidateAnyHexAddressOrAddress and ValidateAddressesOrHexAddresses for hex/Bech32 address validation.
Validator Tests
common/validate_test.go
Added tests for new address validation functions, covering valid/invalid hex and Bech32 address scenarios.
Bech32 Address Conversion Utility
crypto/bech32.go, crypto/bech32_test.go
Added PubKeyToBech32Address to convert hex public keys to Bech32 addresses and corresponding tests. Introduced InitHRP constant.
minitia Launch Address Handling
models/minitia/launch.go
Updated input validators to accept hex public keys or Bech32 addresses. Added logic to convert hex addresses to Bech32 during genesis account and fee whitelist processing.
Dependency Cleanup
go.mod
Removed unused github.com/BurntSushi/toml dependency.

Sequence Diagram(s)

Hex Public Key to Bech32 Address Conversion in Genesis Account Handling

sequenceDiagram
    participant User
    participant InputValidator
    participant GenesisAccountHandler
    participant Bech32Converter

    User->>InputValidator: Enter address (hex or Bech32)
    InputValidator->>GenesisAccountHandler: Pass validated address
    GenesisAccountHandler->>GenesisAccountHandler: Check if address starts with "0x"
    alt Address is hex
        GenesisAccountHandler->>Bech32Converter: Convert hex to Bech32
        Bech32Converter-->>GenesisAccountHandler: Return Bech32 address
    end
    GenesisAccountHandler->>State: Store Bech32 address
Loading

Fee Whitelist Handling with Mixed Address Formats

sequenceDiagram
    participant User
    participant InputValidator
    participant FeeWhitelistHandler
    participant Bech32Converter

    User->>InputValidator: Enter comma-separated addresses (hex/Bech32)
    InputValidator->>FeeWhitelistHandler: Pass validated addresses
    loop For each address
        FeeWhitelistHandler->>FeeWhitelistHandler: Check if address starts with "0x"
        alt Address is hex
            FeeWhitelistHandler->>Bech32Converter: Convert hex to Bech32
            Bech32Converter-->>FeeWhitelistHandler: Return Bech32 address
        end
        FeeWhitelistHandler->>Map: Store Bech32 address
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~40 minutes

Poem

🐇
A hop and a skip, new checks in the code,
Hex and Bech32 now share the same road.
Addresses convert with a magical twist,
Validators renamed—none have been missed!
With tests in the meadow and bugs on the run,
This patch makes address handling fun!
🌱✨

Note

⚡️ Unit Test Generation is now available in beta!

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


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e47a647 and 867772c.

📒 Files selected for processing (1)
  • crypto/bech32.go (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • crypto/bech32.go
⏰ 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). (1)
  • GitHub Check: Run Integration Tests on Ubuntu
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch validate-hex-address

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

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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

🔭 Outside diff range comments (1)
common/validate_test.go (1)

209-209: Update test expectation to match the refined error handling.

The pipeline failure indicates that the error message expectation in the "missing port" test case needs to be updated to match the refined error handling in ValidateURLWithPort.

Based on the pipeline failure, the expected error message should be changed:

		{
			name:    "missing port",
			url:     "http://example.com",
			wantErr: true,
-			errMsg:  "URL must include a port number",
+			errMsg:  "invalid port number: must be between 1 and 65535",
		},

This aligns with the change in Line 209 of common/validate.go where the error handling was refined to allow "missing port in address" errors to pass through to the port validation logic.

🧹 Nitpick comments (4)
crypto/bech32.go (1)

110-149: Consider adding input length validation.

The function correctly handles the core conversion logic, but could benefit from stricter input validation to prevent potential issues with malformed inputs.

Consider adding validation for expected public key lengths:

 func PubKeyToBech32Address(pubKeyHex string) (string, error) {
 	// Remove "0x" prefix if present
 	pubKeyHex = strings.TrimPrefix(pubKeyHex, "0x")
 
 	// Decode the hex string to bytes
 	pubKeyBytes, err := hex.DecodeString(pubKeyHex)
 	if err != nil {
 		return "", fmt.Errorf("failed to decode hex string: %w", err)
 	}
+
+	// Validate input length
+	if len(pubKeyBytes) != 20 && len(pubKeyBytes) != 33 && len(pubKeyBytes) != 65 {
+		return "", fmt.Errorf("invalid input length: expected 20 (address hash), 33 (compressed pubkey), or 65 (uncompressed pubkey) bytes, got %d", len(pubKeyBytes))
+	}
 
 	// Check if the input is already a 20-byte hash (RIPEMD160)
 	var addressHash []byte
crypto/bech32_test.go (1)

9-73: Remove unused hrp field from test struct.

The test struct includes an hrp field that is never used since PubKeyToBech32Address doesn't accept an HRP parameter. The function uses a hardcoded HRP internally.

 func TestPubKeyToBech32Address(t *testing.T) {
 	tests := []struct {
 		name      string
 		pubKeyHex string
-		hrp       string
 		expected  string
 		expectErr bool
 	}{
 		{
 			name:      "Valid init address with 0x prefix (1)",
 			pubKeyHex: "0x932d1475bbad306322a839238d56fe5dc9184744",
-			hrp:       "init",
 			expected:  "init1jvk3gadm45cxxg4g8y3c64h7thy3s36yat0ezy",
 		},
 		{
 			name:      "Valid init address without 0x prefix (2)",
 			pubKeyHex: "0x552bfcf61b41b22eab0a520b896b072a1cd22b8c",
-			hrp:       "init",
 			expected:  "init1254leasmgxeza2c22g9cj6c89gwdy2uvwv05qu",
 		},
 		{
 			name:      "Valid init address without 0x prefix",
 			pubKeyHex: "932d1475bbad306322a839238d56fe5dc9184744",
-			hrp:       "init",
 			expected:  "init1jvk3gadm45cxxg4g8y3c64h7thy3s36yat0ezy",
 		},
 		{
 			name:      "Valid init capital address with 0x prefix ",
 			pubKeyHex: "0x932D1475BBAD306322A839238D56FE5DC9184744",
-			hrp:       "init",
 			expected:  "init1jvk3gadm45cxxg4g8y3c64h7thy3s36yat0ezy",
 		},
 		{
 			name:      "Invalid init address with 0x prefix",
 			pubKeyHex: "0x932D1475BBAD306322A839238D56FE5DC91847441",
-			hrp:       "init",
 			expectErr: true,
 		},
 		{
 			name:      "Invalid init address without 0x prefix",
 			pubKeyHex: "932D1475BBAD306322A839238D56FE5DC91847441",
-			hrp:       "init",
 			expectErr: true,
 		},
 		{
 			name:      "Invalid init address",
 			pubKeyHex: "invalid",
-			hrp:       "init",
 			expectErr: true,
 		},
 	}

Otherwise, the test coverage is comprehensive and well-structured, covering valid hex addresses with different formats and invalid inputs.

common/validate_test.go (1)

226-257: Rename test function to match the function being tested.

The test function TestValidateHexAddress is actually testing ValidateAnyHexAddressOrAddress, which is misleading.

-func TestValidateHexAddress(t *testing.T) {
+func TestValidateAnyHexAddressOrAddress(t *testing.T) {

Also update the error message in line 253:

-				t.Errorf("IsValidHexAddress() %s error = %v, wantErr %v", tt.name, err, tt.wantErr)
+				t.Errorf("ValidateAnyHexAddressOrAddress() %s error = %v, wantErr %v", tt.name, err, tt.wantErr)

The test coverage itself looks good with valid and invalid hex address cases.

common/validate.go (1)

229-229: Consider standardizing ValidateDNS return type for consistency.

While the function was renamed from IsValidDNS to ValidateDNS to follow the naming convention, it still returns bool instead of error like other Validate* functions. This creates inconsistency in the validation API.

Consider updating the function signature and implementation:

-func ValidateDNS(dns string) bool {
+func ValidateDNS(dns string) error {
 	// Regular expression for validating DNS names
 	dnsRegex := `^([a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$`
 	re := regexp.MustCompile(dnsRegex)
 
-	// Validate DNS name
-	return re.MatchString(dns)
+	if !re.MatchString(dns) {
+		return fmt.Errorf("invalid DNS name: %s", dns)
+	}
+	return nil
 }

And update the usage in line 285:

-		if net.ParseIP(host) == nil && !ValidateDNS(host) {
+		if net.ParseIP(host) == nil && ValidateDNS(host) != nil {
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0293c98 and f18c449.

⛔ Files ignored due to path filters (1)
  • go.sum is excluded by !**/*.sum
📒 Files selected for processing (8)
  • common/validate.go (8 hunks)
  • common/validate_test.go (1 hunks)
  • crypto/bech32.go (3 hunks)
  • crypto/bech32_test.go (1 hunks)
  • go.mod (0 hunks)
  • models/initia/run_l1_node.go (3 hunks)
  • models/minitia/launch.go (5 hunks)
  • models/opinit_bots/init.go (1 hunks)
💤 Files with no reviewable changes (1)
  • go.mod
🧰 Additional context used
🧬 Code Graph Analysis (4)
models/opinit_bots/init.go (1)
common/validate.go (1)
  • ValidateInteger (323-332)
crypto/bech32_test.go (1)
crypto/bech32.go (1)
  • PubKeyToBech32Address (111-149)
common/validate_test.go (1)
common/validate.go (2)
  • ValidateAnyHexAddressOrAddress (361-376)
  • ValidateAddressesOrHexAddresses (378-386)
models/initia/run_l1_node.go (1)
common/validate.go (1)
  • ValidatePeerOrSeed (241-305)
🪛 GitHub Actions: Basic Checks
common/validate_test.go

[error] 217-217: TestValidateURLWithPort/missing_port failed: Expected error message to contain 'URL must include a port number' but got 'invalid port number: must be between 1 and 65535'.

⏰ 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). (2)
  • GitHub Check: Run Integration Tests on Ubuntu
  • GitHub Check: Analyze (go)
🔇 Additional comments (18)
crypto/bech32.go (1)

20-20: LGTM!

The InitHRP constant is well-named and follows the established pattern for Bech32 human-readable prefixes in the Cosmos ecosystem.

models/opinit_bots/init.go (1)

1030-1030: LGTM!

The function name change from IsValidInteger to ValidateInteger aligns with the standardization effort mentioned in the PR objectives. The validation logic remains unchanged and is appropriate for validating L1 start height input.

models/initia/run_l1_node.go (3)

583-583: LGTM! Function renaming correctly applied.

The update from common.IsValidPeerOrSeed to common.ValidatePeerOrSeed is consistent with the validation function standardization effort in this PR.


651-651: LGTM! Function renaming correctly applied.

The update from common.IsValidPeerOrSeed to common.ValidatePeerOrSeed is consistent with the validation function standardization effort in this PR.


1689-1689: LGTM! Function renaming correctly applied.

The update from common.IsValidPeerOrSeed to common.ValidatePeerOrSeed is consistent with the validation function standardization effort in this PR.

common/validate_test.go (1)

259-290: LGTM! Comprehensive test coverage for multiple address validation.

The test cases properly cover comma-separated hex addresses, mixed address types, and invalid addresses.

common/validate.go (7)

209-209: LGTM! Refined error handling for missing port scenario.

The change correctly allows "missing port in address" errors to pass through to port validation logic, ensuring appropriate error messages are returned.


241-241: LGTM! Function renaming correctly applied.

The update from IsValidPeerOrSeed to ValidatePeerOrSeed is consistent with the validation function standardization effort.


285-285: LGTM! Updated function call matches renaming.

The call correctly uses the renamed ValidateDNS function.


323-323: LGTM! Function renaming correctly applied.

The update from IsValidInteger to ValidateInteger is consistent with the validation function standardization effort.


334-334: LGTM! Function renaming correctly applied.

The update from IsValidAddress to ValidateAddress is consistent with the validation function standardization effort.


344-350: LGTM! Function renaming correctly applied.

The update from IsValidAddresses to ValidateAddresses and the internal call to ValidateAddress are consistent with the validation function standardization effort.


361-386: LGTM! Well-implemented new validation functions.

The new functions ValidateAnyHexAddressOrAddress and ValidateAddressesOrHexAddresses properly extend address validation to support both hex-prefixed and Bech32 addresses. The implementation correctly:

  1. Validates hex addresses using crypto.PubKeyToBech32Address
  2. Validates Bech32 addresses using existing ValidateAddress
  3. Provides clear error messages for invalid formats
  4. Handles comma-separated lists appropriately

These functions integrate well with the existing validation framework.

models/minitia/launch.go (5)

25-25: LGTM!

The crypto package import is correctly added and properly positioned within the local imports section.


2119-2129: LGTM! Hex address conversion is properly implemented.

The implementation correctly:

  • Checks for hex prefix "0x"
  • Converts hex public keys to Bech32 addresses
  • Preserves the original address for display
  • Handles errors appropriately

3087-3098: LGTM! Fee whitelist hex address handling is consistent.

The implementation properly:

  • Converts hex addresses to Bech32 format before processing
  • Uses a cache to prevent duplicate addresses
  • Maintains consistency with the genesis account address handling

2048-2048: ValidateAnyHexAddressOrAddress implementation verified

The function in common/validate.go (lines 361–376) correctly handles both “0x”-prefixed hex addresses (via PubKeyToBech32Address) and Bech32 addresses (via ValidateAddress), returning an error for any other format. No issues found.


1993-1993: Validation logic confirmed

The ValidateAddressesOrHexAddresses function correctly splits on commas and validates each segment as either a hex or Bech32 address. The implementation in common/validate.go and the accompanying tests in common/validate_test.go cover mixed formats and invalid entries, so no further changes are needed.

coderabbitai[bot]
coderabbitai bot previously approved these changes Aug 4, 2025
coderabbitai[bot]
coderabbitai bot previously approved these changes Aug 4, 2025
coderabbitai[bot]
coderabbitai bot previously approved these changes Aug 4, 2025
- Updated the PubKeyToBech32Address function to include padding for odd-length hex strings.
- Introduced a new helper function, getPaddedBytes, to manage padding logic.
- Revised test cases in bech32_test.go to cover additional valid and invalid address scenarios, removing unnecessary hrp parameters.
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

🧹 Nitpick comments (1)
crypto/bech32.go (1)

20-20: Consider making HRP configurable for module addresses.

The hardcoded InitHRP constant works for the current use case, but consider making it configurable to support different address types like module addresses mentioned in previous reviews.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 17d142d and e47a647.

📒 Files selected for processing (2)
  • crypto/bech32.go (3 hunks)
  • crypto/bech32_test.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • crypto/bech32_test.go
⏰ 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). (1)
  • GitHub Check: Run Integration Tests on Ubuntu
🔇 Additional comments (2)
crypto/bech32.go (2)

5-5: LGTM!

The encoding/hex import is correctly added and needed for the new hex decoding functionality.


110-144: Well-structured function with good error handling.

The function correctly handles hex decoding, padding, and Bech32 encoding. The error handling is comprehensive and the logic flow is clear.

songwongtp
songwongtp previously approved these changes Aug 7, 2025
Copy link
Collaborator

@WasinWatt WasinWatt left a comment

Choose a reason for hiding this comment

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

tested, all good

@WasinWatt WasinWatt merged commit 4be02b3 into main Aug 7, 2025
8 checks passed
@WasinWatt WasinWatt deleted the validate-hex-address branch August 7, 2025 06:38
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.

3 participants