Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(x/tx): add custom type encoder #19786

Merged
merged 4 commits into from
Mar 27, 2024

Conversation

pinosu
Copy link
Contributor

@pinosu pinosu commented Mar 19, 2024

Description

Closes: #19785


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

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
    • Enhanced JSON marshaling for improved data handling and encoding, introducing functions to handle protoreflect.Value and []byte values more efficiently.
    • Added the ability to encode bytes as strings in the unreleased version.

@pinosu pinosu requested a review from a team as a code owner March 19, 2024 14:37
Copy link
Contributor

coderabbitai bot commented Mar 19, 2024

Walkthrough

The update introduces new functionalities in the Cosmos SDK to handle JSON marshaling for protoreflect.Value types and enhance support for inline_json encoding. These changes aim to resolve compatibility issues between different Cosmos SDK versions, specifically addressing Amino JSON representation differences that impacted signer functionality and custom type serialization.

Changes

Files Change Summary
x/tx/signing/aminojson/encoder.go Added cosmosBytesAsString function for JSON marshaling of []byte in protoreflect.Value.
x/tx/signing/aminojson/json_marshal.go Enhanced to handle inline_json encoding in aminoFieldEncoders within NewEncoder function.
x/tx/signing/aminojson/encoder_test.go Introduced TestCosmosBytesAsString function for protoreflect.Value to string conversion validation.
docs/build/building-modules/05-protobuf-annotations.md Added examples for encoding bytes as strings in amino JSON marshaler.
x/tx/CHANGELOG.md Added feature to encode bytes as strings in the unreleased version.

Assessment against linked issues

Objective Addressed Explanation
Identify breaking changes in Amino JSON representation between Cosmos SDK 0.47 and 0.50 (#19785)
Address signer breaking changes due to custom MarshalJSON implementations (#19785)
Resolve RawContractMessage marshalling issue in Amino JSON sign doc with SDK 0.50 (#19785)
Compare and reconcile expected vs. actual sign doc discrepancies due to Amino JSON changes (#19785)
Ensure compatibility in Amino JSON for message passing on Cosmos SDK 0.50 upgrade (#19785)

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-tests 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 tests 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 tests.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

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 a review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @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.
  • The JSON schema for the configuration file is available here.
  • 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/coderabbit-overrides.v2.json

CodeRabbit Discord Community

Join our Discord Community to get help, request features, and share feedback.

@kocubinski kocubinski self-assigned this Mar 19, 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.

Review Status

Actionable comments generated: 0

Configuration used: .coderabbit.yml

Commits Files that changed from the base of the PR and between 65ab253 and 47199e373767e0ee411292ad3c1c8bc5bc6ad1a4.
Files selected for processing (2)
  • x/tx/signing/aminojson/encoder.go (1 hunks)
  • x/tx/signing/aminojson/json_marshal.go (1 hunks)
Additional comments: 2
x/tx/signing/aminojson/encoder.go (1)
  • 84-93: The implementation of cosmosInlineJson appears correct and aligns with the PR's objectives to handle JSON marshaling for protoreflect.Value. It would be beneficial to add a comment detailing the specific use case or scenario where this function is expected to be utilized, enhancing clarity and maintainability.
x/tx/signing/aminojson/json_marshal.go (1)
  • 75-75: The addition of the inline_json key to the aminoFieldEncoders map, utilizing the cosmosInlineJson function, is a crucial change for addressing the PR's objectives. It's important to verify the integration and functionality of the cosmosInlineJson function within the broader context of the file and the PR's objectives to ensure proper serialization and deserialization of custom types.

// cosmosInlineJson replicates the behavior at:
// https://github.com/CosmWasm/wasmd/blob/08567ff20e372e4f4204a91ca64a371538742bed/x/wasm/types/tx.go#L20-L22
func cosmosInlineJson(_ *Encoder, v protoreflect.Value, w io.Writer) error {
blob, err := json.RawMessage(v.Bytes()).MarshalJSON()
Copy link
Member

Choose a reason for hiding this comment

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

this is a lot of machinery to just print a pre-rendered string, v.Bytes() doesn't even need to be valid json.

	raw := json.RawMessage("foo")
	bz, err := raw.MarshalJSON()
	fmt.Println(string(bz))
    => "foo"

Given this, could this encoder just be called bytes_as_string and include a type check on v protoreflect.Value (it should be bytes) similar to nullSliceAsEmptyEncoder checks that v is a List?

Copy link
Member

Choose a reason for hiding this comment

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

All of this PR is specific to Amino JSON and embedded somewhere in a JSON document. So I wonder why the emphesis on arbitrary bytes here is useful.

I don't think the naming choice "bytes_as_string" is great, because to me it sounds like adding a JSON string to the document instead of a nested JSON object. I.e. from the name it could easily mean that the bytes {"foo":123} becomes

{
  "envelope":"{\"foo\":123}"
}

instead of

{
  "envelope": {
    "foo": 123
  }
}

We need the later here, which is why I suggested inline JSON.

Copy link
Member

@julienrbrt julienrbrt Mar 28, 2024

Choose a reason for hiding this comment

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

Are you willing to open a PR with your suggestion? So it doesn't get lost here.

Copy link
Member

Choose a reason for hiding this comment

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

Yeah, I can do, no probem. Just wanted to check if there is alignment on my proposal/thinking first.

Copy link
Member

Choose a reason for hiding this comment

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

I see what you mean, and if there is a possible ambiguity, let's indeed reword it.

Copy link
Member

Choose a reason for hiding this comment

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

Great, will take a look.

Do you have an idea how I can create a simple test that shows how the field is embedded in a larger structure (similar to shown in my comment)?

Copy link
Member

Choose a reason for hiding this comment

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

Copy link
Member

Choose a reason for hiding this comment

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

Great, thank you. Will do that during or after Easter depending on family mood

Copy link
Member

Choose a reason for hiding this comment

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

Thank again! Here we go: #19919

@@ -81,6 +81,17 @@ func nullSliceAsEmptyEncoder(enc *Encoder, v protoreflect.Value, w io.Writer) er
}
}

// cosmosInlineJson replicates the behavior at:
// https://github.com/CosmWasm/wasmd/blob/08567ff20e372e4f4204a91ca64a371538742bed/x/wasm/types/tx.go#L20-L22
func cosmosInlineJson(_ *Encoder, v protoreflect.Value, w io.Writer) error {
Copy link
Member

Choose a reason for hiding this comment

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

Can we add a test for this + changelog in x/tx ?

@julienrbrt julienrbrt self-assigned this Mar 19, 2024
@julienrbrt
Copy link
Member

Could you as well add a mention of this new annotation on this page: https://docs.cosmos.network/v0.50/build/building-modules/protobuf-annotations (https://github.com/cosmos/cosmos-sdk/blob/main/docs/build/building-modules/05-protobuf-annotations.md)

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.

Review Status

Actionable comments generated: 0

Configuration used: .coderabbit.yml

Commits Files that changed from the base of the PR and between 47199e373767e0ee411292ad3c1c8bc5bc6ad1a4 and 9879ece09c58068402782fa2096199dc89a23d13.
Files selected for processing (4)
  • x/tx/CHANGELOG.md (1 hunks)
  • x/tx/signing/aminojson/encoder.go (1 hunks)
  • x/tx/signing/aminojson/encoder_test.go (1 hunks)
  • x/tx/signing/aminojson/json_marshal.go (1 hunks)
Files skipped from review as they are similar to previous changes (2)
  • x/tx/signing/aminojson/encoder.go
  • x/tx/signing/aminojson/json_marshal.go
Additional comments: 2
x/tx/signing/aminojson/encoder_test.go (1)
  • 3-49: Consider using a single assertion library (require or assert) throughout your tests for consistency. Mixing require and assert can make the test code less coherent and slightly harder to read.
x/tx/CHANGELOG.md (1)
  • 34-37: The changelog entry for the added feature is clear and correctly formatted. Great job on maintaining the changelog's readability and usefulness.

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.

Review Status

Actionable comments generated: 0

Configuration used: .coderabbit.yml

Commits Files that changed from the base of the PR and between 9879ece09c58068402782fa2096199dc89a23d13 and bf52ad80c31083c3f822ef9bd82f6fee3c77cca0.
Files selected for processing (1)
  • docs/build/building-modules/05-protobuf-annotations.md (1 hunks)
Additional comments: 2
docs/build/building-modules/05-protobuf-annotations.md (2)
  • 128-133: The addition of encoding instructions for bytes as strings using the bytes_as_string option is a valuable update for developers working with amino JSON encoding. This change clearly demonstrates how to apply this encoding option within protobuf annotations, enhancing the documentation's utility and clarity.
  • 125-133: > 📝 NOTE

This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [1-133]

Ensure that the documentation is updated to reflect the new annotation for encoding bytes as strings in the amino JSON marshaler. This addition is crucial for developers to understand how to use this specific encoding option effectively. The documentation appears to be well-structured and informative, providing valuable insights into protobuf annotations within the Cosmos SDK.

// cosmosBytesAsString replicates the behavior at:
// https://github.com/CosmWasm/wasmd/blob/08567ff20e372e4f4204a91ca64a371538742bed/x/wasm/types/tx.go#L20-L22
func cosmosBytesAsString(_ *Encoder, v protoreflect.Value, w io.Writer) error {
switch bz := v.Interface().(type) {
Copy link
Member

Choose a reason for hiding this comment

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

can this entire block be replaced with

_, err = w.Write(string(bz))
return err

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Write does not accept string , only []byte . I tried to remove the cast and it seems to work fine in wasmd ( msg is not base64 encoded)
then the function would look like this:

func cosmosBytesAsString(_ *Encoder, v protoreflect.Value, w io.Writer) error {
	switch bz := v.Interface().(type) {
	case []byte:
		_, err := w.Write(bz)
		return err
	default:
		return fmt.Errorf("unsupported type %T", bz)
	}
}

Do you agree?

Copy link
Contributor Author

@pinosu pinosu Mar 21, 2024

Choose a reason for hiding this comment

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

@kocubinski @julienrbrt I did some tests and the outputs of the two implementations are the same.
Personally I would prefer the first implementation because it is more clear and the implementation matches the one in wasmd. On the other side, the second option is much shorter so it is nice as well.
Please let me know how to proceed so I will do the needed changes. Thank you!

Copy link
Member

Choose a reason for hiding this comment

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

Sorry for the delay, please feel free to ping me in Slack if I'm not responsive on this PR.

I find below (the first implementation) confusing:

		blob, err := json.RawMessage(bz).MarshalJSON()
		if err != nil {
			return err
		}
		_, err = w.Write(blob)

There is mention of json, but bz need not even be valid json! the effect of this code is just to write bytes as a literal, with the exception that when the byte slice is nil the string literal "null" is printed.

// RawMessage is a raw encoded JSON value.
// It implements [Marshaler] and [Unmarshaler] and can
// be used to delay JSON decoding or precompute a JSON encoding.
type RawMessage []byte

// MarshalJSON returns m as the JSON encoding of m.
func (m RawMessage) MarshalJSON() ([]byte, error) {
	if m == nil {
		return []byte("null"), nil
	}
	return m, nil
}

I don't want to be overly pedantic here either, since as you say either will produce the same results. Given that I'll approve as is.

Copy link
Member

Choose a reason for hiding this comment

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

There is mention of json, but bz need not even be valid json! the effect of this code is just to write bytes as a literal

The code you are referencing requires bytes to be valid JSON which is enforced in a different part of the code:

func (r *RawContractMessage) ValidateBasic() error {
	if r == nil {
		return ErrEmpty
	}
	if !json.Valid(*r) {
		return ErrInvalid
	}
	return nil
}

So yeah, it is technically possible for a RawContractMessage instance to contain invalid JSON. But every valid usage of that type must perform this check and can then make assumptions on JSON validity later on. I with this was guaranteed at type level instead of app logic levels but this is not how json.RawMessage work and creating a custom "valid JSON" type seemed to be a bit overkill and not idiomatic.

@pinosu pinosu force-pushed the pinosu/inline-json-fix branch from bf52ad8 to 1e3a6f6 Compare March 26, 2024 14:27
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.

Review Status

Actionable comments generated: 0

Configuration used: .coderabbit.yml

Commits Files that changed from the base of the PR and between 6e9528a and 1e3a6f6.
Files selected for processing (5)
  • docs/build/building-modules/05-protobuf-annotations.md (1 hunks)
  • x/tx/CHANGELOG.md (1 hunks)
  • x/tx/signing/aminojson/encoder.go (1 hunks)
  • x/tx/signing/aminojson/encoder_test.go (1 hunks)
  • x/tx/signing/aminojson/json_marshal.go (1 hunks)
Files skipped from review as they are similar to previous changes (3)
  • x/tx/signing/aminojson/encoder.go
  • x/tx/signing/aminojson/encoder_test.go
  • x/tx/signing/aminojson/json_marshal.go
Additional comments: 2
docs/build/building-modules/05-protobuf-annotations.md (1)
  • 128-133: The addition of encoding instructions for bytes as strings using the bytes_as_string option is a valuable update for users needing this specific encoding behavior. However, it would enhance clarity to include a brief explanation or example of when this encoding might be necessary or beneficial.
x/tx/CHANGELOG.md (1)
  • 36-36: The changelog entry for adding the option to encode bytes as strings is clear and includes the necessary pull request link. It's important to ensure that this entry follows the project's standards for changelog entries, including the level of detail and formatting. If there are any additional impacts or considerations related to this change that could affect users, it might be helpful to include those details here for completeness.

@kocubinski kocubinski added this pull request to the merge queue Mar 27, 2024
Merged via the queue into cosmos:main with commit 39808e0 Mar 27, 2024
57 of 60 checks passed
@@ -31,6 +31,10 @@ Ref: https://keepachangelog.com/en/1.0.0/

## [Unreleased]

### Features
Copy link
Member

@julienrbrt julienrbrt Mar 27, 2024

Choose a reason for hiding this comment

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

Shall we prepare x/tx v0.13.2 / v0.14 now or do we have anything related to protov2 / gogo to get in before?
cc @kocubinski

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.

[Bug]: Amino JSON representation changed between cosmos-sdk 0.47 and 0.50
4 participants