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(accounts): lockup check sender in context not in message #23621

Merged
merged 10 commits into from
Feb 6, 2025

Conversation

tac0turtle
Copy link
Member

@tac0turtle tac0turtle commented Feb 6, 2025

Description

The lockup accounts were not following the design of the accounts module instead like the sdk.


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

  • Refactor
    • Streamlined account transaction processing by automating the identification of the initiating account, eliminating the need for explicit sender details.
  • Bug Fixes
    • Improved transaction response handling by ensuring that all operations now return a correctly encoded response.
  • Tests
    • Enhanced test coverage to verify that unauthorized actions are properly blocked, reinforcing the integrity of account transactions.

Copy link
Contributor

coderabbitai bot commented Feb 6, 2025

📝 Walkthrough

Walkthrough

The changes remove the Sender field and its associated logic from multiple message types across various API, proto, and test files. The modifications update methods to retrieve the sender from the context rather than the message, adjust method signatures, and simplify validations. In addition, new test cases have been added to cover unauthorized coin sending. The overall changes affect both functional logic and integration tests without altering the primary transaction flows.

Changes

File(s) Change Summary
api/cosmos/accounts/defaults/lockup/v1/tx.pulsar.go Removed Sender field and associated getter/setter methods from the messages: MsgDelegate, MsgUndelegate, MsgWithdrawReward, and MsgSend.
x/accounts/defaults/lockup/lockup.go Replaced direct msg.Sender access with accountstd.Sender(ctx); updated checkSender to accept a []byte and added a print statement in SendCoins.
x/accounts/msg_server.go Added a return statement in the Execute method to return a v1.MsgExecuteResponse.
x/accounts/proto/cosmos/accounts/defaults/lockup/v1/tx.proto Removed the option (cosmos.msg.v1.signer) and sender field (of scalar type cosmos.AddressString) from the messages: MsgDelegate, MsgUndelegate, MsgWithdrawReward, and MsgSend.
Test Files (continuous_locking_account_test.go, delayed_locking_account_test.go, periodic_locking_account_test.go, permanent_locking_account_test.go, and integration test suites in tests/integration/v2/accounts/lockup/) Removed the Sender field from message instances; updated test setups (e.g., changing hardcoded "owner" string and adding new helper newMockContext2); added a new test TestPeriodicAccountSendCoinsUnauthorized to validate unauthorized access.
x/accounts/defaults/lockup/utils_test.go Updated the newMockContext function to use []byte("owner") instead of []byte("sender").

Sequence Diagram(s)

sequenceDiagram
    participant Client as Unauthorized Sender ("hacker")
    participant Context as Account Context
    participant Server as Lockup Account Server

    Client->>Context: Create mock context with "hacker"
    Client->>Server: Initiate SendCoins operation
    Server->>Server: Retrieve sender via accountstd.Sender(ctx)
    alt Sender unauthorized
        Server-->>Client: Return error response
    else
        Server-->>Client: Process transaction (not applicable here)
    end
Loading

Possibly related PRs

Suggested reviewers

  • sontrinh16
  • testinginprod
  • julienrbrt
  • akhilkumarpilli

Tip

🌐 Web search-backed reviews and chat
  • We have enabled web search-based reviews and chat for all users. This feature allows CodeRabbit to access the latest documentation and information on the web.
  • You can disable this feature by setting web_search: false in the knowledge_base settings.
  • Please share any feedback in the Discord discussion.
✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

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

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.

@tac0turtle tac0turtle marked this pull request as ready for review February 6, 2025 11:40
@tac0turtle tac0turtle requested a review from a team as a code owner February 6, 2025 11:40
Copy link
Contributor

github-actions bot commented Feb 6, 2025

@tac0turtle your pull request is missing a changelog!

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

🧹 Nitpick comments (2)
x/accounts/defaults/lockup/periodic_locking_account_test.go (1)

255-275: Optimize the query handler in newMockContext2.

The query handler contains a switch statement with only a default case, which can be simplified.

Consider simplifying the query handler:

