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: apply comments from the c4 audits #132

Merged
merged 2 commits into from
Jan 22, 2025
Merged

fix: apply comments from the c4 audits #132

merged 2 commits into from
Jan 22, 2025

Conversation

beer-1
Copy link
Member

@beer-1 beer-1 commented Jan 22, 2025

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

Release Notes

  • New Features

    • Enhanced oracle vote validation and processing.
    • Introduced a new sentinel error for handling bridge configuration errors.
  • Bug Fixes

    • Added validation for bridge configurations during token deposit.
    • Tightened criteria for initiating withdrawals based on deposit success.
  • Chores

    • Refactored oracle-related utility functions.
    • Updated method signatures in several modules.

The release focuses on improving system reliability and error handling across multiple components of the blockchain infrastructure.

@beer-1 beer-1 requested a review from sh-cha January 22, 2025 05:13
@beer-1 beer-1 self-assigned this Jan 22, 2025
@beer-1 beer-1 requested a review from a team as a code owner January 22, 2025 05:13
Copy link

coderabbitai bot commented Jan 22, 2025

Walkthrough

The pull request introduces modifications across multiple files in the x/opchild and x/ophost modules, focusing on enhancing error handling, vote extension processing, and validation mechanisms. Changes include updates to oracle vote validation, token deposit processes, and bridge configuration checks. The modifications aim to improve the robustness of the system by adding more precise error handling and refining the logic for processing oracle-related operations.

Changes

File Change Summary
x/opchild/keeper/msg_server.go Modified FinalizeTokenDeposit method's conditional logic for withdrawal initiation
x/opchild/keeper/msg_server_test.go Replaced getSlinky with getConnect in test method
x/opchild/keeper/oracle.go Updated UpdateOracle method to store vote extension validation results
x/opchild/keeper/oracle_test.go Renamed getSlinky function to getConnect
x/opchild/keeper/validator.go Added enhanced error handling in validator retrieval methods
x/opchild/l2connect/aggregator.go Refactored GetOracleVotes method signature and logic
x/opchild/l2connect/utils.go Significant changes to ValidateVoteExtensions method
x/ophost/keeper/msg_server.go Added bridge configuration validation in InitiateTokenDeposit
x/ophost/types/error.go Introduced new ErrBridgeNotFound sentinel error
x/ophost/keeper/msg_server_test.go Added test for handling error when initiating deposit on non-existent bridge

Sequence Diagram

sequenceDiagram
    participant Client
    participant MsgServer
    participant OracleHandler
    participant Validator

    Client->>MsgServer: Initiate Token Deposit
    MsgServer->>MsgServer: Check Bridge Configuration
    alt Bridge Not Found
        MsgServer-->>Client: Return Bridge Not Found Error
    else Bridge Exists
        MsgServer->>OracleHandler: Process Deposit
        OracleHandler->>Validator: Validate Vote Extensions
        Validator-->>OracleHandler: Return Validated Votes
        OracleHandler-->>MsgServer: Confirm Deposit
        MsgServer-->>Client: Deposit Successful
    end
Loading

Poem

🐰 Hoppity hop, through code we leap,
Validations tight, no errors to keep
Bridges checked, votes now clear
Oracle's wisdom drawing near
CodeRabbit's magic makes systems bright! 🌟

✨ 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.

Copy link

codecov bot commented Jan 22, 2025

Codecov Report

Attention: Patch coverage is 50.00000% with 20 lines in your changes missing coverage. Please review.

Project coverage is 49.40%. Comparing base (7da22a7) to head (3957f84).
Report is 3 commits behind head on main.

Files with missing lines Patch % Lines
x/opchild/l2connect/utils.go 45.83% 12 Missing and 1 partial ⚠️
x/opchild/keeper/validator.go 0.00% 2 Missing and 2 partials ⚠️
x/ophost/keeper/msg_server.go 57.14% 1 Missing and 2 partials ⚠️
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main     #132      +/-   ##
==========================================
- Coverage   49.41%   49.40%   -0.01%     
==========================================
  Files          57       57              
  Lines        4256     4271      +15     
==========================================
+ Hits         2103     2110       +7     
- Misses       1720     1723       +3     
- Partials      433      438       +5     
Files with missing lines Coverage Δ
x/opchild/keeper/msg_server.go 57.86% <100.00%> (ø)
x/opchild/keeper/oracle.go 55.07% <100.00%> (ø)
x/opchild/l2connect/aggregator.go 61.76% <100.00%> (ø)
x/ophost/keeper/msg_server.go 56.41% <57.14%> (-0.20%) ⬇️
x/opchild/keeper/validator.go 64.13% <0.00%> (-3.65%) ⬇️
x/opchild/l2connect/utils.go 41.86% <45.83%> (+4.68%) ⬆️

Copy link

@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: 3

🧹 Nitpick comments (1)
x/opchild/keeper/oracle.go (1)

96-96: Maintain Code Consistency

Line 96:

There is an unnecessary blank line after the error check:

if err != nil {
	return err
}
-
prices, err := k.voteAggregator.AggregateOracleVotes(sdkCtx, votes)

Consider removing the extra blank line to maintain code consistency and readability.

Apply this diff:

if err != nil {
	return err
}
-prices, err := k.voteAggregator.AggregateOracleVotes(sdkCtx, votes)
+prices, err := k.voteAggregator.AggregateOracleVotes(sdkCtx, votes)
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8119243 and ed980d3.

📒 Files selected for processing (9)
  • x/opchild/keeper/msg_server.go (1 hunks)
  • x/opchild/keeper/msg_server_test.go (1 hunks)
  • x/opchild/keeper/oracle.go (1 hunks)
  • x/opchild/keeper/oracle_test.go (2 hunks)
  • x/opchild/keeper/validator.go (2 hunks)
  • x/opchild/l2connect/aggregator.go (1 hunks)
  • x/opchild/l2connect/utils.go (5 hunks)
  • x/ophost/keeper/msg_server.go (1 hunks)
  • x/ophost/types/error.go (1 hunks)
🧰 Additional context used
🪛 GitHub Check: codecov/patch
x/opchild/keeper/validator.go

[warning] 21-21: x/opchild/keeper/validator.go#L21
Added line #L21 was not covered by tests


[warning] 42-42: x/opchild/keeper/validator.go#L42
Added line #L42 was not covered by tests

x/opchild/l2connect/utils.go

[warning] 46-46: x/opchild/l2connect/utils.go#L46
Added line #L46 was not covered by tests


[warning] 57-58: x/opchild/l2connect/utils.go#L57-L58
Added lines #L57 - L58 were not covered by tests


[warning] 70-70: x/opchild/l2connect/utils.go#L70
Added line #L70 was not covered by tests


[warning] 75-75: x/opchild/l2connect/utils.go#L75
Added line #L75 was not covered by tests


[warning] 80-80: x/opchild/l2connect/utils.go#L80
Added line #L80 was not covered by tests


[warning] 93-93: x/opchild/l2connect/utils.go#L93
Added line #L93 was not covered by tests


[warning] 98-98: x/opchild/l2connect/utils.go#L98
Added line #L98 was not covered by tests


[warning] 110-110: x/opchild/l2connect/utils.go#L110
Added line #L110 was not covered by tests


[warning] 114-114: x/opchild/l2connect/utils.go#L114
Added line #L114 was not covered by tests


[warning] 123-123: x/opchild/l2connect/utils.go#L123
Added line #L123 was not covered by tests


[warning] 128-128: x/opchild/l2connect/utils.go#L128
Added line #L128 was not covered by tests

x/ophost/keeper/msg_server.go

[warning] 230-230: x/ophost/keeper/msg_server.go#L230
Added line #L230 was not covered by tests


[warning] 232-233: x/ophost/keeper/msg_server.go#L232-L233
Added lines #L232 - L233 were not covered by tests

🔇 Additional comments (12)
x/ophost/types/error.go (1)

24-24: LGTM! Well-structured error definition.

The new error ErrBridgeNotFound follows the established pattern and uses an appropriate error code.

x/opchild/l2connect/utils.go (4)

49-51: Initialize Variables for Accurate Vote Processing

Initializing totalVP, seenValidators, and validVotes enhances clarity and prepares for accurate vote processing.

Lines 49-51:

totalVP = totalBondedTokens.Int64()
seenValidators := make(map[string]bool)
validVotes := make([]cometabci.ExtendedVoteInfo, 0, len(extCommit.Votes))

This setup is appropriate for maintaining state during vote validation.


56-61: Prevent Duplicate Votes from Validators

The logic to prevent duplicate votes ensures each validator's vote is counted only once.

Lines 56-61:

if strAddr := valConsAddr.String(); seenValidators[strAddr] {
	// ignore duplicate votes
	continue
} else {
	seenValidators[strAddr] = true
}

This prevents potential double-counting and enhances the integrity of the voting process.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 57-58: x/opchild/l2connect/utils.go#L57-L58
Added lines #L57 - L58 were not covered by tests


117-118: Accumulate Valid Votes and Voting Power

Collecting valid votes and summing their voting power are crucial steps.

Lines 117-118:

validVotes = append(validVotes, vote)
sumVP += power.Int64()

This implementation correctly prepares the data for the super-majority check.


134-134: Return Validated Votes

Line 134:

return validVotes, nil

Returning the slice of validated votes aligns with the updated function signature and enables further processing downstream.

x/opchild/l2connect/aggregator.go (1)

23-26: Update Function Signature and Logic in GetOracleVotes

The function GetOracleVotes now accepts extendedVotes []cometabci.ExtendedVoteInfo instead of extendedCommitInfo cometabci.ExtendedCommitInfo.

Lines 23-26:

func GetOracleVotes(
	veCodec connectcodec.VoteExtensionCodec,
	extendedVotes []cometabci.ExtendedVoteInfo,
) ([]connectaggregator.Vote, error) {
	votes := make([]connectaggregator.Vote, len(extendedVotes))
	for i, voteInfo := range extendedVotes {

This change ensures compatibility with the updated return value of ValidateVoteExtensions and correctly processes the votes. The loop and decoding logic have been appropriately adjusted.

x/opchild/keeper/oracle.go (2)

87-88: Capture extendedVotes from ValidateVoteExtensions

Lines 87-88:

extendedVotes, err := l2connect.ValidateVoteExtensions(sdkCtx, k.HostValidatorStore, h-1, hostChainID, extendedCommitInfo)
if err != nil {
	return err
}

By capturing extendedVotes, the code now utilizes the validated votes returned by ValidateVoteExtensions, which is essential for subsequent processing.


92-94: Pass extendedVotes to GetOracleVotes

Lines 92-94:

votes, err := l2connect.GetOracleVotes(k.veCodec, extendedVotes)
if err != nil {
	return err
}

Updating the parameter to extendedVotes aligns with the updated function signature of GetOracleVotes, ensuring consistency and correct data flow.

x/opchild/keeper/validator.go (1)

41-42: Add test coverage for panic scenarios in GetValidatorByConsAddr.

Similar to GetValidator, this critical error path needs test coverage to ensure proper handling of unexpected errors.

Run this script to verify test coverage:

✅ Verification successful

The review comment is correct - panic scenario needs test coverage

The test file x/opchild/keeper/validator_test.go contains a Test_GetValidatorByConsAddr function that covers the happy path and "not found" scenarios, but lacks coverage for the panic path when unexpected errors occur. This matches the pattern used in GetValidator where similar error handling exists.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check test coverage for GetValidatorByConsAddr panic scenario
rg -A 5 'func TestGetValidatorByConsAddr'

Length of output: 43


Script:

#!/bin/bash
# Find the implementation of GetValidatorByConsAddr
ast-grep --pattern 'func ($_ *$_) GetValidatorByConsAddr($_) $_'

# Find any test files that might contain tests for this function
fd -e go -E vendor test

# Look for similar panic scenario tests in the codebase
rg -g '**/*_test.go' -B 2 -A 5 'panic\('

Length of output: 2161


Script:

#!/bin/bash
# Check the implementation in validator.go
cat x/opchild/keeper/validator.go

# Check the test file
cat x/opchild/keeper/validator_test.go

# Look for any GetValidatorByConsAddr tests with different naming patterns
rg -g 'validator_test.go' 'ByConsAddr'

Length of output: 10464

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 42-42: x/opchild/keeper/validator.go#L42
Added line #L42 was not covered by tests

x/opchild/keeper/msg_server.go (1)

463-463: LGTM! Improved withdrawal condition logic.

The condition for initiating withdrawals has been tightened to only trigger when both deposit and hook have failed AND the coin amount is positive. This is a security improvement that prevents unnecessary withdrawals.

x/opchild/keeper/oracle_test.go (1)

53-53: LGTM! Function rename maintains functionality.

The function rename from getSlinky to getConnect is consistent with the codebase changes while preserving the test logic.

x/opchild/keeper/msg_server_test.go (1)

658-658: LGTM! Consistent function rename.

The update to use getConnect instead of getSlinky maintains consistency with the changes in oracle_test.go.

x/ophost/keeper/msg_server.go Show resolved Hide resolved
x/opchild/l2connect/utils.go Show resolved Hide resolved
x/opchild/keeper/validator.go Show resolved Hide resolved
Copy link
Contributor

@sh-cha sh-cha left a comment

Choose a reason for hiding this comment

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

LGTM

Copy link

@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/ophost/keeper/msg_server_test.go (1)

183-189: LGTM! Consider enhancing the error assertion.

The test case effectively verifies error handling for non-existent bridges. To improve clarity, consider asserting the specific error type.

-	require.Error(t, err)
+	require.ErrorIs(t, err, types.ErrBridgeNotFound)
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between ed980d3 and 3957f84.

📒 Files selected for processing (1)
  • x/ophost/keeper/msg_server_test.go (1 hunks)

@sh-cha sh-cha merged commit bb31a38 into main Jan 22, 2025
9 checks passed
@sh-cha sh-cha deleted the fix/audit branch January 22, 2025 08:43
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants