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/tx): sort with oneof field name in amino-json #21782

Merged
merged 7 commits into from
Oct 11, 2024

Conversation

maharifu
Copy link
Contributor

@maharifu maharifu commented Sep 17, 2024

Description

The Marshal operation in amino-json needs to take the oneof field name into consideration when ordering the fields, otherwise the resulting JSON will not be properly ordered.
This PR adds checks to the oneof field name when ordering fields.

This issue prevents ledger devices from signing authz grant delegate transactions with a deny-list, since the Validators field was not properly ordered.


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

  • Bug Fixes

    • Fixed JSON attribute sorting for messages using oneof fields, ensuring consistent and predictable output.
  • Improvements

    • Enhanced handling of concurrent writes for better reliability.
    • Improved marshaling of messages with oneof fields, ensuring accurate field names and structure in the output.
    • Updated tests to ensure consistency in JSON encoding across different implementations.

Copy link
Contributor

coderabbitai bot commented Sep 17, 2024

📝 Walkthrough

Walkthrough

The recent update introduces a fix for the JSON attribute sorting mechanism specifically for messages that utilize oneof fields, ensuring consistent ordering during serialization and deserialization. Additionally, improvements to the Context implementation enhance concurrent write handling. Changes in the Encoder struct refine the management of oneof fields during marshaling, including adjustments to field names and output formatting. The test suite has also been updated to ensure consistency across JSON encoding methods.

Changes

Files Change Summary
x/tx/CHANGELOG.md, x/tx/signing/aminojson/encoder.go, x/tx/signing/aminojson/json_marshal.go Fixed JSON attribute sort order for messages with oneof fields. Modified moduleAccountPretty struct and thresholdStringEncoder function for improved JSON output. Enhanced nameAndIndex struct for better handling of oneof fields during marshaling.
tests/integration/tx/aminojson/aminojson_test.go Updated TestAminoJSON_LegacyParity to ensure consistency in JSON encoding. Introduced sortJson helper function for sorting JSON fields. Updated test cases for StakeAuthorization.

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.

@maharifu maharifu marked this pull request as ready for review September 17, 2024 13:57
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.

Can you add a test?

@kocubinski
Copy link
Member

kocubinski commented Sep 17, 2024

@maharifu Thanks for your PR. I am trying to reproduce a failing test case on main for protoWithOneOf such that legacyAminoMarshal(protoWithOneOf) != aminoMarshal(protoWithOneOf) but not able to so far. I'm using StakeAuthorization. Could you help out by providing a failing protoWithOneOf ?

@maharifu
Copy link
Contributor Author

@maharifu Thanks for your PR. I am trying to reproduce a failing test case on main for protoWithOneOf such that legacyAminoMarshal(protoWithOneOf) != aminoMarshal(protoWithOneOf) but not able to so far. I'm using StakeAuthorization. Could you help out by providing a failing protoWithOneOf ?

Thank you @kocubinski. I ran into this issue by running a StakeAuthorization transaction with a deny-list. This was the resulting JSON:

{"account_number":"27","chain_id":"1BA492","fee":{"amount":[{"amount":"300","denom":"ugrain"}],"gas":"114580","granter":"paloma1zn6pee8mxmz09nsmntllu45wu0rajtzx95w22s"},"memo":"","msgs":[{"type":"cosmos-sdk/MsgGrant","value":{"grant":{"authorization":{"type":"cosmos-sdk/StakeAuthorization","value":{"authorization_type":1,"Validators":{"type":"cosmos-sdk/StakeAuthorization/DenyList","value":{"deny_list":{"address":["palomavaloper1pnt738zamsvfj5af9mh3ds48qdc8utr7zkpz8y"]}}}}}},"grantee":"paloma1pnt738zamsvfj5af9mh3ds48qdc8utr7dxk73h","granter":"paloma1uml9u2kk62ahhtanhu2nyx3t745j68pcv842ww"}}],"sequence":"4"}

authorization_type comes before Validators, but it shouldn't since the latter is uppercased. I didn't try it but I think it wouldn't fail if setting the allow-list instead.

Does this help?

@kocubinski
Copy link
Member

...
Does this help?

After some testing this message seems OK, but I see other ones failing. Looking deeper into this I think our amino JSON test suite needs a rewrite after recent refactoring as we should have caught this. In the meantime, can I ask you to apply this patch to your PR and see if the (now failing) tests pass? c2f94a3