-		}, func(ctx context.Context, req transaction.Msg) (transaction.Msg, error) {
-			typeUrl := sdk.MsgTypeURL(req)
-			switch typeUrl {
-			default:
-				return nil, errors.New("unrecognized request type")
-			}
+		}, func(ctx context.Context, req transaction.Msg) (transaction.Msg, error) {
+			return nil, errors.New("unrecognized request type")
🧰 Tools
🪛 golangci-lint (1.62.2)

269-269: singleCaseSwitch: found switch with default case only

(gocritic)

x/accounts/defaults/lockup/lockup.go (1)

333-333: Remove redundant Error() call in error wrapping.

The Error() call is redundant when wrapping an error, as the error message is already included.

-return sdkerrors.ErrInvalidAddress.Wrapf("invalid owner address: %s", err.Error())
+return sdkerrors.ErrInvalidAddress.Wrapf("invalid owner address: %s", err)
📜 Review details

Configuration used: .coderabbit.yml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7e39195 and fc30bfc.

⛔ Files ignored due to path filters (1)
  • x/accounts/defaults/lockup/v1/tx.pb.go is excluded by !**/*.pb.go
📒 Files selected for processing (10)
  • api/cosmos/accounts/defaults/lockup/v1/tx.pulsar.go (1 hunks)
  • x/accounts/defaults/lockup/continuous_locking_account_test.go (0 hunks)
  • x/accounts/defaults/lockup/delayed_locking_account_test.go (0 hunks)
  • x/accounts/defaults/lockup/lockup.go (6 hunks)
  • x/accounts/defaults/lockup/periodic_locking_account_test.go (2 hunks)
  • x/accounts/defaults/lockup/permanent_locking_account_test.go (0 hunks)
  • x/accounts/defaults/lockup/utils_test.go (1 hunks)
  • x/accounts/msg_server.go (1 hunks)
  • x/accounts/msg_server_test.go (1 hunks)
  • x/accounts/proto/cosmos/accounts/defaults/lockup/v1/tx.proto (0 hunks)
💤 Files with no reviewable changes (4)
  • x/accounts/defaults/lockup/delayed_locking_account_test.go
  • x/accounts/defaults/lockup/permanent_locking_account_test.go
  • x/accounts/defaults/lockup/continuous_locking_account_test.go
  • x/accounts/proto/cosmos/accounts/defaults/lockup/v1/tx.proto
🧰 Additional context used
📓 Path-based instructions (2)
`**/*.go`: Review the Golang code for conformity with the Ub...

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

  • x/accounts/defaults/lockup/utils_test.go
  • x/accounts/msg_server_test.go
  • x/accounts/defaults/lockup/periodic_locking_account_test.go
  • x/accounts/msg_server.go
  • x/accounts/defaults/lockup/lockup.go
  • api/cosmos/accounts/defaults/lockup/v1/tx.pulsar.go
`**/*_test.go`: "Assess the unit test code assessing suffici...

**/*_test.go: "Assess the unit test code assessing sufficient code coverage for the changes associated in the pull request"

  • x/accounts/defaults/lockup/utils_test.go
  • x/accounts/msg_server_test.go
  • x/accounts/defaults/lockup/periodic_locking_account_test.go
🪛 golangci-lint (1.62.2)
x/accounts/defaults/lockup/periodic_locking_account_test.go

269-269: singleCaseSwitch: found switch with default case only

(gocritic)

⏰ Context from checks skipped due to timeout of 90000ms (8)
  • GitHub Check: tests (03)
  • GitHub Check: tests (02)
  • GitHub Check: tests (01)
  • GitHub Check: tests (00)
  • GitHub Check: test-system-v2
  • GitHub Check: test-sim-nondeterminism
  • GitHub Check: Analyze
  • GitHub Check: Summary
🔇 Additional comments (7)
api/cosmos/accounts/defaults/lockup/v1/tx.pulsar.go (1)

4815-4818: Confirm usage of newly introduced proto imports.

These added imports (e.g., cosmos_proto/cosmos.proto, gogoproto/gogo.proto, google/protobuf/any.proto, google/protobuf/timestamp.proto) appear consistent with the usage of timestamppb.Timestamp and anypb.Any throughout the file. No issues found.

x/accounts/msg_server.go (1)

85-89: LGTM! Return statement added for proper method completion.

The added return statement correctly returns the encoded response from the execution.

x/accounts/msg_server_test.go (1)

82-116: LGTM! Well-structured test for unauthorized execution.

The test effectively validates that unauthorized users cannot execute transactions on accounts they don't own. Good security boundary testing with clear setup and assertions.

x/accounts/defaults/lockup/utils_test.go (1)

73-73: LGTM! Consistent sender parameter update.

The change from "sender" to "owner" aligns with the broader refactor of sender handling across the codebase.

x/accounts/defaults/lockup/periodic_locking_account_test.go (1)

218-252: LGTM! Comprehensive test for unauthorized coin sending.

The test effectively validates that unauthorized users cannot send coins even when tokens are fully unlocked. Good test structure with clear setup, time manipulation, and assertions.

x/accounts/defaults/lockup/lockup.go (2)

132-133: LGTM! Improved sender validation.

The change to use accountstd.Sender(ctx) and pass bytes directly to checkSender is more efficient and aligns with the PR objectives.


330-340: LGTM! Improved efficiency in sender validation.

The change to use byte comparison directly instead of string conversion is more efficient and reduces unnecessary allocations.

x/accounts/defaults/lockup/lockup.go Outdated Show resolved Hide resolved
x/accounts/defaults/lockup/lockup.go Outdated Show resolved Hide resolved
@julienrbrt julienrbrt added the backport/v0.52.x PR scheduled for inclusion in the v0.52's next stable release label Feb 6, 2025
Copy link
Member

@julienrbrt julienrbrt left a comment

Choose a reason for hiding this comment

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

nice! lgtm

@tac0turtle tac0turtle enabled auto-merge February 6, 2025 12:18
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/accounts/defaults/lockup/lockup.go (1)

429-489: Consider breaking down complex methods into smaller functions.

The TrackDelegation and TrackUndelegation methods, while well-documented, are quite complex. Consider extracting the computation logic (e.g., the X and Y calculations) into separate helper functions to improve readability and maintainability.

Example refactor for TrackDelegation:

+func computeDelegationAmounts(lockedAmt, delLockingAmt, delAmt math.Int) (x, y math.Int) {
+    // compute x and y per the specification, where:
+    // X := min(max(V - DV, 0), D)
+    // Y := D - X
+    x = math.MinInt(math.MaxInt(lockedAmt.Sub(delLockingAmt), math.ZeroInt()), delAmt)
+    y = delAmt.Sub(x)
+    return x, y
+}

 func (bva *BaseLockup) TrackDelegation(
     ctx context.Context, balance, lockedCoins, amount sdk.Coins,
 ) error {
     // ... existing validation code ...

     lockedAmt := lockedCoins.AmountOf(bondDenom)
     delLockingAmt, err := bva.DelegatedLocking.Get(ctx, bondDenom)
     if err != nil {
         return err
     }
     delFreeAmt, err := bva.DelegatedFree.Get(ctx, bondDenom)
     if err != nil {
         return err
     }

-    // compute x and y per the specification, where:
-    // X := min(max(V - DV, 0), D)
-    // Y := D - X
-    x := math.MinInt(math.MaxInt(lockedAmt.Sub(delLockingAmt), math.ZeroInt()), delAmt)
-    y := delAmt.Sub(x)
+    x, y := computeDelegationAmounts(lockedAmt, delLockingAmt, delAmt)

     // ... rest of the method
 }

Also applies to: 491-547

📜 Review details

Configuration used: .coderabbit.yml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between fc30bfc and efd7bde.

📒 Files selected for processing (5)
  • tests/integration/v2/accounts/lockup/continous_lockup_test_suite.go (0 hunks)
  • tests/integration/v2/accounts/lockup/delayed_lockup_test_suite.go (0 hunks)
  • tests/integration/v2/accounts/lockup/periodic_lockup_test_suite.go (0 hunks)
  • tests/integration/v2/accounts/lockup/permanent_lockup_test_suite.go (0 hunks)
  • x/accounts/defaults/lockup/lockup.go (5 hunks)
💤 Files with no reviewable changes (4)
  • tests/integration/v2/accounts/lockup/continous_lockup_test_suite.go
  • tests/integration/v2/accounts/lockup/permanent_lockup_test_suite.go
  • tests/integration/v2/accounts/lockup/delayed_lockup_test_suite.go
  • tests/integration/v2/accounts/lockup/periodic_lockup_test_suite.go
🧰 Additional context used
📓 Path-based instructions (1)
`**/*.go`: Review the Golang code for conformity with the Ub...

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

  • x/accounts/defaults/lockup/lockup.go
⏰ Context from checks skipped due to timeout of 90000ms (10)
  • GitHub Check: Analyze
  • GitHub Check: tests (03)
  • GitHub Check: tests (02)
  • GitHub Check: tests (01)
  • GitHub Check: tests (00)
  • GitHub Check: test-sim-nondeterminism
  • GitHub Check: test-integration
  • GitHub Check: test-system-v2
  • GitHub Check: build (arm64)
  • GitHub Check: Summary
🔇 Additional comments (2)
x/accounts/defaults/lockup/lockup.go (2)

131-132: LGTM! Consistent sender retrieval from context.

The changes consistently retrieve the sender from context instead of message across all methods, which aligns with the module's design principles.

Also applies to: 187-188, 260-261, 288-289


328-338: LGTM! Optimized sender verification.

The method now efficiently compares byte slices directly without string conversion, which is a performance improvement.

@aljo242 aljo242 disabled auto-merge February 6, 2025 16:47
@aljo242 aljo242 merged commit 5cedd50 into main Feb 6, 2025
70 of 71 checks passed
@aljo242 aljo242 deleted the marko/lockup_account_fix branch February 6, 2025 16:48
mergify bot pushed a commit that referenced this pull request Feb 6, 2025
Co-authored-by: Alex | Interchain Labs <[email protected]>
(cherry picked from commit 5cedd50)

# Conflicts:
#	api/cosmos/accounts/defaults/lockup/v1/tx.pulsar.go
#	x/accounts/defaults/lockup/continuous_locking_account_test.go
#	x/accounts/defaults/lockup/periodic_locking_account_test.go
#	x/accounts/defaults/lockup/permanent_locking_account_test.go
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
backport/v0.52.x PR scheduled for inclusion in the v0.52's next stable release C:x/accounts/lockup C:x/accounts
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants