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

feat: audit #354

Merged
merged 9 commits into from
Mar 4, 2025
Merged

feat: audit #354

merged 9 commits into from
Mar 4, 2025

Conversation

beer-1
Copy link
Member

@beer-1 beer-1 commented Mar 1, 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

@beer-1 beer-1 self-assigned this Mar 1, 2025
@beer-1 beer-1 requested a review from a team as a code owner March 1, 2025 08:51
Copy link

coderabbitai bot commented Mar 1, 2025

Important

Review skipped

Review was skipped due to path filters

⛔ Files ignored due to path filters (1)
  • .github/workflows/docker.yml is excluded by !**/*.yml

CodeRabbit blocks several paths by default. You can override this behavior by explicitly including those paths in the path filters. For example, including **/dist/** will override the default block on the dist directory, by removing the pattern from both the lists.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

📝 Walkthrough

Walkthrough

This PR adjusts several reward allocation and error handling routines across the distribution and move modules. In the distribution module, the token allocation now uses truncated division, and the genesis balance check has been relaxed. In the move module, the initialization no longer processes execution responses while dispatch and view functions receive improved error handling using type checks and an infinite gas context. The connector’s pool weight function is also modified to return valid weights without triggering an error for timestamp discrepancies.

Changes

File(s) Change Summary
x/distribution/keeper/allocation.go Changed the poolFraction calculation in AllocateTokens to use QuoTruncate (truncated division) instead of standard division.
x/distribution/keeper/genesis.go Updated InitGenesis to compare module account balances using IsAllGTE and added a variable (broken) for condition tracking before panicking.
x/move/keeper/genesis.go Modified the Initialize method to remove execution response handling by returning nil directly.
x/move/keeper/handler.go Enhanced error handling in dispatchMessage (using a type switch for panic recovery) and adjusted execution context in executeViewFunction and executeEntryFunction (new variables ac/ec and infinite gas for Move VM).
x/move/types/connector.go Revised GetPoolWeights to return prior weight values with a nil error instead of returning an error when the timestamp condition fails.
x/evidence/keeper/msg_server.go Added validation checks for msg.Submitter and msg.GetEvidence() in SubmitEvidence, enhancing error handling.
x/intertx/keeper/msg_server.go Introduced validation for icaMsg in RegisterAccount and SubmitTx methods before processing messages.

Possibly related PRs

  • fix: apply audit #229: The changes in the main PR regarding the AllocateTokens method in allocation.go are directly related to the modifications made in the same file in the retrieved PR, which also involves updates to the allocation logic.
  • feat: audit #251: The changes in the main PR and the retrieved PR are related as both involve modifications to division operations, specifically replacing standard division methods with truncation variants in the AllocateTokens method and the ShareToAmount function, respectively.
  • fix: audit #253: The changes in the main PR modify the AllocateTokens method in allocation.go, while the retrieved PR also alters the logic within the AllocateTokens function in the same file, indicating a direct relationship between the two.

Suggested reviewers

  • Vritra4

Poem

I’m a bunny code-rabbit, hopping through the field of change,
Carrots of logic trimmed with care, arranged within each range.
Allocation flows now truncate errors, gentle but precise,
Genesis checks and view functions sing, bugs vanish like ice.
With cadence and with cheer, I nibble through this byte,
Celebrating every little fix that makes our code feel right!
🥕🐇


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

github-actions bot commented Mar 1, 2025

Dependency Review

✅ No vulnerabilities or license issues or OpenSSF Scorecard issues found.

OpenSSF Scorecard

PackageVersionScoreDetails

Scanned Files

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

🧹 Nitpick comments (1)
x/distribution/keeper/genesis.go (1)

126-132: Relaxed module account balance validation.

The validation check has been changed to only verify that the module account balance is greater than or equal to the expected holdings, rather than requiring an exact match. This accommodates potential external transfers into the module account.

This is a reasonable approach given the challenges with blocking fungible asset transfers. However, ensure there are regular audits to detect any unexpected discrepancies in balances that might indicate issues beyond normal operations.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 30059bc and 96e498d.

📒 Files selected for processing (5)
  • x/distribution/keeper/allocation.go (1 hunks)
  • x/distribution/keeper/genesis.go (1 hunks)
  • x/move/keeper/genesis.go (1 hunks)
  • x/move/keeper/handler.go (2 hunks)
  • x/move/types/connector.go (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: golangci-lint
  • GitHub Check: Run test and upload codecov
  • GitHub Check: Initiad
  • GitHub Check: Analyze (go)
🔇 Additional comments (5)
x/move/types/connector.go (1)

414-415:

✅ Verification successful

Improved error handling for timestamp inconsistencies.

The code now returns valid weight values instead of an error when timestampBefore is greater than timestamp. This change makes the function more robust by handling potential timestamp inconsistencies gracefully.

Run this script to verify how these weights are used in practice:


🏁 Script executed:

#!/bin/bash
# Check where GetPoolWeights is called and how errors are handled
rg -A 3 -B 3 "GetPoolWeights" --type go

Length of output: 1283


Notice: Timestamp Handling Update Verified
The changes at x/move/types/connector.go (lines 414–415) now return the pre-calculated weights (weightCoinABefore and weightCoinBBefore) with a nil error when timestampBefore is greater than timestamp. Verification shows that downstream calls (e.g., in Test_GetDexWeight in connector_test.go) expect a valid weight value and handle the nil error appropriately. This update improves robustness by gracefully managing timestamp inconsistencies without propagating an error.

x/move/keeper/handler.go (4)

394-400: Enhanced panic handling for gas-related errors.

This change improves error handling by differentiating between out-of-gas errors and other panic types, allowing appropriate propagation of gas errors while safely handling other panic scenarios.


589-591: Account tracking added to view function execution.

Adding account number tracking alongside execution counter provides better context for audit purposes. The variable naming change from executionCounter to ec also improves code consistency.


599-601: Verify the implications of using an infinite gas meter for view functions.

While delegating gas metering to the Move VM makes sense, using an infinite gas meter for view functions could potentially allow resource-intensive operations without proper constraints.

Can you confirm that the Move VM properly handles gas accounting internally for view functions? Otherwise, this approach could expose the system to potential DoS vulnerabilities if complex view functions consume excessive resources.


605-608: Context enrichment for better auditing.

Passing account number and execution counter to the execution environment enhances the audit trail for view function calls, which aligns with the PR's audit feature objectives.

Copy link

codecov bot commented Mar 1, 2025

Codecov Report

Attention: Patch coverage is 43.18182% with 25 lines in your changes missing coverage. Please review.

Project coverage is 41.18%. Comparing base (30059bc) to head (f1e401a).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
x/evidence/keeper/msg_server.go 0.00% 10 Missing ⚠️
x/intertx/keeper/msg_server.go 53.84% 4 Missing and 2 partials ⚠️
x/move/keeper/handler.go 57.14% 6 Missing ⚠️
x/distribution/keeper/genesis.go 0.00% 2 Missing ⚠️
x/move/types/connector.go 0.00% 1 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main     #354      +/-   ##
==========================================
- Coverage   41.21%   41.18%   -0.03%     
==========================================
  Files         269      269              
  Lines       25761    25783      +22     
==========================================
+ Hits        10617    10620       +3     
- Misses      13498    13515      +17     
- Partials     1646     1648       +2     
Files with missing lines Coverage Δ
x/distribution/keeper/allocation.go 67.61% <100.00%> (ø)
x/ibc-hooks/move-hooks/receive.go 57.14% <100.00%> (ø)
x/move/keeper/genesis.go 13.29% <100.00%> (ø)
x/move/types/connector.go 19.35% <0.00%> (ø)
x/distribution/keeper/genesis.go 0.00% <0.00%> (ø)
x/intertx/keeper/msg_server.go 81.63% <53.84%> (-10.26%) ⬇️
x/move/keeper/handler.go 80.14% <57.14%> (-0.92%) ⬇️
x/evidence/keeper/msg_server.go 10.00% <0.00%> (-6.67%) ⬇️

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 (4)
x/ibc-hooks/move-hooks/receive.go (4)

24-29: Enhanced error handling for memo validation in ICS-20 packet processing

This change improves the conditional logic to properly handle error cases during memo validation. Now, the function only passes the packet to the standard processing path when either it's not Move-routed OR (the validation produced no error AND there's no Move message). This ensures that invalid memo data with errors won't be incorrectly processed.

While the current implementation is correct, consider extracting this flow control logic into a helper function since it's duplicated in both packet handlers:

+ func shouldUseDefaultHandler(isMoveRouted bool, err error, hookData *HookData) bool {
+    return !isMoveRouted || (err == nil && hookData != nil && hookData.Message == nil)
+ }

  func (h MoveHooks) onRecvIcs20Packet(
      // ...existing params...
  ) ibcexported.Acknowledgement {
      isMoveRouted, hookData, err := validateAndParseMemo(data.GetMemo())
-     if !isMoveRouted || (err == nil && hookData.Message == nil) {
+     if shouldUseDefaultHandler(isMoveRouted, err, hookData) {
          return im.App.OnRecvPacket(ctx, packet, relayer)
      } else if err != nil {
          return newEmitErrorAcknowledgement(err)
      }

31-66: Consider adding audit logging for successful Move hook executions

Given that this PR is focused on adding an audit feature (as mentioned in the PR objectives), and considering this is a critical path for interchain communications, it would be beneficial to add audit logging for successful executions of Move hooks when processing ICS-20 packets.

Consider adding audit logging after successful execution:

  _, err = h.execMsg(ctx, msg)
  if err != nil {
      return newEmitErrorAcknowledgement(err)
  }
+ 
+ // Add audit logging for successful hook execution
+ ctx.Logger().Info("ICS-20 packet processed with Move hook", 
+     "sender", intermediateSender,
+     "module_address", msg.ModuleAddress,
+     "channel", packet.GetDestChannel())

  return ack

112-117: Consider adding audit logging for successful Move hook executions in ICS-721 handler

Similar to the ICS-20 handler, this function should also include audit logging for successful executions to maintain consistency and improve traceability of NFT-related operations.

Consider adding audit logging after successful execution:

  _, err = h.execMsg(ctx, msg)
  if err != nil {
      return newEmitErrorAcknowledgement(err)
  }
+
+ // Add audit logging for successful hook execution
+ ctx.Logger().Info("ICS-721 packet processed with Move hook", 
+     "sender", intermediateSender,
+     "module_address", msg.ModuleAddress,
+     "channel", packet.GetDestChannel(),
+     "class_id", data.ClassId)

  return ack

121-133: Consider adding execution metrics for monitoring and auditing

To further enhance the audit capabilities of this system, consider instrumenting the execMsg function with metrics that track execution counts, success rates, and execution times. This would be valuable for operational monitoring and auditing.

func (h MoveHooks) execMsg(ctx sdk.Context, msg *movetypes.MsgExecute) (*movetypes.MsgExecuteResponse, error) {
+   start := time.Now()
+   defer func() {
+       h.metrics.ObserveExecutionTime(time.Since(start))
+   }()

    if err := msg.Validate(h.ac); err != nil {
+       h.metrics.IncrementFailedExecutions(msg.ModuleAddress)
        return nil, err
    }

    moveMsgServer := movekeeper.NewMsgServerImpl(h.moveKeeper)
    res, err := moveMsgServer.Execute(ctx, msg)
    if err != nil {
+       h.metrics.IncrementFailedExecutions(msg.ModuleAddress)
        return nil, err
    }

+   h.metrics.IncrementSuccessfulExecutions(msg.ModuleAddress)
    return res, 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 fae9962 and 114b26b.

📒 Files selected for processing (1)
  • x/ibc-hooks/move-hooks/receive.go (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: Run test and upload codecov
  • GitHub Check: golangci-lint
  • GitHub Check: Initiad
  • GitHub Check: Analyze (go)
🔇 Additional comments (1)
x/ibc-hooks/move-hooks/receive.go (1)

76-81: Enhanced error handling for memo validation in ICS-721 packet processing

This change applies the same improved error handling logic to the non-fungible token packet processing path. The function now correctly ensures that errors from memo validation are properly handled before proceeding with any processing.

@beer-1 beer-1 merged commit a450534 into main Mar 4, 2025
10 checks passed
@beer-1 beer-1 deleted the feat/audit branch March 4, 2025 11:35
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.

1 participant