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(x/auth/tx): JSON TX encoding/decoding #20803

Merged
merged 20 commits into from
Jul 29, 2024
Merged

fix(x/auth/tx): JSON TX encoding/decoding #20803

merged 20 commits into from
Jul 29, 2024

Conversation

kocubinski
Copy link
Member

@kocubinski kocubinski commented Jun 27, 2024

Description

Fixes a regression in JSON transaction encoding/decoding introduced somewhere in recent x/tx refactors.

Previously decimal fields in proto specs were represented in JSON as human readable strings, e.g.

3.14159 -> "3.141590000000000000"

On main (today) they are represented by their backing word in the math package, e.g

3.14159 -> "3141590000000000000"

The latter is consistent with the at rest state representation, and proto wire format, but different from how JSON RPC represents decimals (the former) in the Amino ProtoJSON spec. See: #10863 (comment). As long as we're committing to AminoJSON at the JSON RPC boundary, we ought to represent JSON Txs with the same spec, Amino JSON.

The added test now fails without the patch to x/auth/tx in this PR like:

        	Messages:   	expected {"body":{"messages":[{"@type":"/testpb.TestMsg", "signers":["cosmos1dlgll8xq9e2yxd00qccw9mymqv45h8244jp4l8"], "decField":"3141590000000000000"}], "memo":"foomemo"}, "auth_info":{"signer_infos":[{"public_key":{"@type":"/cosmos.crypto.secp256k1.PubKey", "key":"A87XkCofwGthnhovnbbKIx/F6ftaAm7tWDnykHLIWK3+"}, "mode_info":{"single":{"mode":"SIGN_MODE_LEGACY_AMINO_JSON"}}}], "fee":{"amount":[{"denom":"atom", "amount":"150"}], "gas_limit":"50000"}}, "signatures":["ZHVtbXlTaWc="]} to contain 3.141590000000000000

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

Summary by CodeRabbit

  • New Features

    • Added ValidatorInfo field to provide additional details for each validator.
    • Introduced a new field DecField in TestMsg for better message handling.
    • Added a new launch configuration for debugging the simapp application.
  • Bug Fixes

    • Enhanced JSON decoding and marshaling in transaction encoding and decoding functions.
  • Tests

    • Updated test cases to include the new DecField for comprehensive validation.
  • Chores

    • Updated imports and internal methods to align with new protobuf and JSON handling libraries.

Copy link
Contributor

coderabbitai bot commented Jun 27, 2024

Warning

Rate limit exceeded

@kocubinski has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 15 minutes and 15 seconds before requesting another review.

How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

Commits

Files that changed from the base of the PR and between 47fc88c and 605b1d0.

Walkthrough

Walkthrough

The recent updates introduce key enhancements to the Cosmos SDK, focusing on the addition of new fields and adjustments in protobuf messaging (tx.proto and related Go files). This includes the introduction of ValidatorInfo and DecField, as well as improvements in JSON encoding and decoding functions. These changes enhance the SDK's data handling capabilities and ensure consistency across various components.

Changes

File Change Summary
api/cosmos/staking/v1beta1/query.pulsar.go Added ValidatorInfo field to QueryValidatorsResponse struct.
testutil/testdata/testpb/tx.proto Included import for cosmos_proto/cosmos.proto and added decField to TestMsg message.
testutil/testdata/testpb/tx.pulsar.go Added support for DecField in TestMsg, including various field operations.
x/auth/migrations/legacytx/stdtx_test.go Updated JSON string in test function to include "decField":"0".
x/auth/tx/decoder.go Switched from protojson to gogoproto for JSON decoding, altered imports, and improved error handling.
x/auth/tx/encoder.go Modified DefaultJSONTxEncoder to use proto.Marshal and gogoproto.Unmarshal.
x/auth/tx/testutil/suite.go Set DecField values in test messages using math.LegacyZeroDec() and math.LegacyMustNewDecFromStr(pi).
testutil/testdata/tx.go Initialized DecField in NewTestMsg function.
types/tx_msg_test.go Updated test case to use NewTestMsg() and set DecField.
.vscode/launch.json Added new launch configuration for debugging Go application "Start: simapp/v1".

Sequence Diagrams

The provided changes do not necessitate a sequence diagram as they mainly involve struct enhancements, protocol buffer changes, and minor testing tweaks without altering the control flow or introducing significant new features.


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

@kocubinski kocubinski marked this pull request as ready for review July 1, 2024 16:51
@kocubinski kocubinski requested a review from a team as a code owner July 1, 2024 16:51
@kocubinski kocubinski changed the title fix(x/auth): DNM json encoding fix(x/auth): JSON encoding/decoding Jul 1, 2024
Copy link
Contributor

github-actions bot commented Jul 1, 2024

@kocubinski your pull request is missing a changelog!

@kocubinski kocubinski changed the title fix(x/auth): JSON encoding/decoding fix(x/auth/tx): JSON encoding/decoding Jul 1, 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: 1

Outside diff range and nitpick comments (1)
x/auth/tx/decoder.go (1)

Line range hint 18-43: Improve error handling consistency.

Ensure that all errors are wrapped consistently using errorsmod.Wrap.

-		if err != nil {
-			return nil, err
-		}
+		if err != nil {
+			return nil, errorsmod.Wrap(sdkerrors.ErrTxDecode, err.Error())
+		}
Review details

Configuration used: .coderabbit.yml
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 7c0ff07 and 76e8ca0.

Files ignored due to path filters (2)
  • testutil/testdata/tx.pb.go is excluded by !**/*.pb.go
  • x/staking/types/query.pb.go is excluded by !**/*.pb.go
Files selected for processing (7)
  • api/cosmos/staking/v1beta1/query.pulsar.go (1 hunks)
  • testutil/testdata/testpb/tx.proto (2 hunks)
  • testutil/testdata/testpb/tx.pulsar.go (15 hunks)
  • x/auth/migrations/legacytx/stdtx_test.go (1 hunks)
  • x/auth/tx/decoder.go (1 hunks)
  • x/auth/tx/encoder.go (2 hunks)
  • x/auth/tx/testutil/suite.go (5 hunks)
Additional context used
Path-based instructions (6)
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/decoder.go (1)

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

x/auth/migrations/legacytx/stdtx_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/testutil/suite.go (1)

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

testutil/testdata/testpb/tx.pulsar.go (1)

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

api/cosmos/staking/v1beta1/query.pulsar.go (1)

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

Additional comments not posted (13)
testutil/testdata/testpb/tx.proto (1)

40-45: Ensure consistency in field options.

The decField has multiple options applied. Ensure that these options are consistent with the rest of the proto file and do not conflict with each other.

Verification successful

Field options are consistent.

The gogoproto.customtype field option is consistently used across the proto files without any conflicts.

  • cosmossdk.io/math.LegacyDec
  • cosmossdk.io/math.Int
Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify consistency of field options in proto files.

# Test: Search for other fields with similar options. Expect: No conflicts or inconsistencies.
rg --type proto $'gogoproto.customtype'

Length of output: 68



Script:

#!/bin/bash
# Locate all .proto files and search for the gogoproto.customtype field option within them
fd -e proto -x rg 'gogoproto.customtype' {}

Length of output: 3247

x/auth/migrations/legacytx/stdtx_test.go (1)

47-47: Ensure test coverage for all scenarios.

The string msgStr includes a new field decField. Ensure that tests cover various values for this field, including edge cases.

x/auth/tx/testutil/suite.go (5)

72-73: Ensure DecField is correctly set.

The DecField is being set to math.LegacyZeroDec(). Verify that this is the intended value for the tests.


81-82: Ensure all messages are correctly set.

The unbuiltMsgs should be equal to msgs. Verify that all messages are correctly set in the transaction builder.


250-251: Ensure DecField is correctly set to the value of pi.

The DecField is being set to math.LegacyMustNewDecFromStr(pi). Verify that this is the intended value for the tests.


296-298: Check JSON representation for human-readable decimal value.

Ensure that the JSON representation contains the human-readable decimal value of pi.


315-316: Verify DecField after JSON decoding.

Ensure that the DecField retains the correct value of pi after JSON decoding.

testutil/testdata/testpb/tx.pulsar.go (5)

8-8: Approved: New import statement for cosmos-proto.

The addition of the import statement for cosmos-proto is necessary for the new functionality.


985-987: Approved: New field descriptor for DecField.

The addition of the field descriptor fd_TestMsg_decField is necessary for handling the new DecField.


994-994: Approved: Initialization of new field descriptor in init function.

The initialization of the new field descriptor fd_TestMsg_decField in the init function is correct.


1068-1073: Approved: Logic for iterating over DecField in Range method.

The logic for iterating over the new DecField in the Range method is correct.


1091-1092: Approved: Logic for handling DecField in various methods.

The logic for handling the new DecField in the Has, Clear, Get, Set, Mutable, NewField, ProtoMethods, and Unmarshal methods is correct.

Also applies to: 1111-1112, 1135-1137, 1162-1163, 1190-1191, 1208-1209, 1285-1288, 1415-1446

api/cosmos/staking/v1beta1/query.pulsar.go (1)

14424-14428: Ensure field ValidatorInfo is correctly populated.

The ValidatorInfo field is a new addition that provides additional details for each validator. Ensure that this field is correctly populated and maintained in sync with the Validators field in all relevant parts of the codebase.

Comments are clear and helpful.

The comments explaining the usage of the ValidatorInfo field are clear and provide valuable context for developers. This is a good practice and should be continued.

Consider adding validation logic.

Consider adding validation logic to ensure the ValidatorInfo list always corresponds in order and length to the Validators list, to prevent potential mismatches.

Comment on lines 32 to 41
bz, err := proto.Marshal(gogoWrapper.Tx)
if err != nil {
return nil, err
}
v1Tx := &sdktx.Tx{}
err = gogoproto.Unmarshal(bz, v1Tx)
if err != nil {
return nil, err
}
return cdc.MarshalJSON(v1Tx)
Copy link
Contributor

Choose a reason for hiding this comment

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

Consider simplifying the encoding process.

The function uses both proto.Marshal and gogoproto.Unmarshal. This might lead to unnecessary complexity and potential issues. If possible, use a single protobuf library for encoding.

-    bz, err := proto.Marshal(gogoWrapper.Tx)
+    bz, err := gogoproto.Marshal(gogoWrapper.Tx)
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
bz, err := proto.Marshal(gogoWrapper.Tx)
if err != nil {
return nil, err
}
v1Tx := &sdktx.Tx{}
err = gogoproto.Unmarshal(bz, v1Tx)
if err != nil {
return nil, err
}
return cdc.MarshalJSON(v1Tx)
bz, err := gogoproto.Marshal(gogoWrapper.Tx)
if err != nil {
return nil, err
}
v1Tx := &sdktx.Tx{}
err = gogoproto.Unmarshal(bz, v1Tx)
if err != nil {
return nil, err
}
return cdc.MarshalJSON(v1Tx)

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 76e8ca0 and f1f156c.

Files selected for processing (3)
  • testutil/testdata/tx.go (2 hunks)
  • types/tx_msg_test.go (2 hunks)
  • x/auth/tx/testutil/suite.go (5 hunks)
Files skipped from review as they are similar to previous changes (1)
  • x/auth/tx/testutil/suite.go
Additional context used
Path-based instructions (2)
types/tx_msg_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"

testutil/testdata/tx.go (1)

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

golangci-lint
types/tx_msg_test.go

6-6: File is not gci-ed with --skip-generated -s standard -s default -s prefix(cosmossdk.io) -s prefix(github.com/cosmos/cosmos-sdk) --custom-order

(gci)


5-5: File is not gofumpt-ed with -extra

(gofumpt)

Additional comments not posted (1)
testutil/testdata/tx.go (1)

85-86: LGTM!

The code changes are approved. The initialization of DecField with math.LegacyZeroDec() ensures proper handling of the new field.

types/tx_msg_test.go 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 f1f156c and 1866691.

Files selected for processing (1)
  • types/tx_msg_test.go (2 hunks)
Files skipped from review as they are similar to previous changes (1)
  • types/tx_msg_test.go

Copy link
Contributor

@testinginprod testinginprod left a comment

Choose a reason for hiding this comment

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

lgtm

@aaronc
Copy link
Member

aaronc commented Jul 11, 2024

Unfortunately the correct proto JSON rendering for LegacyDec is "3141590000000000000" because the proto JSON spec says it should match the (bad) binary encoding. Yes it is not human readable because of how the binary encoding was setup years ago. Trying to make it human readable with the correct decimal point is simply incorrect because it breaks the proto JSON spec. We may think this is a small issue but whenever you break a spec you're going to be causing some bugs somewhere else in the system. If it is proto JSON and the type is string, the rendering should be the exact same string that is encoded in proto binary.

Two alternatives are 1) create another json encoding where we control the rules (we actually already have one called amino) or 2) use a different Dec type where the binary encoding includes a decimal point. We could accomplish 2 without even moving over to a GDA Dec but simply by creating a v2 of this LegacyDec.

Trying to make things sort of work by hacking into how gogo proto works is not a good idea IMHO. The fact that gogo supports custom JSON marshaling was never a good idea and created subtle bugs for us years ago. Probably the panic is because of these custom gogo JSON methods. The problem though is that no other protobuf clients will be able to match our encoding if we use gogo to break the spec. Consider what would happen if a user who has a correct protobuf client takes some legacy dec value from a proto binary endpoint and then tries to pass it to a "gogo proto json" endpoints. They will be off by an order of magnitude. Or if someone is using proto v2 as a client in go and uses both proto json and binary (which is the case with autocli). Now I personally think proto json is extremely limiting and we should move on from it. But breaking specs is almost always bad and that's one of the big footguns of gogo - lots of customization introduces lots of ways to mess up.

@kocubinski
Copy link
Member Author

kocubinski commented Jul 16, 2024

Trying to make things sort of work by hacking into how gogo proto works is not a good idea IMHO.

Unfortunately the SDK spec has this hack as canonical (SDK correct?) up to v0.50, so changing it now is breaking for any client which reads or writes JSON, including a JSON formatted genesis file.

@kocubinski
Copy link
Member Author

kocubinski commented Jul 17, 2024

this issue runs deeper than I initially realized, tagging #20085 here too for my reference

edit: see also: #20536

@kocubinski kocubinski changed the title fix(x/auth/tx): JSON encoding/decoding fix(x/auth/tx): JSON TX encoding/decoding Jul 26, 2024
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.

tACK. It is a property of the SDK now so makes sense to keep the behavior.

@kocubinski kocubinski enabled auto-merge July 29, 2024 17:54
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 1866691 and 47fc88c.

Files selected for processing (1)
  • .vscode/launch.json (1 hunks)
Additional comments not posted (1)
.vscode/launch.json (1)

24-31: LGTM! Configuration for simapp/v1 is correctly added.

The new launch configuration for simapp/v1 follows the same structure as the existing configurations and appears to be correct.

@kocubinski kocubinski added this pull request to the merge queue Jul 29, 2024
Merged via the queue into main with commit d80afaa Jul 29, 2024
73 checks passed
@kocubinski kocubinski deleted the kocu/json-encoding branch July 29, 2024 18:33
@julienrbrt
Copy link
Member

@Mergifyio backport release/v0.52.x

Copy link
Contributor

mergify bot commented Jul 31, 2024

backport release/v0.52.x

✅ Backports have been created

mergify bot pushed a commit that referenced this pull request Jul 31, 2024
julienrbrt pushed a commit that referenced this pull request Jul 31, 2024
Co-authored-by: Matt Kocubinski <mkocubinski@gmail.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

5 participants