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

fix(avs): prevent BLS12-381 replay attacks #314

Merged
merged 14 commits into from
Feb 24, 2025

Conversation

trestinlsd
Copy link
Contributor

@trestinlsd trestinlsd commented Feb 21, 2025

Description


refactor: improve bls signature validation logic
test: add unit tests for BLS signature functionality
update the pre-compiled bls key registration interface parameters

Summary by CodeRabbit

  • New Features
    • Simplified the public key registration process by removing unnecessary parameters and updating naming conventions for clarity.
    • Added a new constant for improved organization of constants related to BLS signed messages.
  • Bug Fixes
    • Improved error handling and validation for public key registration, providing clearer error messages and preventing reuse of BLS keys across different operators and AVSs.
  • Tests
    • Introduced a new test to validate the registration of BLS public keys, enhancing overall test coverage.

Copy link
Contributor

coderabbitai bot commented Feb 21, 2025

Walkthrough

The pull request updates the BLS public key registration process by modifying the registerBLSPublicKey function's parameters for consistent casing and removing unnecessary parameters. The keeper function enhances validation logic by computing a new expected hash for the registration message. A new test case is added to ensure the updated registration flow works as intended.

Changes

File(s) Change Summary
precompiles/avs/IAVSManager.sol Updated registerBLSPublicKey: renamed parameters for consistent casing and removed two parameters.
precompiles/avs/tx.go Renamed BLS parameter fields (e.g., PubkeyRegistrationSignaturePubKeyRegistrationSignature) and removed PubkeyRegistrationMessageHash.
x/avs/keeper/keeper.go Enhanced RegisterBLSPublicKey with new validation logic for message format and hash consistency; renamed variable for clarity.
x/avs/keeper/avs_test.go Added new test function TestRegisterBLSPublicKey to verify the registration process.
x/avs/types/utils.go Renamed field PubkeyRegistrationSignature to PubKeyRegistrationSignature and removed PubkeyRegistrationMessageHash.
precompiles/avs/abi.json Updated parameters in registerBLSPublicKey: renamed pubkeyRegistrationSignature to pubKeyRegistrationSignature and removed pubkeyRegistrationMessageHash.
x/avs/types/types.go Added constant BLSMessageToSign and reorganized existing constants.

Possibly related PRs

Suggested labels

C:Proto, C:CLI, Type: Build, Type: Tests

Suggested reviewers

  • magj2006
  • adu-web3
  • cloud8little
  • MaxMustermann2
  • TimmyExogenous
  • leonz789
  • bwhour
  • mikebraver

Poem

I hopped through lines of code with glee,
Tweaking keys and tests for all to see.
New parameters and checks make me smile,
Like carrots along my coding mile.
A rabbit’s cheer for changes set right—
Hoppy commits sure brighten the night!

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

🪧 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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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.

@trestinlsd trestinlsd changed the title Fix issuse 304 refactor: improve bls signature validation logic(fix issuse 304) Feb 21, 2025
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 (5)
x/avs/keeper/keeper.go (3)

296-299: Favor Cosmos SDK error handling over fmt.Errorf.
Instead of returning a plain Go error, consider using errorsmod.Wrap or a similar Cosmos SDK error code to improve debugging and streamline handling in higher layers.

- return fmt.Errorf("invalid message format: %s", params.Message)
+ return errorsmod.Wrap(types.ErrInvalidInput, fmt.Sprintf("invalid message format: %s", params.Message))

300-307: Ensure msgHash is exactly 32 bytes before converting to [32]byte.
While this code is correct assuming the hash is always 32 bytes, adding a length check can safeguard against malformed input.

+ if len(msgHash) != 32 {
+     return errorsmod.Wrap(types.ErrInvalidHash, "PubKeyRegistrationMessageHash must be 32 bytes")
+ }
expectedHash := crypto.Keccak256Hash([]byte(expectedMessage))
if !bytes.Equal(msgHash, expectedHash.Bytes()) {
    ...
}

325-326: Grammar fix for the error message.
The error string has a minor grammatical issue.

- return errorsmod.Wrap(types.ErrAlreadyExists, fmt.Sprintf("the bls key is already exists:%s", blsInfo.PubKey))
+ return errorsmod.Wrap(types.ErrAlreadyExists, fmt.Sprintf("the BLS key already exists: %s", blsInfo.PubKey))
x/avs/keeper/avs_test.go (1)

202-222: Consider expanding test coverage.
The current test succeeds with matching fields. You could add negative tests (e.g., mismatched messages, invalid signatures) to confirm that the registration fails as expected.

precompiles/avs/IAVSManager.sol (1)

198-200: Documentation needs improvement.

The documentation for the parameters is not descriptive enough:

  • pubKeyRegistrationSignature is described as "the public keys of the operator" which is incorrect
  • pubKeyRegistrationMessageHash is described as "the public keys of the operator" which is incorrect

Apply this diff to improve the documentation:

-    /// @param pubKeyRegistrationSignature the public keys of the operator
-    /// @param pubKeyRegistrationMessageHash the public keys of the operator
-    /// @param msg is the message which signed using a private key
+    /// @param pubKeyRegistrationSignature the BLS signature of the registration message
+    /// @param pubKeyRegistrationMessageHash the hash of the registration message
+    /// @param msg the message that was signed using the private key
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 770a676 and 16b8823.

📒 Files selected for processing (5)
  • precompiles/avs/IAVSManager.sol (1 hunks)
  • precompiles/avs/tx.go (1 hunks)
  • x/avs/keeper/avs_test.go (2 hunks)
  • x/avs/keeper/keeper.go (2 hunks)
  • x/avs/types/utils.go (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: test-unit-cover
  • GitHub Check: test-unit-e2e
  • GitHub Check: Analyze (go)
  • GitHub Check: goreleaser
🔇 Additional comments (11)
x/avs/keeper/keeper.go (4)

291-295: Good documentation to prevent replay attacks.
This comment block clearly explains the usage of the Message parameter to avoid replay attacks by including chain ID and operator address in lowercase.


308-311: Confirm [32]byte conversion aligns with the BLS library requirements.
If msgHash is guaranteed to be 32 bytes, this invocation is valid. Otherwise, there could be a silent mismatch.


317-317: Struct naming clarity.
Renaming to blsInfo adds clarity by reflecting the purpose of this struct.


328-328: No issues found.
This return statement appropriately delegates to set the operator’s public key.

x/avs/types/utils.go (1)

45-47: Field naming improves consistency, and adding Message is beneficial.
Renaming PubkeyRegistrationSignaturePubKeyRegistrationSignature and PubkeyRegistrationMessageHashPubKeyRegistrationMessageHash aligns with standard casing. Including the Message field clarifies its role in preventing replay attacks.

x/avs/keeper/avs_test.go (1)

4-6: No concerns regarding new imports.

precompiles/avs/IAVSManager.sol (2)

201-208: LGTM! Parameter naming and structure improvements.

The changes improve consistency in parameter naming by standardizing the casing of pubKey across all parameters. The addition of the msg parameter enhances the registration process by providing the original message for signature verification.


205-207: LGTM! Parameter naming and structure changes look good.

The parameter names have been updated for consistency, and the new msg parameter has been added to provide additional data for signature validation.

precompiles/avs/tx.go (3)

325-329: LGTM! Robust parameter validation.

The implementation properly validates the new msg parameter and correctly assigns it to the blsParams structure. The error handling follows the established pattern used for other parameters.


317-318: LGTM! Field name changes look good.

The field names have been updated for consistency with the interface changes.

Also applies to: 323-324


325-329: LGTM! Parameter validation and field assignment look good.

The new msg parameter is properly validated and assigned to the Message field.

Copy link
Contributor

@MaxMustermann2 MaxMustermann2 left a comment

Choose a reason for hiding this comment

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

Minor changes requested for code cleanliness

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)
precompiles/avs/tx.go (1)

317-318: Fix formatting issue.

Remove the extra newline to comply with gofumpt formatting rules.

 	blsParams.PubKeyRegistrationSignature = pubKeyRegistrationSignature
-	
🧰 Tools
🪛 GitHub Check: Run golangci-lint

[failure] 318-318:
File is not gofumpt-ed (gofumpt)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 16b8823 and f0d8826.

📒 Files selected for processing (6)
  • precompiles/avs/IAVSManager.sol (1 hunks)
  • precompiles/avs/abi.json (1 hunks)
  • precompiles/avs/tx.go (1 hunks)
  • x/avs/keeper/avs_test.go (2 hunks)
  • x/avs/keeper/keeper.go (1 hunks)
  • x/avs/types/utils.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (4)
  • x/avs/types/utils.go
  • precompiles/avs/IAVSManager.sol
  • x/avs/keeper/keeper.go
  • x/avs/keeper/avs_test.go
🧰 Additional context used
🪛 GitHub Check: Run golangci-lint
precompiles/avs/tx.go

[failure] 318-318:
File is not gofumpt-ed (gofumpt)

⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: test-unit-e2e
  • GitHub Check: test-unit-cover
  • GitHub Check: goreleaser
  • GitHub Check: Analyze (go)
🔇 Additional comments (2)
precompiles/avs/tx.go (1)

284-328: LGTM! The changes align with the PR objectives.

The function has been successfully refactored to improve BLS signature validation logic by:

  • Removing the redundant PubkeyRegistrationMessageHash parameter
  • Updating field names for consistency with Go naming conventions
  • Maintaining robust parameter validation and error handling
🧰 Tools
🪛 GitHub Check: Run golangci-lint

[failure] 318-318:
File is not gofumpt-ed (gofumpt)

precompiles/avs/abi.json (1)

1017-1027: Ensure Consistency in BLS Registration Parameters.

The recent changes remove the extraneous "pubkeyRegistrationMessageHash" parameter and rename "pubkeyRegistrationSignature" to "pubKeyRegistrationSignature" to align with the updated interface. This adjustment looks correct—just verify that all calling contracts and related unit tests (e.g., in x/avs/keeper/avs_test.go) reflect these naming changes properly.

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)
x/avs/keeper/keeper.go (1)

289-319: LGTM! BLS signature validation logic is robust and secure.

The implementation effectively:

  1. Prevents replay attacks by including chain ID and operator address in the message
  2. Prevents rogue key attacks by validating BLS signatures
  3. Prevents key reuse by checking for duplicates

Consider adding a constant for the error message format string to improve maintainability.

Apply this diff to extract the error message format string:

+const (
+    ErrOperatorFormat = "the operator is :%s"
+)

 func (k Keeper) RegisterBLSPublicKey(ctx sdk.Context, params *types.BlsParams) error {
     // ...
-    return errorsmod.Wrap(types.ErrSigNotMatchPubKey, fmt.Sprintf("the operator is :%s", params.OperatorAddress))
+    return errorsmod.Wrap(types.ErrSigNotMatchPubKey, fmt.Sprintf(ErrOperatorFormat, params.OperatorAddress))
     // ...
-    return errorsmod.Wrap(types.ErrAlreadyExists, fmt.Sprintf("the operator is :%s", params.OperatorAddress))
+    return errorsmod.Wrap(types.ErrAlreadyExists, fmt.Sprintf(ErrOperatorFormat, params.OperatorAddress))
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1ec0e09 and 007dfb6.

📒 Files selected for processing (3)
  • x/avs/keeper/avs_test.go (6 hunks)
  • x/avs/keeper/keeper.go (1 hunks)
  • x/avs/types/types.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • x/avs/types/types.go
⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: test-unit-cover
  • GitHub Check: test-unit-e2e
  • GitHub Check: goreleaser
  • GitHub Check: docker-localnet-build
  • GitHub Check: docker-build
  • GitHub Check: Analyze (go)
🔇 Additional comments (4)
x/avs/keeper/avs_test.go (4)

217-233: LGTM! Test case for successful registration is well-structured.

The test case thoroughly validates the BLS public key registration flow by:

  1. Generating a random BLS key pair
  2. Formatting the message with chain ID and operator address
  3. Signing the message with the private key
  4. Verifying the signature

235-251: LGTM! Test case for wrong chain ID is comprehensive.

The test case effectively validates that the signature verification fails when using an incorrect chain ID, preventing replay attacks across different chains.


253-270: LGTM! Test case for wrong operator address is thorough.

The test case effectively validates that the signature verification fails when using a mismatched operator address, preventing impersonation attacks.


272-289: LGTM! Test case for mismatched BLS key is well-designed.

The test case effectively validates that the signature verification fails when using a mismatched BLS key pair, preventing rogue key attacks.

@MaxMustermann2 MaxMustermann2 changed the title refactor: improve bls signature validation logic(fix issuse 304) fix(avs): prevent BLS12-381 replay attacks Feb 21, 2025
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)
x/avs/keeper/avs_test.go (1)

206-307: Add test cases for additional edge cases.

The test suite is well-structured using table-driven tests. Consider adding the following test cases to improve coverage:

  1. Invalid public key format
  2. Invalid signature format
  3. Empty operator address
 testCases := []testCase{
+		{
+			name: "invalid public key format",
+			setupParams: func() *types.BlsParams {
+				operatorAddress := sdk.AccAddress(utiltx.GenerateAddress().Bytes())
+				return &types.BlsParams{
+					OperatorAddress: operatorAddress,
+					AvsAddress:     testutiltx.GenerateAddress(),
+					PubKey:         []byte("invalid"),
+				}
+			},
+			errorContains: "invalid public key format",
+		},
+		{
+			name: "invalid signature format",
+			setupParams: func() *types.BlsParams {
+				privateKey, err := blst.RandKey()
+				suite.NoError(err)
+				operatorAddress := sdk.AccAddress(utiltx.GenerateAddress().Bytes())
+				return &types.BlsParams{
+					OperatorAddress:             operatorAddress,
+					AvsAddress:                  testutiltx.GenerateAddress(),
+					PubKey:                      privateKey.PublicKey().Marshal(),
+					PubKeyRegistrationSignature: []byte("invalid"),
+				}
+			},
+			errorContains: "invalid signature format",
+		},
+		{
+			name: "empty operator address",
+			setupParams: func() *types.BlsParams {
+				privateKey, err := blst.RandKey()
+				suite.NoError(err)
+				return &types.BlsParams{
+					AvsAddress:                  testutiltx.GenerateAddress(),
+					PubKey:                      privateKey.PublicKey().Marshal(),
+					PubKeyRegistrationSignature: []byte{},
+				}
+			},
+			errorContains: "empty operator address",
+		},
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 007dfb6 and 511788b.

📒 Files selected for processing (1)
  • x/avs/keeper/avs_test.go (6 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: test-unit-e2e
  • GitHub Check: test-unit-cover
  • GitHub Check: goreleaser
  • GitHub Check: Analyze (go)
🔇 Additional comments (2)
x/avs/keeper/avs_test.go (2)

9-9: Update import path to remove organization prefix.

Remove the ExocoreNetwork prefix from the import path to maintain consistency.

-	testutiltx "github.com/ExocoreNetwork/exocore/testutil/tx"
+	testutiltx "github.com/exocore/testutil/tx"

82-155: LGTM! Improved error handling and test robustness.

The changes enhance error handling with proper nil checks and explicit action assignments.

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 (2)
x/avs/keeper/avs_test.go (1)

206-402: Enhance test coverage for BLS key registration.

The test cases are comprehensive and well-structured, covering key scenarios like successful registration, key reuse, and invalid signatures. Consider adding these additional test cases to further improve coverage:

  1. Test with empty AVS address
  2. Test with malformed BLS public key (not just invalid format)
  3. Test concurrent registrations
  4. Test with maximum/minimum sized inputs

Here's a template for additional test cases:

 testCases := []testCase{
+    {
+        name: "empty avs address",
+        setupParams: func() *types.BlsParams {
+            privateKey, err := blst.RandKey()
+            suite.NoError(err)
+            operatorAddress := sdk.AccAddress(utiltx.GenerateAddress().Bytes())
+            msg := fmt.Sprintf(types.BLSMessageToSign, types.ChainIDWithoutRevision(suite.Ctx.ChainID()), operatorAddress.String())
+            hashedMsg := crypto.Keccak256Hash([]byte(msg))
+            sig := privateKey.Sign(hashedMsg.Bytes())
+
+            return &types.BlsParams{
+                OperatorAddress:             operatorAddress,
+                AvsAddress:                  common.Address{},
+                PubKey:                      privateKey.PublicKey().Marshal(),
+                PubKeyRegistrationSignature: sig.Marshal(),
+            }
+        },
+        errorContains: "empty avs address",
+    },
x/avs/keeper/keeper.go (1)

300-303: Enhance error handling specificity.

The current error handling combines validation errors under ErrSigNotMatchPubKey. Consider creating specific error types for different validation failures:

  1. Invalid signature format
  2. Invalid public key format
  3. Signature verification failure

Example implementation:

 valid, err := blst.VerifySignature(sig, hashedMsg, pubKey)
 if err != nil || !valid {
-    return errorsmod.Wrap(types.ErrSigNotMatchPubKey, fmt.Sprintf("the operator is %s", params.OperatorAddress))
+    if err != nil {
+        return errorsmod.Wrap(types.ErrInvalidSignatureFormat, fmt.Sprintf("invalid signature format for operator %s: %v", params.OperatorAddress, err))
+    }
+    return errorsmod.Wrap(types.ErrSignatureVerificationFailed, fmt.Sprintf("signature verification failed for operator %s", params.OperatorAddress))
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 511788b and 6e25e16.

📒 Files selected for processing (2)
  • x/avs/keeper/avs_test.go (6 hunks)
  • x/avs/keeper/keeper.go (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: test-unit-e2e
  • GitHub Check: test-unit-cover
  • GitHub Check: goreleaser
  • GitHub Check: Analyze (go)
🔇 Additional comments (2)
x/avs/keeper/avs_test.go (1)

9-9: Update import path prefix.

The import path contains "ExocoreNetwork/exocore". Based on previous feedback, the "ExoCore-" prefix should be dropped.

x/avs/keeper/keeper.go (1)

291-297: Well-implemented replay attack prevention!

The changes effectively prevent replay attacks by:

  1. Using a templated message format
  2. Including chain-id and operator-address in the message
  3. Using Keccak256 for message hashing

This ensures that signatures are unique to this registration function and cannot be reused across different chains or operators.

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 (3)
x/avs/keeper/avs_test.go (1)

214-407: Consider adding more edge cases to strengthen test coverage.

While the current test cases are comprehensive, consider adding these scenarios:

  1. Zero-length public key
  2. Zero-length signature
  3. Invalid operator address format
  4. Maximum length values for inputs

Also, the test cases for reusing BLS keys (lines 234-293) effectively validate the prevention of key reuse, which is crucial for security. Good job on including these cases!

x/avs/keeper/keeper.go (2)

300-306: Enhance error messages with more specific details.

While the error handling is good, consider making the error messages more specific:

-		return errorsmod.Wrap(types.ErrParsePubKey, fmt.Sprintf("the operator is %s", params.OperatorAddress))
+		return errorsmod.Wrap(types.ErrParsePubKey, fmt.Sprintf("failed to parse BLS public key for operator %s: %v", params.OperatorAddress, err))
-		return errorsmod.Wrap(types.ErrSigNotMatchPubKey, fmt.Sprintf("the operator is %s", params.OperatorAddress))
+		return errorsmod.Wrap(types.ErrSigNotMatchPubKey, fmt.Sprintf("BLS signature verification failed for operator %s", params.OperatorAddress))

319-329: Add security rationale in comments.

The code effectively prevents BLS key reuse, but consider adding a comment explaining the security implications:

-	// verify that the BLS key is not already in use by
-	// (1) even the same operator on a different AVS
-	// (2) different operators on the same AVS
-	// this design decision is made to ensure that the same BLS key
-	// is not reused across different AVSs by the same operator
+	// Prevent BLS key reuse to mitigate several security risks:
+	// 1. Rogue key attacks where an attacker claims ownership of another's key
+	// 2. Cross-AVS replay attacks where signatures from one AVS could be reused in another
+	// 3. Key sharing between operators which could lead to collusion
+	// Therefore, we ensure each BLS key is unique across:
+	// - Different AVSs (even for the same operator)
+	// - Different operators (even within the same AVS)
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 6e25e16 and d9c5be2.

📒 Files selected for processing (3)
  • precompiles/avs/tx.go (1 hunks)
  • x/avs/keeper/avs_test.go (6 hunks)
  • x/avs/keeper/keeper.go (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • precompiles/avs/tx.go
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: test-unit-cover
  • GitHub Check: test-unit-e2e
  • GitHub Check: goreleaser
  • GitHub Check: Analyze (go)
🔇 Additional comments (3)
x/avs/keeper/avs_test.go (2)

9-9: Update import path to drop "ExoCore-" prefix.

The import path contains "ExocoreNetwork/exocore" which should be updated based on previous feedback.


207-212: Well-structured test function!

The test function follows best practices:

  • Uses table-driven tests for better organization
  • Each test case has a descriptive name
  • Setup is isolated per test case
  • Clear error expectations
x/avs/keeper/keeper.go (1)

291-297: Excellent security measures for preventing replay attacks!

The implementation effectively prevents replay attacks by:

  1. Including chain ID in the message
  2. Including operator address in the message
  3. Using a templated message format to ensure consistency

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)
x/avs/keeper/avs_test.go (1)

207-422: Excellent test coverage for BLS key registration!

The test cases thoroughly cover important security scenarios including:

  • Successful registration
  • Replay attack prevention
  • Chain ID validation
  • Signature verification
  • Public key format validation

Consider adding these edge cases:

  1. Empty AVS address validation
  2. Nil public key and signature handling
  3. Maximum length validation for public key and signature
 		{
+			name: "empty avs address",
+			setupParams: func() *types.BlsParams {
+				privateKey, err := blst.RandKey()
+				suite.NoError(err)
+				operatorAddress := sdk.AccAddress(utiltx.GenerateAddress().Bytes())
+				msg := fmt.Sprintf(types.BLSMessageToSign, types.ChainIDWithoutRevision(suite.Ctx.ChainID()), operatorAddress.String())
+				hashedMsg := crypto.Keccak256Hash([]byte(msg))
+				sig := privateKey.Sign(hashedMsg.Bytes())
+				return &types.BlsParams{
+					OperatorAddress:             operatorAddress,
+					AvsAddress:                  common.Address{},
+					PubKey:                      privateKey.PublicKey().Marshal(),
+					PubKeyRegistrationSignature: sig.Marshal(),
+				}
+			},
+			errorContains: types.ErrInvalidAddr.Error(),
+		},
+		{
+			name: "nil public key and signature",
+			setupParams: func() *types.BlsParams {
+				operatorAddress := sdk.AccAddress(utiltx.GenerateAddress().Bytes())
+				return &types.BlsParams{
+					OperatorAddress:             operatorAddress,
+					AvsAddress:                  testutiltx.GenerateAddress(),
+					PubKey:                      nil,
+					PubKeyRegistrationSignature: nil,
+				}
+			},
+			errorContains: types.ErrParsePubKey.Error(),
+		},
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d9c5be2 and 271d6d6.

📒 Files selected for processing (1)
  • x/avs/keeper/avs_test.go (6 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: test-unit-e2e
  • GitHub Check: test-unit-cover
  • GitHub Check: goreleaser
  • GitHub Check: Analyze (go)
🔇 Additional comments (2)
x/avs/keeper/avs_test.go (2)

9-9: Update import path to remove "ExocoreNetwork" prefix.

Based on previous review comments, the "ExocoreNetwork" prefix should be dropped from the import path.

-	testutiltx "github.com/ExocoreNetwork/exocore/testutil/tx"
+	testutiltx "github.com/exocore/testutil/tx"

86-86: LGTM! Action field assignments are consistent.

The changes to the Action field assignments in the test cases are consistent and maintain the test coverage for AVS registration and deregistration flows.

Also applies to: 118-118, 131-131, 147-147

Copy link
Contributor

@bwhour bwhour left a comment

Choose a reason for hiding this comment

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

the whole looks good.

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 (3)
x/avs/keeper/avs_test.go (1)

227-442: Well-structured test cases with comprehensive coverage.

The test cases thoroughly cover various scenarios including successful registration, key reuse, invalid signatures, and format validation. However, there are a few potential improvements:

  1. Consider adding a test case for empty AVS address
  2. The test message format could be moved to a constant for reusability

Consider adding this test case:

+		{
+			name: "empty avs address",
+			setupParams: func() *types.BlsParams {
+				privateKey, err := blst.RandKey()
+				suite.NoError(err)
+				operatorAddress := sdk.AccAddress(utiltx.GenerateAddress().Bytes())
+				msg := fmt.Sprintf(types.BLSMessageToSign, types.ChainIDWithoutRevision(suite.Ctx.ChainID()), operatorAddress.String())
+				hashedMsg := crypto.Keccak256Hash([]byte(msg))
+				sig := privateKey.Sign(hashedMsg.Bytes())
+
+				return &types.BlsParams{
+					OperatorAddress:             operatorAddress,
+					AvsAddress:                  common.Address{},
+					PubKey:                      privateKey.PublicKey().Marshal(),
+					PubKeyRegistrationSignature: sig.Marshal(),
+				}
+			},
+			errorContains: types.ErrInvalidAddr.Error(),
+		},
x/avs/keeper/keeper.go (2)

300-306: Improve error handling consistency.

While the error handling is generally good, the error messages could be more consistent. Consider using a consistent format for all error messages.

Apply this diff to make error messages more consistent:

-		return errorsmod.Wrap(types.ErrParsePubKey, fmt.Sprintf("the operator is %s", params.OperatorAddress))
+		return errorsmod.Wrap(types.ErrParsePubKey, fmt.Sprintf("failed to parse public key for operator: %s", params.OperatorAddress))
-		return errorsmod.Wrap(types.ErrSigNotMatchPubKey, fmt.Sprintf("the operator is %s", params.OperatorAddress))
+		return errorsmod.Wrap(types.ErrSigNotMatchPubKey, fmt.Sprintf("signature verification failed for operator: %s", params.OperatorAddress))

319-330: Strong security measures against key reuse.

The implementation effectively prevents BLS key reuse across different AVSs and operators. Consider adding validation for the AVS address to ensure it's not empty.

Add this validation at the start of the function:

func (k Keeper) RegisterBLSPublicKey(ctx sdk.Context, params *types.BlsParams) error {
+	if bytes.Equal(params.AvsAddress.Bytes(), common.Address{}.Bytes()) {
+		return errorsmod.Wrap(types.ErrInvalidAddr, "AVS address cannot be empty")
+	}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 271d6d6 and 841d289.

📒 Files selected for processing (4)
  • precompiles/avs/IAVSManager.sol (1 hunks)
  • precompiles/avs/tx.go (1 hunks)
  • x/avs/keeper/avs_test.go (6 hunks)
  • x/avs/keeper/keeper.go (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • precompiles/avs/IAVSManager.sol
  • precompiles/avs/tx.go
⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: test-unit-e2e
  • GitHub Check: test-unit-cover
  • GitHub Check: docker-build
  • GitHub Check: docker-localnet-build
  • GitHub Check: Analyze (go)
  • GitHub Check: goreleaser
🔇 Additional comments (2)
x/avs/keeper/avs_test.go (1)

100-100: LGTM! Action type references updated correctly.

The changes correctly update the action type references to use the types package.

Also applies to: 136-136, 149-149

x/avs/keeper/keeper.go (1)

291-297: Good security improvement for preventing replay attacks.

The templated message format effectively prevents replay attacks by including chain-id and operator-address. The comments clearly explain the security benefits.

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)
x/avs/keeper/avs_test.go (1)

222-437: Well-structured test suite with comprehensive coverage!

The test suite effectively covers various security scenarios including replay attacks, signature validation, and input validation. This aligns well with the PR's security objectives.

Consider these improvements to enhance maintainability:

  1. Extract repeated test values into constants
  2. Group related test cases using subtests
  3. Add verification of stored data in the successful case

Apply this diff to improve the test structure:

 func (suite *AVSTestSuite) TestRegisterBLSPublicKey() {
+    const (
+        invalidChainID = "onemorechain_211"
+        invalidBytes   = "invalid"
+    )
+
     type testCase struct {
         name          string
         setupParams   func() *types.BlsParams
         errorContains string
+        verifyState   func(*types.BlsParams)
     }
 
     testCases := []testCase{
         {
             name: "successful registration",
             setupParams: func() *types.BlsParams {
                 // ... existing setup code ...
             },
+            verifyState: func(params *types.BlsParams) {
+                // Verify the key was stored correctly
+                storedKey, err := suite.App.AVSManagerKeeper.GetBLSKey(
+                    suite.Ctx,
+                    params.OperatorAddress,
+                    params.AvsAddress,
+                )
+                suite.NoError(err)
+                suite.Equal(params.PubKey, storedKey)
+            },
         },
         // Group related test cases
+        {
+            name: "key reuse scenarios",
+            subtests: []testCase{
+                // Move key reuse test cases here
+            },
+        },
         // ... rest of the test cases ...
     }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 841d289 and 2a46eee.

📒 Files selected for processing (2)
  • precompiles/avs/query_test.go (1 hunks)
  • x/avs/keeper/avs_test.go (6 hunks)
✅ Files skipped from review due to trivial changes (1)
  • precompiles/avs/query_test.go
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: test-unit-e2e
  • GitHub Check: test-unit-cover
  • GitHub Check: goreleaser
  • GitHub Check: Analyze (go)
🔇 Additional comments (1)
x/avs/keeper/avs_test.go (1)

3-26: Clean up duplicate imports.

There are duplicate imports that need to be cleaned up:

  1. avstypes is imported but types is already imported
  2. utiltx from evmos is imported but testutiltx is already imported

@trestinlsd trestinlsd added this pull request to the merge queue Feb 24, 2025
Merged via the queue into imua-xyz:develop with commit 505516b Feb 24, 2025
22 checks passed
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.

BLS12-381 Replay Attacks
3 participants