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(emissions): add nil checks for reward distributions #2999

Merged
merged 5 commits into from
Oct 14, 2024

Conversation

lumtis
Copy link
Member

@lumtis lumtis commented Oct 11, 2024

Description

  • Add nil check for the reward per block params, panic here would halt the chain
  • Add nil checks in the params validation, originally it panicked at this stage as well
  • Skip reward distribution logic if reward per block is 0

Summary by CodeRabbit

  • New Features

    • Introduced a new helper function for improved logging during reward distribution.
  • Bug Fixes

    • Enhanced error handling and validation for reward distribution and parameter checks.
  • Documentation

    • Updated test cases and error messages for better clarity and coverage.

Copy link
Contributor

coderabbitai bot commented Oct 11, 2024

📝 Walkthrough

Walkthrough

The changes in this pull request involve renaming variables and constants across several files to standardize naming conventions, particularly regarding the casing of "TSS". Key updates include the renaming of UndistributedTssRewardsPool to UndistributedTSSRewardsPool in multiple locations and the renaming of the DistributeTssRewards function to DistributeTSSRewards. Additionally, test cases have been updated for clarity and robustness, with enhancements to validation logic and error messages.

Changes

File Path Change Summary
app/app.go, testutil/keeper/keeper.go, x/emissions/abci.go, x/emissions/module.go, x/emissions/types/keys.go Renamed UndistributedTssRewardsPool to UndistributedTSSRewardsPool in multiple locations; renamed DistributeTssRewards to DistributeTSSRewards in abci.go; introduced logEach10Blocks helper function; streamlined error handling for reward distribution.
x/emissions/abci_test.go, x/emissions/types/message_update_params_test.go, x/emissions/types/params.go, x/emissions/types/params_test.go Updated test cases and validation logic; expanded scenarios in TestDistributeObserverRewards; enhanced validation for nil and negative values in params.go.

Suggested labels

no-changelog

Suggested reviewers

  • fbac
  • skosito
  • CharlieMc0
  • brewmaster012
  • kingpinXD

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

@lumtis lumtis added the no-changelog Skip changelog CI check label Oct 11, 2024
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: 3

🧹 Outside diff range and nitpick comments (11)
x/emissions/types/message_update_params_test.go (2)

32-32: Approve change with minor suggestion for consistency

The updated error message, "block reward amount must not be negative," is more precise and aligns well with mathematical terminology. This change improves the clarity of the test case.

For consistency with Go's standard library error messages, consider using "must be" instead of "must not be". This would result in:

require.ErrorContains(t, err, "block reward amount must be non-negative")

This phrasing maintains the improved precision while adhering more closely to idiomatic Go error messages.


Line range hint 1-94: Commend comprehensive test coverage

The test file demonstrates thorough coverage of the MsgUpdateParams functionality. It includes tests for:

  1. Invalid authority address
  2. Invalid parameters
  3. Valid cases
  4. Signer validation
  5. Message type and route checks
  6. Sign bytes generation

The use of sub-tests with t.Run() enhances readability and organization. The tests utilize appropriate assertion functions from the require package, which is a best practice in Go testing.

Consider adding edge cases or boundary value tests if not covered elsewhere, such as:

  1. Maximum allowed block reward amount
  2. Minimum valid non-zero block reward amount

Overall, the test file exhibits high quality and adherence to Go testing conventions.

x/emissions/types/params.go (1)

107-111: Approval with minor suggestion: Enhanced robustness in slash amount validation

The addition of a nil check and the use of v.IsNegative() significantly improve the robustness of the validation logic. The updated error messages provide more specific information about validation failures.

For consistency with other error messages in this file, consider modifying the error message on line 111 to:

return fmt.Errorf("observer slash amount must not be negative")

This change would align the wording with the error messages in other validation functions.

x/emissions/types/params_test.go (2)

59-59: Approve the addition of nil check with a minor suggestion.

The inclusion of a nil check in the TestValidateObserverSlashAmount function enhances the robustness of the test suite. This change aligns well with the PR objective of implementing nil checks to improve system stability.

To further strengthen the test, consider adding an assertion to verify the specific error message returned when a nil value is provided. This would ensure that the error handling is not only present but also provides the expected feedback.

Consider adding an assertion for the error message:

err := validateObserverSlashAmount(nil)
require.Error(t, err)
require.Contains(t, err.Error(), "observer slash amount cannot be nil")

73-73: Approve the addition of nil check with a minor suggestion.

The inclusion of a nil check in the TestValidateBlockRewardAmount function enhances the test coverage and aligns with the PR objective of implementing nil checks for improved stability.

To further strengthen the test, consider adding an assertion to verify the specific error message returned when a nil value is provided. This would ensure that the error handling is not only present but also provides the expected feedback.

Consider adding an assertion for the error message:

err := validateBlockRewardsAmount(nil)
require.Error(t, err)
require.Contains(t, err.Error(), "block reward amount cannot be nil")
x/emissions/abci.go (3)

19-25: Consider extracting the magic number as a constant.

The logEach10Blocks function effectively reduces log frequency. However, to enhance maintainability, consider extracting the magic number '10' as a package-level constant:

const logFrequencyBlocks = 10

func logEach10Blocks(message string) {
    if ctx.BlockHeight()%logFrequencyBlocks == 0 {
        ctx.Logger().Info(message)
    } else {
        ctx.Logger().Debug(message)
    }
}

This change would make it easier to adjust the logging frequency in the future if needed.


42-44: Consider simplifying the string formatting for improved readability.

While the updated logging is an improvement, the string formatting can be simplified for better readability:

logEach10Blocks(fmt.Sprintf("Block rewards %s are greater than emission pool balance %s", blockRewards, emissionPoolBalance))

This change removes the redundant .String() calls, as fmt.Sprintf will automatically call the String() method on these types.


186-191: Enhance function comment for clarity and correctness.

The renaming of the function and the use of UndistributedTSSRewardsPool improve consistency. However, the function comment could be enhanced:

// DistributeTSSRewards transfers the allocated rewards to the Undistributed TSS Rewards Pool.
// This ensures that the reserves factor is properly calculated in the next block.
func DistributeTSSRewards(ctx sdk.Context, amount sdk.Int, bankKeeper types.BankKeeper) error {
    coin := sdk.NewCoins(sdk.NewCoin(config.BaseDenom, amount))
    return bankKeeper.SendCoinsFromModuleToModule(ctx, types.ModuleName, types.UndistributedTSSRewardsPool, coin)
}

This comment correction fixes the typo "trasferes" and clarifies the purpose of the function.

x/emissions/abci_test.go (3)

39-39: TestBeginBlocker function updated correctly.

The changes in this function are consistent with the renaming efforts, improving code clarity. However, consider extracting the repeated emissions.BeginBlocker(ctx, *k) calls into a helper function to reduce duplication and improve maintainability.

Consider applying this refactor:

func runBeginBlocker(ctx sdk.Context, k *emissionskeeper.Keeper) sdk.Context {
    emissions.BeginBlocker(ctx, *k)
    return ctx.WithBlockHeight(ctx.BlockHeight() + 1)
}

// Usage in tests
ctx = runBeginBlocker(ctx, k)

Also applies to: 46-46, 68-68, 73-73, 86-86, 103-103, 109-109, 142-142, 169-169, 200-200, 202-202, 220-220, 236-236, 255-255


320-327: TestDistributeObserverRewards function significantly improved.

The changes to this function greatly enhance the test coverage, including important edge cases such as nil, negative, and zero block rewards. This improvement aligns with best practices for comprehensive unit testing.

To further enhance readability and maintainability, consider grouping related test cases into subtests using t.Run(). This approach would make it easier to identify and run specific test scenarios.

Consider restructuring the tests as follows:

func TestDistributeObserverRewards(t *testing.T) {
    t.Run("RewardDistribution", func(t *testing.T) {
        // Test cases for normal reward distribution
    })

    t.Run("EdgeCases", func(t *testing.T) {
        t.Run("NilBlockReward", func(t *testing.T) {
            // Test case for nil block reward
        })
        t.Run("NegativeBlockReward", func(t *testing.T) {
            // Test case for negative block reward
        })
        t.Run("ZeroBlockReward", func(t *testing.T) {
            // Test case for zero block reward
        })
    })
}

Also applies to: 331-336, 339-350, 354-359, 362-373, 377-382, 385-396, 400-405, 408-419, 423-428, 431-434, 437-449, 450-517


585-594: New setEmissionsParams function added for testing purposes.

The setEmissionsParams function provides a way to set emissions parameters directly in the store without validation. While this is useful for testing scenarios, it's important to ensure this function is not used in production code.

Consider adding a comment to clearly indicate that this function is intended for testing purposes only:

// setEmissionsParams sets the emissions params in the store without validation.
// IMPORTANT: This function is intended for testing purposes only and should not be used in production code.
func setEmissionsParams(t *testing.T, ctx sdk.Context, k emissionskeeper.Keeper, params emissionstypes.Params) {
    // ... (existing implementation)
}
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 95186e0 and c029fe0.

📒 Files selected for processing (9)
  • app/app.go (1 hunks)
  • testutil/keeper/keeper.go (1 hunks)
  • x/emissions/abci.go (3 hunks)
  • x/emissions/abci_test.go (20 hunks)
  • x/emissions/module.go (1 hunks)
  • x/emissions/types/keys.go (2 hunks)
  • x/emissions/types/message_update_params_test.go (1 hunks)
  • x/emissions/types/params.go (6 hunks)
  • x/emissions/types/params_test.go (3 hunks)
✅ Files skipped from review due to trivial changes (2)
  • app/app.go
  • testutil/keeper/keeper.go
🧰 Additional context used
📓 Path-based instructions (7)
x/emissions/abci.go (1)

Pattern **/*.go: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.

x/emissions/abci_test.go (1)

Pattern **/*.go: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.

x/emissions/module.go (1)

Pattern **/*.go: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.

x/emissions/types/keys.go (1)

Pattern **/*.go: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.

x/emissions/types/message_update_params_test.go (1)

Pattern **/*.go: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.

x/emissions/types/params.go (1)

Pattern **/*.go: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.

x/emissions/types/params_test.go (1)

Pattern **/*.go: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.

🔇 Additional comments (10)
x/emissions/types/keys.go (1)

45-45: Approve the variable update for consistency.

The update of UndistributedTssRewardsPoolAddress to use the renamed constant UndistributedTSSRewardsPool maintains consistency with the earlier constant renaming. This change ensures that the module address is correctly associated with the updated constant name.

To confirm this change is applied correctly and consistently, please execute the following verification script:

x/emissions/types/params.go (5)

66-68: Approval: Improved readability in negative value check

The modification from dec.LT(sdk.ZeroDec()) to dec.IsNegative() enhances code clarity while maintaining the correct logic. This change aligns with idiomatic Go practices and improves the overall readability of the validation function.


81-83: Approval: Consistent improvement in negative value check

The alteration from dec.LT(sdk.ZeroDec()) to dec.IsNegative() maintains consistency with the previous function and enhances code clarity. This change contributes to a more uniform and readable codebase.


96-98: Approval: Consistent improvement across emission percentage validations

The modification from dec.LT(sdk.ZeroDec()) to dec.IsNegative() in this function completes the consistent update across all emission percentage validation functions. This change contributes to a more uniform, readable, and maintainable codebase.


134-138: Approval: Improved validation for block rewards amount

The modifications in this function significantly enhance the robustness of the validation logic:

  1. The addition of a nil check prevents potential panics when dealing with uninitialized values.
  2. The use of v.IsNegative() aligns with the changes made in other validation functions, promoting consistency across the codebase.
  3. The updated error messages provide more precise information about the nature of validation failures, which will aid in debugging and error handling.

These changes collectively contribute to a more reliable and maintainable validation process for the block rewards amount.


Line range hint 1-141: Summary: Comprehensive improvements in parameter validation

The changes made to this file significantly enhance the robustness and clarity of the parameter validation logic:

  1. Consistent use of IsNegative() for checking negative values across all validation functions improves readability and maintainability.
  2. Introduction of nil checks in relevant functions prevents potential panics and aligns with the PR objectives.
  3. Updated error messages provide more specific information, aiding in debugging and error handling.

These modifications collectively contribute to a more stable and reliable emissions module, effectively addressing the goals outlined in the PR objectives.

x/emissions/types/params_test.go (1)

118-118: Approve the updated error message.

The modification of the error message in the TestValidate function for negative block reward amounts is a commendable improvement. The new message, "block reward amount must not be negative," is more precise and aligns better with the validation logic. This change enhances the clarity of error feedback, which is crucial for effective debugging and system maintenance.

x/emissions/abci.go (2)

35-39: Robust nil and non-positive check for block rewards.

The addition of this check enhances the function's robustness by handling edge cases where block rewards might be nil or non-positive. The use of the logEach10Blocks function for logging is appropriate and consistent with the new logging strategy.


64-64: Approved: Consistent naming convention for TSS.

The renaming of DistributeTssRewards to DistributeTSSRewards improves consistency in the codebase by using the correct capitalization for the acronym "TSS" (Threshold Signature Scheme). This change aligns with Go's naming conventions for acronyms.

x/emissions/abci_test.go (1)

16-17: Import statements updated appropriately.

The renaming of import packages aligns with the standardization efforts mentioned in the summary. This change enhances code consistency.

Also applies to: 19-19

x/emissions/types/keys.go Show resolved Hide resolved
x/emissions/module.go Show resolved Hide resolved
x/emissions/abci_test.go Show resolved Hide resolved
Copy link
Contributor

@swift1337 swift1337 left a comment

Choose a reason for hiding this comment

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

... panic here would halt the chain

Do we have a wrapper with defer for panic recovery somewhere?

@lumtis
Copy link
Member Author

lumtis commented Oct 11, 2024

... panic here would halt the chain

Do we have a wrapper with defer for panic recovery somewhere?

Nope, I'm not sure we should had a general wrapper, in some case a bug where a panic happen could reflect a deeper issue where it's not safe to let the chain continue producing blocks

Copy link

codecov bot commented Oct 11, 2024

Codecov Report

Attention: Patch coverage is 73.07692% with 7 lines in your changes missing coverage. Please review.

Project coverage is 66.07%. Comparing base (81fc485) to head (c8b6d34).
Report is 5 commits behind head on develop.

Files with missing lines Patch % Lines
x/emissions/types/params.go 66.66% 2 Missing and 2 partials ⚠️
x/emissions/abci.go 78.57% 2 Missing and 1 partial ⚠️
Additional details and impacted files

Impacted file tree graph

@@             Coverage Diff             @@
##           develop    #2999      +/-   ##
===========================================
- Coverage    66.09%   66.07%   -0.02%     
===========================================
  Files          397      397              
  Lines        22332    22347      +15     
===========================================
+ Hits         14760    14766       +6     
- Misses        6804     6810       +6     
- Partials       768      771       +3     
Files with missing lines Coverage Δ
x/emissions/abci.go 92.59% <78.57%> (-2.36%) ⬇️
x/emissions/types/params.go 92.68% <66.66%> (-4.76%) ⬇️

... and 1 file with indirect coverage changes

@lumtis lumtis added this pull request to the merge queue Oct 14, 2024
Merged via the queue into develop with commit cb9f348 Oct 14, 2024
34 checks passed
@lumtis lumtis deleted the fix/prevent-nil-beginBlocker branch October 14, 2024 08:23
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
no-changelog Skip changelog CI check
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants