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

refactor(x/**): rewrite ante handlers as tx validators #20488

Merged
merged 11 commits into from
Jun 3, 2024

Conversation

julienrbrt
Copy link
Member

@julienrbrt julienrbrt commented May 30, 2024

Description

Bring tx validators from server_modular by cherry-picking:


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

  • New Features

    • Introduced new methods for transaction handling, including hashing, gas limit retrieval, message retrieval, and sender retrieval.
    • Added a TxValidator function to improve transaction validation.
  • Improvements

    • Updated various interfaces and methods to streamline transaction processing and improve performance.
    • Simplified access to transaction fields for better code maintainability and readability.

Copy link
Contributor

coderabbitai bot commented May 30, 2024

Walkthrough

Walkthrough

The changes involve adding new methods to various structs to support hashing, gas limit, message, and sender retrieval, along with updating import statements and refactoring code to align with new module structures. These updates enhance the functionality and maintainability of transaction handling within the Cosmos SDK.

Changes

File Path Change Summary
server/mock/tx.go Added methods to KVStoreTx for hashing, gas limit, messages, and senders.
types/mempool/signer_extraction_adapater_test.go Added methods to nonVerifiableTx for byte manipulation, hashing, gas limit, messages, and senders.
types/tx_msg.go Added import for cosmossdk.io/core/transaction and embedded transaction.Tx within the Tx interface.
x/auth/module.go Imported new modules, updated interfaces, and introduced TxValidator function for server/v2.
x/auth/tx/builder.go Updated references to fields within decodedTx and AuthInfo structs.
x/auth/tx/encoder.go Changed DefaultTxEncoder and DefaultJSONTxEncoder to use updated gogoWrapper fields.
x/auth/tx/gogotx.go Updated newWrapperFromDecodedTx return type, embedded *decode.DecodedTx in gogoTxWrapper, and adjusted method references.
x/auth/tx/legacy_amino_json.go Simplified field access in signModeLegacyAminoJSONHandler's GetSignBytes method.
x/tx/decode/decode.go Added imports, global variable, and methods for transaction.Tx interface in DecodedTx struct.

Sequence Diagram(s) (Beta)

Possibly related issues


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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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 as 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.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

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

@@ -95,6 +98,8 @@ func TestValidateMemo(t *testing.T) {
}

func TestConsumeGasForTxSize(t *testing.T) {
t.Skip() // TODO(@julienrbrt) Fix after https://github.com/cosmos/cosmos-sdk/pull/20072
Copy link
Member Author

Choose a reason for hiding this comment

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

todo, to do.

@julienrbrt julienrbrt marked this pull request as ready for review May 30, 2024 11:07
@julienrbrt julienrbrt requested a review from a team as a code owner May 30, 2024 11:07
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: 4

Outside diff range and nitpick comments (5)
contrib/images/simd-env/Dockerfile (5)

Line range hint 3-3: Pin versions in apk add to ensure reproducibility.

- RUN apk add build-base git linux-headers
+ RUN apk add build-base=2.0.1 git=2.30 linux-headers=5.10

Line range hint 3-3: Use the --no-cache option with apk add to avoid unnecessary cache storage.

- RUN apk add build-base git linux-headers
+ RUN apk add --no-cache build-base git linux-headers

Line range hint 37-37: Always tag the version of an image explicitly to avoid unexpected changes.

- FROM alpine AS run
+ FROM alpine:3.14 AS run

Line range hint 38-38: Pin versions in apk add to ensure reproducibility.

- RUN apk add bash curl jq
+ RUN apk add bash=5.1 curl=7.76 jq=1.6

Line range hint 38-38: Use the --no-cache option with apk add to avoid unnecessary cache storage.

- RUN apk add bash curl jq
+ RUN apk add --no-cache bash curl jq
Review details

Configuration used: .coderabbit.yml
Review profile: CHILL

Commits

Files that changed from the base of the PR and between ac49374 and 87efc48.

Files ignored due to path filters (6)
  • runtime/v2/go.mod is excluded by !**/*.mod
  • runtime/v2/go.sum is excluded by !**/*.sum
  • x/auth/go.mod is excluded by !**/*.mod
  • x/auth/go.sum is excluded by !**/*.sum
  • x/tx/go.mod is excluded by !**/*.mod
  • x/tx/go.sum is excluded by !**/*.sum
Files selected for processing (15)
  • contrib/images/simd-env/Dockerfile (1 hunks)
  • server/mock/tx.go (2 hunks)
  • server/v2/stf/mock/tx.go (1 hunks)
  • simapp/ante.go (1 hunks)
  • types/mempool/mempool_test.go (3 hunks)
  • types/mempool/signer_extraction_adapater_test.go (2 hunks)
  • types/tx_msg.go (2 hunks)
  • x/auth/ante/ante.go (1 hunks)
  • x/auth/ante/basic.go (7 hunks)
  • x/auth/ante/basic_test.go (4 hunks)
  • x/auth/ante/sigverify.go (1 hunks)
  • x/auth/module.go (3 hunks)
  • x/auth/tx/config/depinject.go (1 hunks)
  • x/auth/tx/gogotx.go (2 hunks)
  • x/tx/decode/decode.go (3 hunks)
Files skipped from review due to trivial changes (1)
  • x/auth/tx/config/depinject.go
Additional context used
Path-based instructions (13)
simapp/ante.go (1)

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

server/v2/stf/mock/tx.go (1)

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

types/mempool/signer_extraction_adapater_test.go (2)

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


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

x/auth/ante/ante.go (1)

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

types/tx_msg.go (1)

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

server/mock/tx.go (1)

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

x/tx/decode/decode.go (1)

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

x/auth/module.go (1)

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

types/mempool/mempool_test.go (2)

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


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

x/auth/ante/basic.go (1)

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

x/auth/ante/basic_test.go (2)

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


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

x/auth/tx/gogotx.go (1)

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

x/auth/ante/sigverify.go (1)

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

Hadolint
contrib/images/simd-env/Dockerfile

[warning] 3-3: Pin versions in apk add. Instead of apk add <package> use apk add <package>=<version>


[info] 3-3: Use the --no-cache switch to avoid the need to use --update and remove /var/cache/apk/* when done installing packages


[warning] 37-37: Always tag the version of an image explicitly


[warning] 38-38: Pin versions in apk add. Instead of apk add <package> use apk add <package>=<version>


[info] 38-38: Use the --no-cache switch to avoid the need to use --update and remove /var/cache/apk/* when done installing packages

Additional comments not posted (36)
contrib/images/simd-env/Dockerfile (1)

26-30: Ensure that the new modules are necessary and correctly placed in the Dockerfile.

simapp/ante.go (1)

41-41: Ensure the NewTxTimeoutHeightDecorator is correctly integrated and the options.Environment parameter is properly utilized.

server/v2/stf/mock/tx.go (1)

26-28: Properly handle nil messages to prevent runtime errors.

types/mempool/signer_extraction_adapater_test.go (1)

28-47: Ensure the added methods for nonVerifiableTx are necessary and correctly implemented for testing purposes.

x/auth/ante/ante.go (1)

48-48: Ensure the NewTxTimeoutHeightDecorator is correctly integrated and the options.Environment parameter is properly utilized.

types/tx_msg.go (1)

55-56: Ensure the transaction.Tx interface is correctly embedded in the Tx interface.

server/mock/tx.go (4)

98-100: The Hash method returns a fixed hash value, which is suitable for mock implementations but should not be used in production.


102-104: The GetGasLimit method returns a fixed gas limit of 0, which is suitable for mock implementations but should not be used in production.


106-108: The GetMessages method returns nil, which is suitable for mock implementations but should not be used in production.


110-112: The GetSenders method returns nil, which is suitable for mock implementations but should not be used in production.

x/tx/decode/decode.go (5)

140-146: The Hash method correctly computes the hash based on transaction bytes. Good implementation.


148-153: The GetGasLimit method correctly retrieves the gas limit from the transaction's AuthInfo and handles potential nil values correctly.


155-166: The GetMessages method correctly converts protobuf messages to transaction messages and handles potential nil values correctly.


168-172: The GetSenders method correctly retrieves the senders from the transaction and handles potential nil values correctly.


175-180: The Bytes method correctly computes the transaction bytes based on the raw transaction data. Good implementation.

x/auth/module.go (1)

154-178: The TxValidator method correctly sets up and applies a series of transaction validators. It handles type assertion and error propagation effectively.

types/mempool/mempool_test.go (2)

79-97: The methods in the testTx struct return fixed values, which are suitable for mock implementations but should not be used in production.


113-131: The methods in the sigErrTx struct return fixed values, which are suitable for mock implementations but should not be used in production.

x/auth/ante/basic.go (4)

35-56: The ValidateTx method in ValidateBasicDecorator correctly checks the transaction execution mode and validates the basic properties of the transaction. Good implementation.


72-97: The ValidateTx method in ValidateMemoDecorator correctly validates the memo size against the parameters and handles errors effectively.


Line range hint 119-185: The ValidateTx method in ConsumeTxSizeGasDecorator correctly consumes gas proportional to the transaction size and simulates gas cost for signatures. Good implementation.


235-263: The ValidateTx method in TxTimeoutHeightDecorator correctly checks the transaction timeout height against the current block height and handles errors effectively.

x/auth/ante/basic_test.go (6)

4-4: Ensure the new import context is utilized appropriately in the tests.


10-11: New imports for appmodule/v2 and header are added. Verify that these are used effectively in the tests, particularly in the new mockHeaderService.


190-191: The mockHeaderService is introduced to support testing the TxTimeoutHeightDecorator. Ensure that this mock is correctly integrated and used in the tests.


230-231: The method WithBlockHeight is used to set the block height in the mockHeaderService. This is crucial for testing the timeout logic in transactions. Ensure that the method is called correctly and the expected behavior is verified in the tests.


237-249: The mockHeaderService struct and its methods are well-defined. Ensure that the HeaderInfo method correctly returns the expected header information and that the WithBlockHeight method effectively sets the expected block height.


101-102: The test is skipped with a TODO note referencing another PR. Ensure this is addressed before merging to maintain test coverage.

Would you like me to help by creating a GitHub issue to track the resolution of this TODO after PR #20072 is merged?

x/auth/tx/gogotx.go (7)

4-4: Ensure the new import crypto/sha256 is used appropriately for cryptographic operations.


11-11: The addition of google.golang.org/protobuf/protoadapt should be justified by its usage in the file, particularly for adapting protobuf messages.


16-16: The import cosmossdk.io/core/transaction is crucial for the transaction handling enhancements mentioned in the PR summary.


109-111: The caching mechanism introduced here with cachedHash, cachedBytes, and cachedHashed is a good performance optimization. Ensure thread safety if applicable.


141-146: The method GetGasLimit() correctly handles potential nil pointers, which is crucial for robust error handling.


148-159: The method GetMessages() effectively checks for nil values before proceeding, which is a good practice for robust error handling.


161-166: The method GetSenders() includes necessary nil checks. Ensure that all possible error paths are tested.

x/auth/ante/sigverify.go (1)

463-469: The AnteHandle method in ValidateSigCountDecorator correctly handles the validation of transaction signatures based on the count. Ensure comprehensive testing for this logic.

Comment on lines 130 to 139
func (w *gogoTxWrapper) computeHashAndBytes() {
bz, err := proto.Marshal(w.decodedTx.TxRaw)
if err != nil {
panic(err)
}

w.cachedBytes = bz
w.cachedHash = sha256.Sum256(bz)
w.cachedHashed = true
}
Copy link
Contributor

@coderabbitai coderabbitai bot May 30, 2024

Choose a reason for hiding this comment

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

The computeHashAndBytes method is central to the caching logic. Consider handling errors gracefully instead of using panic.

func (w *gogoTxWrapper) computeHashAndBytes() error {
	bz, err := proto.Marshal(w.decodedTx.TxRaw)
	if err != nil {
		return err
	}
	w.cachedBytes = bz
	w.cachedHash = sha256.Sum256(bz)
	w.cachedHashed = true
	return nil
}

Copy link
Contributor

Choose a reason for hiding this comment

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

@julienrbrt i think we should shift the duty of this towards x/tx.

Copy link
Contributor

Choose a reason for hiding this comment

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

Seems like the humans are having a chat. I'll hop back into my burrow for now. If you need me again, just tag @coderabbitai in a new comment, and I'll come hopping out!

Copy link
Member Author

Choose a reason for hiding this comment

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

Okay!

Comment on lines 123 to 128
func (w *gogoTxWrapper) Hash() [32]byte {
if !w.cachedHashed {
w.computeHashAndBytes()
}
return w.cachedHash
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Similar to the Bytes() method, Hash() also benefits from caching. Ensure consistency in error handling as suggested for Bytes().

func (w *gogoTxWrapper) Hash() ([32]byte, error) {
	if !w.cachedHashed {
		if err := w.computeHashAndBytes(); err != nil {
			return [32]byte{}, err
		}
	}
	return w.cachedHash, nil
}

Comment on lines 116 to 121
func (w *gogoTxWrapper) Bytes() []byte {
if !w.cachedHashed {
w.computeHashAndBytes()
}
return w.cachedBytes
}
Copy link
Contributor

Choose a reason for hiding this comment

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

The method Bytes() utilizes the caching mechanism effectively. However, consider adding error handling for the computeHashAndBytes method in case of failures.

func (w *gogoTxWrapper) Bytes() ([]byte, error) {
	if !w.cachedHashed {
		if err := w.computeHashAndBytes(); err != nil {
			return nil, err
		}
	}
	return w.cachedBytes, nil
}

Comment on lines +471 to +491
func (vscd ValidateSigCountDecorator) ValidateTx(ctx context.Context, tx sdk.Tx) error {
sigTx, ok := tx.(authsigning.SigVerifiableTx)
if !ok {
return ctx, errorsmod.Wrap(sdkerrors.ErrTxDecode, "Tx must be a sigTx")
return errorsmod.Wrap(sdkerrors.ErrTxDecode, "Tx must be a sigTx")
}

params := vscd.ak.GetParams(ctx)
pubKeys, err := sigTx.GetPubKeys()
if err != nil {
return ctx, err
return err
}

sigCount := 0
for _, pk := range pubKeys {
sigCount += CountSubKeys(pk)
if uint64(sigCount) > params.TxSigLimit {
return ctx, errorsmod.Wrapf(sdkerrors.ErrTooManySignatures, "signatures: %d, limit: %d", sigCount, params.TxSigLimit)
return errorsmod.Wrapf(sdkerrors.ErrTooManySignatures, "signatures: %d, limit: %d", sigCount, params.TxSigLimit)
}
}

return next(ctx, tx, false)
return nil
Copy link
Contributor

Choose a reason for hiding this comment

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

The ValidateTx method provides a robust check for the number of signatures against a set limit. Consider adding more detailed error messages to aid in debugging.

func (vscd ValidateSigCountDecorator) ValidateTx(ctx context.Context, tx sdk.Tx) error {
	sigTx, ok := tx.(authsigning.SigVerifiableTx)
	if !ok {
		return errorsmod.Wrap(sdkerrors.ErrTxDecode, "Tx must be a sigTx with signature verification capabilities")
	}
	params := vscd.ak.GetParams(ctx)
	pubKeys, err := sigTx.GetPubKeys()
	if err != nil {
		return err
	}
	sigCount := 0
	for _, pk := range pubKeys {
		sigCount += CountSubKeys(pk)
		if uint64(sigCount) > params.TxSigLimit {
			return errorsmod.Wrapf(sdkerrors.ErrTooManySignatures, "too many signatures: %d, limit: %d", sigCount, params.TxSigLimit)
		}
	}
	return nil
}

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

Review details

Configuration used: .coderabbit.yml
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 87efc48 and cd12f3b.

Files selected for processing (2)
  • x/auth/ante/basic.go (7 hunks)
  • x/auth/ante/sigverify.go (1 hunks)
Files skipped from review as they are similar to previous changes (2)
  • x/auth/ante/basic.go
  • x/auth/ante/sigverify.go

@@ -126,3 +136,56 @@ func (d *Decoder) Decode(txBytes []byte) (*DecodedTx, error) {
Signers: signers,
}, nil
}

// Hash implements the interface for the Tx interface.
func (dtx *DecodedTx) Hash() [32]byte {
Copy link
Member

Choose a reason for hiding this comment

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

These changes were originally in #19588 but I can't convince myself they're needed here since gogotx handles the conversion and tx building. Is it true they're not needed?

Copy link
Member Author

Choose a reason for hiding this comment

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

Right, if you are not supposed to use a DecodedTx directly, I guess it makes sense to remove this.

Copy link
Member Author

Choose a reason for hiding this comment

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

looks like we should do the reverse: #20488 (comment)

Copy link
Member

Choose a reason for hiding this comment

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

Got it, LGTM

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

Review details

Configuration used: .coderabbit.yml
Review profile: CHILL

Commits

Files that changed from the base of the PR and between cd12f3b and 887e172.

Files ignored due to path filters (2)
  • x/auth/go.mod is excluded by !**/*.mod
  • x/auth/go.sum is excluded by !**/*.sum
Files selected for processing (5)
  • server/mock/tx.go (2 hunks)
  • types/mempool/signer_extraction_adapater_test.go (2 hunks)
  • types/tx_msg.go (3 hunks)
  • x/auth/module.go (3 hunks)
  • x/auth/tx/gogotx.go (2 hunks)
Files skipped from review as they are similar to previous changes (5)
  • server/mock/tx.go
  • types/mempool/signer_extraction_adapater_test.go
  • types/tx_msg.go
  • x/auth/module.go
  • x/auth/tx/gogotx.go

x/auth/tx/gogotx.go Outdated Show resolved Hide resolved
x/auth/tx/gogotx.go Outdated Show resolved Hide resolved
x/auth/tx/gogotx.go Outdated Show resolved Hide resolved
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

Review details

Configuration used: .coderabbit.yml
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 887e172 and f384362.

Files ignored due to path filters (6)
  • go.mod is excluded by !**/*.mod
  • go.sum is excluded by !**/*.sum
  • simapp/go.mod is excluded by !**/*.mod
  • simapp/go.sum is excluded by !**/*.sum
  • tests/go.mod is excluded by !**/*.mod
  • tests/go.sum is excluded by !**/*.sum
Files selected for processing (5)
  • x/auth/tx/builder.go (1 hunks)
  • x/auth/tx/encoder.go (2 hunks)
  • x/auth/tx/gogotx.go (8 hunks)
  • x/auth/tx/legacy_amino_json.go (2 hunks)
  • x/tx/decode/decode.go (3 hunks)
Files skipped from review as they are similar to previous changes (2)
  • x/auth/tx/gogotx.go
  • x/tx/decode/decode.go
Additional context used
Path-based instructions (3)
x/auth/tx/encoder.go (1)

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

x/auth/tx/legacy_amino_json.go (1)

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

x/auth/tx/builder.go (1)

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

Additional comments not posted (4)
x/auth/tx/encoder.go (2)

35-35: LGTM! Ensure that the type assertion for gogoWrapper is always valid in all use cases.

Verification successful

The implementation of DefaultJSONTxEncoder includes a type assertion for gogoWrapper, and it returns an error if the assertion fails. This ensures that the type assertion is handled correctly within the function itself.

  • DefaultJSONTxEncoder implementation:

    func DefaultJSONTxEncoder(cdc codec.Codec) sdk.TxEncoder {
        jsonMarshaler := protojson.MarshalOptions{
            Indent:         "",
            UseProtoNames:  true,
            UseEnumNumbers: false,
        }
        return func(tx sdk.Tx) ([]byte, error) {
            gogoWrapper, ok := tx.(*gogoTxWrapper)
            if !ok {
                return nil, fmt.Errorf("unexpected tx type: %T", tx)
            }
            return jsonMarshaler.Marshal(gogoWrapper.Tx)
        }
    }
  • Usage in x/auth/tx/config.go:

    txConfig.jsonEncoder = DefaultJSONTxEncoder(protoCodec)

The type assertion for gogoWrapper is handled correctly within the DefaultJSONTxEncoder function, ensuring that any incorrect type will result in an error.

Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify that all uses of `DefaultJSONTxEncoder` handle the type assertion correctly.

# Test: Search for the function usage. Expect: Proper handling of type assertion.
rg --type go $'DefaultJSONTxEncoder'

Length of output: 310



Script:

#!/bin/bash
# Extract the relevant code from x/auth/tx/config.go to inspect the usage of DefaultJSONTxEncoder.
rg --type go --context 10 'DefaultJSONTxEncoder' x/auth/tx/config.go

Length of output: 779



Script:

#!/bin/bash
# Extract the implementation of DefaultJSONTxEncoder.
rg --type go --context 10 'func DefaultJSONTxEncoder' x/auth/tx/encoder.go

# Extract the usage of txConfig.jsonEncoder.
rg --type go 'txConfig.jsonEncoder' x/auth/tx/

Length of output: 838


19-19: LGTM! Ensure that the type assertion for gogoWrapper is always valid in all use cases.

Verification successful

The type assertion for gogoWrapper in DefaultTxEncoder is handled correctly within the function itself, ensuring that any incorrect type is caught and an error is returned. The usages in config.go and stdtx_builder.go do not introduce any issues related to this type assertion.

  • encoder.go: The type assertion is handled within the DefaultTxEncoder function.
  • config.go: The function is used without additional type assertion handling, but this is acceptable since the function itself handles it.
  • stdtx_builder.go: This file defines a different DefaultTxEncoder function that does not impact the type assertion handling of gogoWrapper.
Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify that all uses of `DefaultTxEncoder` handle the type assertion correctly.

# Test: Search for the function usage. Expect: Proper handling of type assertion.
rg --type go $'DefaultTxEncoder'

Length of output: 469



Script:

#!/bin/bash
# Description: Review the implementation of `DefaultTxEncoder` in `encoder.go`.

# Test: Extract the implementation of `DefaultTxEncoder`.
ast-grep --lang go --pattern $'func DefaultTxEncoder() sdk.TxEncoder {
  $$$
}' x/auth/tx/encoder.go

Length of output: 566


Script:

#!/bin/bash
# Description: Review the usage of `DefaultTxEncoder` in `config.go`.

# Test: Extract the relevant lines around the usage of `DefaultTxEncoder`.
rg --context 5 'DefaultTxEncoder' x/auth/tx/config.go

Length of output: 469


Script:

#!/bin/bash
# Description: Review the usage of `DefaultTxEncoder` in `stdtx_builder.go`.

# Test: Extract the relevant lines around the usage of `DefaultTxEncoder`.
rg --context 5 'DefaultTxEncoder' x/auth/migrations/legacytx/stdtx_builder.go

Length of output: 391

x/auth/tx/legacy_amino_json.go (1)

Line range hint 51-72: LGTM! Ensure that the handling of non-critical fields and extension options is consistent across all transaction types.

Verification successful

The search results indicate that the GetSignBytes function is implemented in several files, with some implementations being placeholders (i.e., panic("not implemented")). However, the relevant implementations that handle non-critical fields and extension options are found in the following files:

  • x/tx/signing/directaux/direct_aux.go
  • x/tx/signing/aminojson/aminojson.go
  • x/auth/tx/legacy_amino_json.go

These implementations show consistent handling of non-critical fields and extension options, aligning with the changes made in x/auth/tx/legacy_amino_json.go.

  • x/tx/signing/directaux/direct_aux.go: Handles fee payer and signer data, ensuring proper authorization.
  • x/tx/signing/aminojson/aminojson.go: Checks for unknown fields and unsupported protobuf extension options.
  • x/auth/tx/legacy_amino_json.go: Validates non-critical fields and extension options, ensuring they are not present.

Based on this analysis, the handling of non-critical fields and extension options appears consistent across the relevant transaction types.

Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify that all transaction types correctly handle non-critical fields and extension options.

# Test: Search for the function usage. Expect: Consistent handling across all transaction types.
rg --type go $'GetSignBytes'

Length of output: 9735



Script:

#!/bin/bash
# Description: Extract implementations of GetSignBytes to verify handling of non-critical fields and extension options.

# Extract implementations of GetSignBytes from relevant files.
ast-grep --lang go --pattern 'func ($_ $_) GetSignBytes($_, $_, $_) ($_ $_) { $$$ }'

Length of output: 86



Script:

#!/bin/bash
# Description: Extract implementations of GetSignBytes to verify handling of non-critical fields and extension options.

# Extract implementations of GetSignBytes with different signatures.
ast-grep --lang go --pattern 'func ($_ $_) GetSignBytes($_, $_, $_) ($_ $_) { $$$ }'
ast-grep --lang go --pattern 'func ($_ $_) GetSignBytes($_, $_) ($_ $_) { $$$ }'
ast-grep --lang go --pattern 'func ($_ $_) GetSignBytes($_) ($_ $_) { $$$ }'

Length of output: 248



Script:

#!/bin/bash
# Description: Extract implementations of GetSignBytes to verify handling of non-critical fields and extension options.

# Search for GetSignBytes function definitions to capture the exact signatures.
rg --type go --pcre2 --regexp 'func \(\w+ \w+\) GetSignBytes\('

Length of output: 1066



Script:

#!/bin/bash
# Description: Extract implementations of GetSignBytes to verify handling of non-critical fields and extension options.

# Extract implementations of GetSignBytes from the identified files.
ast-grep --lang go --pattern 'func (s directHandler) GetSignBytes($_, $_, $_) ($_ $_) { $$$ }' x/tx/signing/handler_map_test.go
ast-grep --lang go --pattern 'func (s aminoJSONHandler) GetSignBytes($_, $_, $_) ($_ $_) { $$$ }' x/tx/signing/handler_map_test.go
ast-grep --lang go --pattern 'func (h SignModeHandler) GetSignBytes($_, $_, $_) ($_ $_) { $$$ }' x/tx/signing/directaux/direct_aux.go
ast-grep --lang go --pattern 'func (h SignModeHandler) GetSignBytes($_, $_, $_) ($_ $_) { $$$ }' x/tx/signing/aminojson/aminojson.go
ast-grep --lang go --pattern 'func (s signModeLegacyAminoJSONHandler) GetSignBytes($_, $_, $_) ($_ $_) { $$$ }' x/auth/tx/legacy_amino_json.go
ast-grep --lang go --pattern 'func (s directHandler) GetSignBytes($_, $_, $_) ($_ $_) { $$$ }' x/accounts/depinject.go
ast-grep --lang go --pattern 'func (s directHandler) GetSignBytes($_, $_, $_) ($_ $_) { $$$ }' tests/integration/auth/keeper/msg_server_test.go

Length of output: 945



Script:

#!/bin/bash
# Description: Extract implementations of GetSignBytes to verify handling of non-critical fields and extension options.

# Extract implementations of GetSignBytes from the identified files.
rg --type go --pcre2 --regexp 'func \(\w+ \w+\) GetSignBytes\(' -A 20

Length of output: 9566

x/auth/tx/builder.go (1)

36-40: LGTM! Ensure that the handling of signer information is consistent and error-free across all transaction types.

Verification successful

The function newBuilderFromDecodedTx is used in the WrapTxBuilder method of the config struct in x/auth/tx/config.go. This method wraps a provided transaction and creates a new builder from the decoded transaction.

The handling of signer information appears to be consistent and integrated within the WrapTxBuilder method, ensuring that the signer information is correctly processed when wrapping transactions.

  • x/auth/tx/config.go:
    • WrapTxBuilder method uses newBuilderFromDecodedTx to handle signer information.
Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify that all transaction types correctly handle signer information.

# Test: Search for the function usage. Expect: Consistent handling across all transaction types.
rg --type go $'newBuilderFromDecodedTx'

Length of output: 327



Script:

#!/bin/bash
# Extract the relevant code from x/auth/tx/config.go to review the handling of signer information.
sed -n '1,50p' x/auth/tx/config.go

Length of output: 2110



Script:

#!/bin/bash
# Extract additional lines from x/auth/tx/config.go to review the handling of signer information.
sed -n '51,100p' x/auth/tx/config.go

Length of output: 2448



Script:

#!/bin/bash
# Extract additional lines from x/auth/tx/config.go to review the handling of signer information.
sed -n '101,150p' x/auth/tx/config.go

Length of output: 1927



Script:

#!/bin/bash
# Extract additional lines from x/auth/tx/config.go to review the handling of signer information.
sed -n '151,200p' x/auth/tx/config.go

Length of output: 1720



Script:

#!/bin/bash
# Extract additional lines from x/auth/tx/config.go to review the handling of signer information.
sed -n '201,250p' x/auth/tx/config.go

Length of output: 1347

@julienrbrt julienrbrt mentioned this pull request May 31, 2024
12 tasks
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

Review details

Configuration used: .coderabbit.yml
Review profile: CHILL

Commits

Files that changed from the base of the PR and between f384362 and ca6d493.

Files ignored due to path filters (8)
  • go.mod is excluded by !**/*.mod
  • go.sum is excluded by !**/*.sum
  • simapp/go.mod is excluded by !**/*.mod
  • simapp/go.sum is excluded by !**/*.sum
  • tests/go.mod is excluded by !**/*.mod
  • tests/go.sum is excluded by !**/*.sum
  • x/auth/go.mod is excluded by !**/*.mod
  • x/auth/go.sum is excluded by !**/*.sum
Files selected for processing (1)
  • x/auth/module.go (3 hunks)
Additional context used
Path-based instructions (1)
x/auth/module.go (1)

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

golangci-lint
x/auth/module.go

38-38: cannot use AppModule{} (value of type AppModule) as "cosmossdk.io/core/appmodule/v2".HasGenesis value in variable declaration: AppModule does not implement "cosmossdk.io/core/appmodule/v2".HasGenesis (missing method IsOnePerModuleType)


39-39: cannot use AppModule{} (value of type AppModule) as "cosmossdk.io/core/appmodule/v2".AppModule value in variable declaration: AppModule does not implement "cosmossdk.io/core/appmodule/v2".AppModule (missing method IsOnePerModuleType)


40-40: cannot use AppModule{} (value of type AppModule) as "cosmossdk.io/core/appmodule".HasServices value in variable declaration: AppModule does not implement "cosmossdk.io/core/appmodule".HasServices (missing method IsOnePerModuleType)


41-41: cannot use AppModule{} (value of type AppModule) as "cosmossdk.io/core/appmodule/v2".HasMigrations value in variable declaration: AppModule does not implement "cosmossdk.io/core/appmodule/v2".HasMigrations (missing method IsOnePerModuleType)

Additional comments not posted (2)
x/auth/module.go (2)

12-16: Ensure new imports are utilized correctly.

The new imports for appmodulev2, transaction, and ante are correctly placed and are essential for the new functionality introduced in this module.


157-180: Review new TxValidator function for correctness and efficiency.

The TxValidator function correctly implements the appmodulev2.HasTxValidator interface. It uses a series of validators to ensure the transaction meets various criteria. The function is well-structured and should operate efficiently under normal conditions.

Comment on lines +38 to +41
_ appmodulev2.HasGenesis = AppModule{}
_ appmodulev2.AppModule = AppModule{}
_ appmodule.HasServices = AppModule{}
_ appmodulev2.HasMigrations = AppModule{}
Copy link
Contributor

Choose a reason for hiding this comment

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

Resolve interface implementation issues.

The AppModule struct is declared to implement several interfaces from appmodulev2 and appmodule, but it's missing the required IsOnePerModuleType method for these interfaces. This needs to be implemented to satisfy the interface contracts.

type AppModule struct {
	accountKeeper     keeper.AccountKeeper
	randGenAccountsFn types.RandomGenAccountsFn
	accountsModKeeper types.AccountsModKeeper
	cdc               codec.Codec
+	IsOnePerModuleType() bool {
+		// Implementation here
+	}
}

Committable suggestion was skipped due low confidence.

Tools
golangci-lint

38-38: cannot use AppModule{} (value of type AppModule) as "cosmossdk.io/core/appmodule/v2".HasGenesis value in variable declaration: AppModule does not implement "cosmossdk.io/core/appmodule/v2".HasGenesis (missing method IsOnePerModuleType)


39-39: cannot use AppModule{} (value of type AppModule) as "cosmossdk.io/core/appmodule/v2".AppModule value in variable declaration: AppModule does not implement "cosmossdk.io/core/appmodule/v2".AppModule (missing method IsOnePerModuleType)


40-40: cannot use AppModule{} (value of type AppModule) as "cosmossdk.io/core/appmodule".HasServices value in variable declaration: AppModule does not implement "cosmossdk.io/core/appmodule".HasServices (missing method IsOnePerModuleType)


41-41: cannot use AppModule{} (value of type AppModule) as "cosmossdk.io/core/appmodule/v2".HasMigrations value in variable declaration: AppModule does not implement "cosmossdk.io/core/appmodule/v2".HasMigrations (missing method IsOnePerModuleType)

Copy link
Member

@kocubinski kocubinski left a comment

Choose a reason for hiding this comment

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

LGTM, are we planning x/tx and core releases (after this merges) to remove the replace directives?

@julienrbrt
Copy link
Member Author

LGTM, are we planning x/tx and core releases (after this merges) to remove the replace directives?

Unfortunately no, as we want to tag core v1, and we don't want to bump core in x/tx just yet.

@julienrbrt julienrbrt added this pull request to the merge queue Jun 3, 2024
Merged via the queue into main with commit 2a5ff38 Jun 3, 2024
66 of 68 checks passed
@julienrbrt julienrbrt deleted the julien/tx-validators branch June 3, 2024 16:52
alpe added a commit that referenced this pull request Jun 4, 2024
* main:
  build(deps): Bump github.com/prometheus/common from 0.53.0 to 0.54.0 (#20534)
  refactor(x/**): rewrite ante handlers as tx validators (#20488)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

5 participants