I have the following behavior on my branch:

$ cd tests/integration/tx/aminojson/
$ go test -run 'TestAminoJSON_LegacyParity/staking/stake_authorization_allow' # passes
$ go test -run 'TestAminoJSON_LegacyParity' # fails

@maharifu
Copy link
Contributor Author

maharifu commented Sep 18, 2024

In the meantime, can I ask you to apply this patch to your PR and see if the (now failing) tests pass?

@kocubinski The tests would still fail because of some custom encoders not having the expected behaviour. I pushed your commit, as well as this one and now all tests pass. Please double-check it.

maharifu and others added 4 commits September 18, 2024 09:36
The Marshal operation in amino-json needs to take the oneof field name
into consideration when ordering the fields, otherwise the resulting
JSON will not be properly ordered.
Custom encoders module_account and threshold_string need to output
fields in lexicographical order.
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

Review details

Configuration used: .coderabbit.yml
Review profile: CHILL

Commits

Files that changed from the base of the PR and between e17c406ef9232be3102ec609e785076de48013ab and b16697e.

Files selected for processing (4)
  • tests/integration/tx/aminojson/aminojson_test.go (6 hunks)
  • x/tx/CHANGELOG.md (1 hunks)
  • x/tx/signing/aminojson/encoder.go (2 hunks)
  • x/tx/signing/aminojson/json_marshal.go (4 hunks)
Files skipped from review as they are similar to previous changes (2)
  • x/tx/CHANGELOG.md
  • x/tx/signing/aminojson/json_marshal.go
Additional context used
Path-based instructions (2)
x/tx/signing/aminojson/encoder.go (1)

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

tests/integration/tx/aminojson/aminojson_test.go (3)

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


Pattern tests/**/*: "Assess the integration and e2e test code assessing sufficient code coverage for the changes associated in the pull request"


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

Additional comments not posted (5)
x/tx/signing/aminojson/encoder.go (2)

129-133: LGTM!

The reordering of fields in the moduleAccountPretty struct does not introduce any functional changes. While it may affect the order of fields in the serialized JSON, this change aligns with the rest of the codebase and does not violate any style guidelines.


173-197: Looks good!

The modifications to the thresholdStringEncoder function improve the JSON encoding process by:

  1. Adjusting the output format to write the pubkeys array before the threshold value.
  2. Streamlining the handling of empty pk.PublicKeys.
  3. Correctly appending the threshold value after the pubkeys array.

These changes enhance the clarity and correctness of the generated JSON while maintaining a valid structure. The code adheres to the Uber Go Style Guide.

tests/integration/tx/aminojson/aminojson_test.go (3)

Line range hint 1-217: LGTM!

The TestAminoJSON_Equivalence function is a comprehensive test that ensures the equivalence of the new x/tx/Encoder encoding and the legacy Encoder encoding. The workflow for testing legacy gogo types is well-defined and handles the necessary conversions.


218-218: LGTM!

The change to the aj variable declaration is correct and removes the DoNotSortFields option, which aligns with the goal of producing a standardized JSON output.


397-401: LGTM!

The changes to the StakeAuthorization test case are correct and ensure consistency between the gogo and pulsar implementations by including the MaxTokens and AuthorizationType fields.

Also applies to: 404-408

Comment on lines 440 to 441
gogoBytes, err = sortJson(gogoBytes)
require.NoError(t, err)
Copy link
Contributor

Choose a reason for hiding this comment

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

Consider using a third-party library for sorting JSON.

Instead of using the custom sortJson function, consider using a well-established library like github.com/tidwall/gjson for sorting JSON. This library provides a more robust and efficient way to sort JSON fields.

import "github.com/tidwall/gjson"

// ...

gogoBytes, err = gjson.ParseBytes(gogoBytes).Sort().Bytes()
require.NoError(t, err)

// ...

newGogoBytes, err = gjson.ParseBytes(newGogoBytes).Sort().Bytes()
require.NoError(t, err)

Also applies to: 469-470

Comment on lines +610 to +626

// sortJson sorts the JSON bytes by way of the side effect of unmarshalling and remarshalling the JSON
// using encoding/json. This hacky way of sorting JSON fields was used by the legacy amino JSON encoding in
// x/auth/migrations/legacytx.StdSignBytes. It is used here ensure the x/tx JSON encoding is equivalent to
// the legacy amino JSON encoding.
func sortJson(bz []byte) ([]byte, error) {
var c any
err := json.Unmarshal(bz, &c)
if err != nil {
return nil, err
}
js, err := json.Marshal(c)
if err != nil {
return nil, err
}
return js, nil
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Move the sortJson function to a separate utility package.

Consider moving the sortJson function to a separate utility package to improve code organization and reusability. This function is a general-purpose utility and can be used in other parts of the codebase.

// utils/json.go
package utils

func SortJSON(bz []byte) ([]byte, error) {
	var c any
	err := json.Unmarshal(bz, &c)
	if err != nil {
		return nil, err
	}
	js, err := json.Marshal(c)
	if err != nil {
		return nil, err
	}
	return js, nil
}

@kocubinski
Copy link
Member

@maharifu thanks again for your PR!
We are ready to merge, can you resolve conflicts and add the following patch to your PR?
Once done, happy to merge 🙏

diff --git a/tests/integration/rapidgen/rapidgen.go b/tests/integration/rapidgen/rapidgen.go
index 0060ca1976..2d2f5ab486 100644
--- a/tests/integration/rapidgen/rapidgen.go
+++ b/tests/integration/rapidgen/rapidgen.go
@@ -259,9 +259,7 @@ var (

                GenType(&slashingtypes.Params{}, &slashingapi.Params{}, GenOpts.WithDisallowNil()),

-               // JSON ordering of one of fields to be fixed in https://github.com/cosmos/cosmos-sdk/pull/21782
-               // TODO uncomment once merged
-               // GenType(&stakingtypes.StakeAuthorization{}, &stakingapi.StakeAuthorization{}, GenOpts),
+               GenType(&stakingtypes.StakeAuthorization{}, &stakingapi.StakeAuthorization{}, GenOpts),

                GenType(&upgradetypes.CancelSoftwareUpgradeProposal{}, &upgradeapi.CancelSoftwareUpgradeProposal{}, GenOpts),       //nolint:staticcheck // testing legacy code path
                GenType(&upgradetypes.SoftwareUpgradeProposal{}, &upgradeapi.SoftwareUpgradeProposal{}, GenOpts.WithDisallowNil()), //nolint:staticcheck // testing legacy code path
diff --git a/tests/integration/tx/aminojson/aminojson_test.go b/tests/integration/tx/aminojson/aminojson_test.go
index cf9695b4b4..e7d5e5b172 100644
--- a/tests/integration/tx/aminojson/aminojson_test.go
+++ b/tests/integration/tx/aminojson/aminojson_test.go
@@ -311,9 +311,6 @@ func TestAminoJSON_LegacyParity(t *testing.T) {
                                },
                                AuthorizationType: stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_DELEGATE,
                        },
-                       // to be fixed in https://github.com/cosmos/cosmos-sdk/pull/21782
-                       // TODO remove once merged
-                       fails: true,
                },
                "vesting/base_account_empty": {
                        gogo: &vestingtypes.BaseVestingAccount{BaseAccount: &authtypes.BaseAccount{}},

@maharifu
Copy link
Contributor Author

maharifu commented Oct 4, 2024

@kocubinski I resolved the conflicts and added your patch. Let me know if something is still missing.

@julienrbrt julienrbrt changed the title fix: sort with oneof field name in amino-json fix(x/tx): sort with oneof field name in amino-json Oct 11, 2024
@julienrbrt julienrbrt added the backport/v0.50.x PR scheduled for inclusion in the v0.50's next stable release label Oct 11, 2024
@julienrbrt
Copy link
Member

Could you merge main?

@julienrbrt julienrbrt added this pull request to the merge queue Oct 11, 2024
Merged via the queue into cosmos:main with commit 60cbe2d Oct 11, 2024
69 of 71 checks passed
mergify bot pushed a commit that referenced this pull request Oct 11, 2024
Co-authored-by: Matt Kocubinski <[email protected]>
(cherry picked from commit 60cbe2d)

# Conflicts:
#	tests/integration/tx/aminojson/aminojson_test.go
#	x/tx/CHANGELOG.md
tac0turtle pushed a commit that referenced this pull request Oct 11, 2024
@faddat faddat mentioned this pull request Nov 8, 2024
12 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
backport/v0.50.x PR scheduled for inclusion in the v0.50's next stable release C:x/tx
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants